SlideShare a Scribd company logo
PHP security audits
Assess your code for security<script>alert(‘XSS’..
Agenda


How to run an audit
Scouting the PHP code
Organizing for security
Speaker


 Damien Seguy
 Raise elePHPants
 damien.seguy@alterway.fr
Yes,
we take
questions
PHP code audits

Interview with the developpers : 1 day
Black Box testing              : 1 day
Open Code audit               : 2 days
Report and review              : 1 day
The application
  http://www.cligraphcrm.com/
Interviewing developpers


 Review what the application does
 Explain the code organization
 Explain the security features
Review the application


 Best : have a non-programmer explain the application
 Then have the programmer explain again
   The differences are interesting
Killer question
 What is the most important asset to secure on the site?
   «everything» is not an answer
 data destruction
 data exportation
 client separation
 company image
How was the app secured?


Where are the security functions?
How are they applied?
How do you check how they are applied ?
I like to hear...

 Out of web folder
 Automated deployement
 Automated tests AND manuals tests
 Security as a layer (functions and application)
Black Box testing
 Test from the outside
 Search the engines
 Session usurpation
 Disclosed files
 Displayed errors
 Tools : Rats, nikto, Wapiti
Open Code audits

What to search for?
What are the entry points?
How can they be exploited
  Or protected ?
What to search for?

  Injections
    PHP
    SQL
    HTML
    system
    HTTP
Keep focused


               Easy to loose focus
               Tempting to audit
               everything
PHP injections

PHP injections
  include, require and *_once
  back ticks ` `
  eval(‘’)
Using variables
Looking for eval
 Easy to look for
 grep
   Fast, available, convenient
   853 occurences
 Tokenizer
   Semantic, accurate
   37 occurrences
Tokenizer
<?php print ("hello $world! "); ?>
  [1] => Array
      (                   [6] => Array
          [0] => 266          (
          [1] => print            [0] => 309
          [2] => 1                [1] => $world
      )                           [2] => 1
                              )
  [2] => Array
      (                   [7] => Array
          [0] => 370          (
          [1] =>                  [0] => 314
          [2] => 1                [1] => !
      )                           [2] => 1
                              )
  [3] => (
  [4] => "                [8] => "
  [5] => Array            [9] => )
      (                   [10] => ;
           [0] => 314              [1] => Array
           [1] => hello                (
           [2] => 1                         [0] => PHP token
      )                                     [1] => PHP code
                                            [2] => Script line
                                       )
                                   [2] => "
Evals

◦ eval('$retour=$GLOBALS["'.$matches[1].'"];')
  ◦ Variable variables.
◦ eval($contenu_thjipk);
◦ eval($contents_essai);
  ◦ Content is read into variable, then executed : an include?
◦ eval('$hexdtime = "'.$hexdtime.'";')
  ◦ Long way to cast a string into a string
◦ eval('$retour2.= '.var_dump($recept->erreur).';')
  ◦ This doesn’t even make sense...
Assessing the code

One liners
  One line of code is sufficiently to be bad
Even though
  you must follow the code
  In reverse
Inclusion
◦ require("../params_frm.php")
◦ require(fct_lien_page_custom(TYPE_DOMAINE."/".TYPE_DOC.
  "_custom.php","abs"))
◦ require(fct_lien_page_custom("params_footer.php","abs"))
  ◦ Pretty secure inclusions

◦ But 96 variables used in includes
◦ include(fct_lien_page_custom("action/facture_".
  $format.".php","abs"))
  ◦ $format, anyone?
◦ require_once("etat_simple_".$choix_page."_trt.php")
  ◦ $choix_page, anyone ?
$format ?
<?php require("../params_trt.php");

$format=htmlentities($_REQUEST['exp_formdoc']);
if(empty($_REQUEST['exp_affiche'])) $affichage=0; 
  else $affichage=$_REQUEST['exp_affiche'];
if(empty($_REQUEST['exp_stockdoc'])) $stockage=0; 
  else $stockage=$_REQUEST['exp_stockdoc'];
$cde_id=$_REQUEST['exp_id'];
$type_doc=$_REQUEST['exp_typedoc'];

require(fct_lien_page_custom("fonctions/fonction_img.php","abs"));

include(fct_lien_page_custom("action/facture_".
$format.".php","abs"));
?>
$choix_format ?
  switch($choix) {
    case 0 : $choix_page="tabl";
    break;
    case 1 : $choix_page="histo1"; 
           if ($gfx_sens_graph=="1") $gfx_margegauche_dft="90";
    break;
    case 2 : $choix_page="histo2"; 
           if ($gfx_sens_graph=="1") $gfx_margegauche_dft="90";
    break;
    case 3 : $choix_page="histo3"; 
           if ($gfx_sens_graph=="1") $gfx_margegauche_dft="90";
    break;
    case 4 : $choix_page="histo4"; 
           if ($gfx_sens_graph=="1") $gfx_margegauche_dft="90";
    break;
    } ###...Way below

    require_once("etat_simple_".$choix_page."_trt.php");
Statistical audit


 Extract one type of information
 Review it out of context
 Use this as a starting point for more questions
Comments
//echo "<div><a class="texte1" style=...
#echo "<pre>";
  Left overs : what were they for?
#print_r($_REQUEST);
  No organization for bugs?
// hack for mozilla sunbird's extra = signs
Look for swearing, TODO, hack
Variables
 6883 different variables names
 All one possible one letter variable
 32 chars : $cache_maxsize_UTF8StringToArray
 Most used : $i (2586 times)
 $_1904, $samedi, $dummy, $sss, 19 $unknowns
 711 variables used only once in the code
Other interesting ideas
 name of functions
 name of classes
 name of constants
 literal
    strings, numbers
 Condition (if, while)
register_globals strikes back
register_globals strikes back


 Don’t use register globals!!
register_globals strikes back


 Don’t use register globals!!
 How can you emulate this behavior?
register_globals strikes back
register_globals strikes back

 foreach and $$
register_globals strikes back

 foreach and $$
 extract
register_globals strikes back

 foreach and $$
 extract
 import_request_var
register_globals strikes back

 foreach and $$
 extract
 import_request_var
 $GLOBALS
register_globals strikes back

 foreach and $$
 extract
 import_request_var
 $GLOBALS
 parse_str
Found!

◦ ./install/identification.php
◦ extract($_POST)  : 1
  ◦ Injection by $_POST


◦ ./fonctions/fonctions_gen.php
◦ $GLOBALS[$k] = $chaine[$k]
◦ $GLOBALS[$this->mode] [$k] = $chaine[$k]

  ◦ In the fct_urldecode, the values are stripslashed, and
     then injected in the $GLOBALS, resulting in variable creation
SQL injections	

 Point of entry
   mysql_query
   mysqli_real_escape_string
   SQL query :
     string with SELECT, UPDATE, ...
Found!
◦ 'UPDATE param_suivi SET      param_suivi_nom="'.str_replace($tr
  ansf_sp,$transf_fr,$_POST["suivi_nom"])  : 1
  ◦ Direct injection via POST

◦ WHERE campagne_nom LIKE '%".addslashes($_REQUEST['rech_nom']) 
  ◦ Injection from $_REQUEST

◦ "UPDATE even_spl SET even_spl_fait='".
  $even_fait."',even_spl_modification='".$date_du_jour."'    
  WHERE even_spl_id='".$even_id."' AND even_spl_affaire_id='".
  $even_aff_id."'";  : 1

◦ "INSERT INTO ".$type_doc."_suivi    (".
  $type_doc."_suivi_param_suivi_id, ".$type_doc."_suivi_".
  $type_doc."_id, ".$type_doc."_suivi_canal_id,    ".
  $type_doc."_suivi_action, ".$type_doc."_suivi_commentaire, ".
  $type_doc."_suivi_creation)    VALUES ('".$id_suivi."', '".
  $id_doc."', '".$id_canal."', '".
  $suivi_date."', '".addslashes($suivi_commentaire)
And also
Header injection
  Look for header()
XSS
  look for echo, print
  look for strings with tags
Etc...
Report
Executive summary
  3 paragraphs, simple to read
Problems summary
  Table, with problems, criticality and load
Details
Extras
Report
 Vulnerability     Critical    Load

register_globals    High       High

   Injections       High      Medium

 SQL injection     Medium      High

   headers          Low        Low
Details
 Title
 In code example and explanation
 Protection suggestions
   Limitations
 List of all occurrences
   Or way to find them
Team Work
Security is recommanded at conception time
Audit is an after-thought tool
  Once
  When necessary
  Regularly
  Continuously
PHP Mantra


List your mantra
The five most important rules you agree upon
Have them printed and visible to everyone
Cross audit

Group developers by two
  Have each one review the code of the other
  Based on the mantra
Light weight process
Doesn’t have to be in the same project
PHP audit tools

Groogle (http://groogle.sourceforge.net)
Review Board (http://www.review-board.org/)
Rietveld http://codereview.appspot.com/
SmartBear (http://www.smartbear.com/)
Community step up

Mantra, cross audits
  go beyond services and departements
Open this outside ?
  External review?
New way of coding ?
Questions?
damien.seguy@alterw
ay.fr

More Related Content

PDF
Php Security
PPT
PHP Security
PPS
PHP Security
PPS
Php Security3895
ODP
Concern of Web Application Security
PPT
Php Security By Mugdha And Anish
PDF
Php tips-and-tricks4128
ODP
My app is secure... I think
Php Security
PHP Security
PHP Security
Php Security3895
Concern of Web Application Security
Php Security By Mugdha And Anish
Php tips-and-tricks4128
My app is secure... I think

What's hot (18)

PPTX
Creating "Secure" PHP Applications, Part 1, Explicit Code & QA
ODP
My app is secure... I think
PDF
Dependency Injection with PHP 5.3
PDF
Symfony2 - OSIDays 2010
PDF
PhpBB meets Symfony2
PPTX
New in php 7
PDF
The state of Symfony2 - SymfonyDay 2010
PDF
What's new with PHP7
PDF
Symfony2 - WebExpo 2010
ODP
My app is secure... I think
PDF
&lt;img src="../i/r_14.png" />
PDF
Review unknown code with static analysis Zend con 2017
PDF
Data Validation models
PPT
PDF
Frontin like-a-backer
PDF
Building a Pyramid: Symfony Testing Strategies
PDF
QA for PHP projects
ODP
My app is secure... I think
Creating "Secure" PHP Applications, Part 1, Explicit Code & QA
My app is secure... I think
Dependency Injection with PHP 5.3
Symfony2 - OSIDays 2010
PhpBB meets Symfony2
New in php 7
The state of Symfony2 - SymfonyDay 2010
What's new with PHP7
Symfony2 - WebExpo 2010
My app is secure... I think
&lt;img src="../i/r_14.png" />
Review unknown code with static analysis Zend con 2017
Data Validation models
Frontin like-a-backer
Building a Pyramid: Symfony Testing Strategies
QA for PHP projects
My app is secure... I think
Ad

Similar to PHP security audits (20)

KEY
Php Code Audits (PHP UK 2010)
PDF
PHP Static Code Review
PDF
Internationalizing CakePHP Applications
PDF
PHP tips and tricks
PPTX
Meet Magento Belarus debug Pavel Novitsky (eng)
KEY
Workshop quality assurance for php projects tek12
PDF
Quality Assurance for PHP projects - ZendCon 2012
PDF
PDF
前端MVC之BackboneJS
PDF
Workshop quality assurance for php projects - phpbelfast
PDF
Python fundamentals - basic | WeiYuan
KEY
FizzBuzzではじめるテスト
PDF
Automated code audits
KEY
Scaling php applications with redis
PDF
Workshop quality assurance for php projects - ZendCon 2013
PPT
Windows Server 2008 (PowerShell Scripting Uygulamaları)
PDF
Unit testing with zend framework tek11
PPT
presentation on java server pages vs servlet.ppt
PPT
Presentation
PPTX
Substitution Cipher
Php Code Audits (PHP UK 2010)
PHP Static Code Review
Internationalizing CakePHP Applications
PHP tips and tricks
Meet Magento Belarus debug Pavel Novitsky (eng)
Workshop quality assurance for php projects tek12
Quality Assurance for PHP projects - ZendCon 2012
前端MVC之BackboneJS
Workshop quality assurance for php projects - phpbelfast
Python fundamentals - basic | WeiYuan
FizzBuzzではじめるテスト
Automated code audits
Scaling php applications with redis
Workshop quality assurance for php projects - ZendCon 2013
Windows Server 2008 (PowerShell Scripting Uygulamaları)
Unit testing with zend framework tek11
presentation on java server pages vs servlet.ppt
Presentation
Substitution Cipher
Ad

More from Damien Seguy (20)

PDF
Strong typing @ php leeds
PPTX
Strong typing : adoption, adaptation and organisation
PDF
Qui a laissé son mot de passe dans le code
PDF
Analyse statique et applications
PDF
Top 10 pieges php afup limoges
PDF
Top 10 php classic traps DPC 2020
PDF
Meilleur du typage fort (AFUP Day, 2020)
PDF
Top 10 php classic traps confoo
PDF
Tout pour se préparer à PHP 7.4
PDF
Top 10 php classic traps php serbia
PDF
Top 10 php classic traps
PDF
Top 10 chausse trappes
PDF
Code review workshop
PDF
Understanding static analysis php amsterdam 2018
PDF
Review unknown code with static analysis php ce 2018
PDF
Everything new with PHP 7.3
PDF
Php 7.3 et ses RFC (AFUP Toulouse)
PDF
Tout sur PHP 7.3 et ses RFC
PDF
Review unknown code with static analysis php ipc 2018
PDF
Code review for busy people
Strong typing @ php leeds
Strong typing : adoption, adaptation and organisation
Qui a laissé son mot de passe dans le code
Analyse statique et applications
Top 10 pieges php afup limoges
Top 10 php classic traps DPC 2020
Meilleur du typage fort (AFUP Day, 2020)
Top 10 php classic traps confoo
Tout pour se préparer à PHP 7.4
Top 10 php classic traps php serbia
Top 10 php classic traps
Top 10 chausse trappes
Code review workshop
Understanding static analysis php amsterdam 2018
Review unknown code with static analysis php ce 2018
Everything new with PHP 7.3
Php 7.3 et ses RFC (AFUP Toulouse)
Tout sur PHP 7.3 et ses RFC
Review unknown code with static analysis php ipc 2018
Code review for busy people

Recently uploaded (20)

PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Machine learning based COVID-19 study performance prediction
PPTX
Cloud computing and distributed systems.
PDF
Encapsulation theory and applications.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
cuic standard and advanced reporting.pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Spectroscopy.pptx food analysis technology
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Network Security Unit 5.pdf for BCA BBA.
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Machine learning based COVID-19 study performance prediction
Cloud computing and distributed systems.
Encapsulation theory and applications.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
cuic standard and advanced reporting.pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
20250228 LYD VKU AI Blended-Learning.pptx
Understanding_Digital_Forensics_Presentation.pptx
Encapsulation_ Review paper, used for researhc scholars
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Spectroscopy.pptx food analysis technology
The AUB Centre for AI in Media Proposal.docx
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
Network Security Unit 5.pdf for BCA BBA.

PHP security audits