SlideShare a Scribd company logo
1 of 44
Download to read offline
Web Application Security (PHP)
Zakieh Alizadeh
zakiehalizadeh@gmail.com
APA Laboratory – Ferdowsi University of Mashhad
Session 9
Path traversal & File Inclusion
Path traversal & File Inclusion
Scenario
 Preventing Path traversal & File Inclusion in College Library
Website
 Table Of Content
 File System Concept
o Permissions
 Path traversal & File Inclusion
 Introducing Risk Factors of File Uploads
 Weak Protection Methods
 Countermeasure
Path traversal & File Inclusion
File System Concept
Path traversal & File Inclusion
Introducing Risk Factors of File Uploads
Weak Protection Methods
Countermeasure
File System Concept
File System Concept
 The filesystem is the view of your disks as seen by your operating system.
For example: in a default install, Apache httpd resides at
o Unix Filesestem : /usr/local/apache2
o Windows filesystem "c:/Program Files/Apache Group/Apache2“ .
File System Concept
Filesystem Structure
 Directory: same as windows directories
 Filesystem: same as windows drives
 Windows: C:, D:, …
 Linux: /
File System Concept
 Directory vs Filesystem
 Directory: same as windows directories
 Filesystem: same as windows drives
File System Concept
Filesystem Structure
File System Concept
Filesystem
 Windows: FAT, FAT32, NTFS
 Linux: ext2, ext3, ext4,
File System Concept
Filesystem
File System Concept
 File Permissions
 Note : The user is not the person who is logged into your application - that, and their role in the
application (admin, etc) is completely irrelevant to the scenario.
 The user is the linux system user that the process runs under. The code of your website is run as
only one user - it may be the user of your webserver (which isn't really a good thing), or it may
be a user specific to your site (which is much better).
Permissions Users Example
Read: r
Write: w
Execute: x
User: u
Group: g
Other: o
u+w: User can write
g-x: Group can not
execute
o-r: Others can not
read
File System Concept
File Permissions
Numerical Representation Example
Read: r = 4
Write: w = 2
Execute: x = 1
4
2
1
rwx = 7
r-x = 5
r-- = 1
File System Concept
File Permissions
 Permission 754 is: rwxr-xr--
Numerical Representation Numeric
User: can read, write and execute USER == > rwx=4+2+1=7
Group: can read and execute Group== > rwx=4+0+1=5
Others: just can read Others== > rwx=4+0+0=4
File System Concept
File Permissions
Permision Numeric
aplication owner =600 uploads/
user-Grroup-Other = 600
File System Concept
Webspace Concept
 the webspace is the view of your site as delivered by the web server and
seen by the client.
 So the path /dir/ in the webspace corresponds to the path
/usr/local/apache2/htdocs/dir/ in the filesystem of a default Apache
httpd install on Unix.
 The webspace need not map directly to the filesystem, since webpages
may be generated dynamically from databases or other locations.
Path traversal & File Inclusion
File System Concept
Path traversal & File Inclusion
Introducing Risk Factors of File Uploads
Weak Protection Methods
Countermeasure
Path traversal & File Inclusion
 File Upload
 File upload helps in increasing your business efficiency.
 File uploads are allowed in social network web applications, such as
Facebook and Twitter. They are also allowed in blogs, forums, e-banking
sites, YouTube and also in corporate support portals, to give the
opportunity to the end user to efficiently share files with corporate
employees.
 The more functionality provided to the end user, the greater is the risk of
having a vulnerable web application
Path traversal & File Inclusion
 File Upload
 When PHP receives a POST request with encoding type multipart/form-data, it will create a temporary
file with a random name in a temp directory (e.g. /var/tmp/php6yXOVs). PhP will also populate the
global array $_FILES with the information about the uploaded file:
o $_FILES[‘uploadedfile’][‘name’]: The original name of the file on the client machine
o $_FILES[‘uploadedfile’][‘type’]: The mime type of the file
o $_FILES[‘uploadedfile’][‘size’]: The size of the file in bytes
o $_FILES[‘uploadedfile’][‘tmp_name’]: The temporary filename in which the uploaded file was
stored on the server.
Path traversal & File Inclusion
 Why File Upload Forms are a Major Security Threat?
 The first step in many attacks is to get some code to the system to be
attacked. Then the attack only needs to find a way to get the code
executed. Using a file upload helps the attacker accomplish the first step.
 The consequences of unrestricted file upload can vary, including
complete system takeover, an overloaded file system, forwarding attacks
to backend systems, and simple defacement. It depends on :
o what the application does with the uploaded file
o including where it is stored
Path traversal & File Inclusion
 Why File Upload Forms are a Major Security Threat?
 There are really two different classes of problems in File upload forms:
 File metadata(path , filename)
o The term metadata refers to "data about data".
o Example of threat :storing the file in a bad location.
 File content
o The range of problems here depends entirely on what the file is used
for
Path traversal & File Inclusion
File System Concept
Path traversal & File Inclusion
Introducing Risk Factors of File Uploads
Weak Protection Methods
Countermeasure
Risk Factors
Risk Factors
 The impact of this vulnerability is high but the likelihood is low. So, the
severity of this type of vulnerability is Medium.
 The website can be defaced.
 The web server can be compromised by uploading and executing a web-shell
which can:
o run a command
o browse the system files
o browse the local resources
o attack to other servers
Risk Factors
Risk Factors
 An attacker might be able to put a phishing page into the website.
 Local file inclusion vulnerabilities can be exploited by uploading a
malicious file into the server.
 A malicious file can be uploaded on the server in order to have a chance
to be executed by administrator or webmaster later.
Path traversal & File Inclusion
File System Concept
Path traversal & File Inclusion
Introducing Risk Factors of File Uploads
Weak Protection Methods
Countermeasure
Weak Protection Methods
Weak Protection Methods
 Using Black-List for Files’ Extensions
 Using White-List for Files’ Extensions
 Using “Content-Type” from the Header
 Using a File Type Recogniser
Weak Protection Methods
Attacks on application platform
 Upload .gif to be resized - image library flaw exploited
 Upload huge files - file space denial of service
 Upload file using malicious path or name - overwrite critical file
 Upload file containing personal data - other users access it
 Upload file containing "tags" - tags get executed as part of being
"included" in a web page
Weak Protection Methods
Using Black-List for Files’ Extensions
 Bypass by changing some letters of extension to the capital form
(example: “file.aSp” or “file.PHp3”).
 Using trailing spaces and/or dots at the end of the These spaces and/or
dots at the end of the filename will be removed when the file wants to be
saved on the hard disk automatically (example: “file.asp ... ... . . .. ..”,
“file.asp ”, or “file.asp.”).
 A web-server may use the first extension after the first dot (“.”) in the file
name (example: “file.php.jpg”).
Weak Protection Methods
Using Black-List for Files’ Extensions
 This protection can be completely bypassed by using the most famous
control character. (example: “file.asp%00.jpg”)
Weak Protection Methods
Using White-List for Files’ Extensions
 Although using white-list is one of the recommendations, it is not enough
on its own. Without having input validation:
o A web-server may use the first extension after the first dot (“.”) in the
file name .(example: “file.php.jpg”).
o Using trailing spaces and/or dots at the end of the These spaces
and/or dots at the end of the filename will be removed when the file
wants to be saved on the hard disk automatically (example: “file.asp ...
... . . .. ..”, “file.asp ”, or “file.asp.”).
Weak Protection Methods
Using “Content-Type” from the Header
 “Content-Type” entity in the header of the request indicates the Internet
media t
o It is possible to bypass this protection by changing this parameter in
the request header by using a local proxy.
Weak Protection Methods
Using a File Type Recogniser
 use some functions (or APIs) to check the type of the file in order to do
further process. For instance, in case of having image resizing, it is
probable to have image type recogniser.
o Sometimes the recognisers just read the few first characters (or
header) of the files .(malicious code after some valid header)
o There are always some places in the structure of the files which are for
the comments section and have no effect on the main file. And, an
attacker can insert malicious codes in these points.
o
Weak Protection Methods
Prevention Methods : File Meta Data
 It is necessary to have a list of only permitted extensions on the web
application. And, file extension should be selected from the list. Use your
extention instead user input extention of file.
Path traversal & File Inclusion
File System Concept
Path traversal & File Inclusion
Introducing Risk Factors of File Uploads
Weak Protection Methods
Countermeasure
Countermeasure
Prevention Methods : File Meta Data
 All the control characters and Unicode ones should be removed from the
filenames.
 Also, the special characters such as “;”, “:”, “>”, “<”, “/” ,””, additional “.”,
“*”, “%”, “$”, and so on should be discarded as well
 recommended to only accept (regular expression: [a-zA-Z0-9]{1,200}.[a-
zA-Z0-9]{1,10}).
 Always Check both forward slashes and backslashes. May the file system
may support both.
Countermeasure
Prevention Methods : File Meta Data
 Awarefrom Encoding:
Countermeasure
 Prevention Methods : File Meta Data
 Limit the filename length.
 Try to use POST method instead of PUT (or GET!)
 Prevent from overwriting a file in case of having the same hash for both.
 Create a list of accepted mime-types (map extensions from these mime types).
 Log users’ activities. However, the logging mechanism should be secured against log
forgery and code injection itself.
Countermeasure
 Prevention Methods : File content
 Use Cross Site Request Forgery protection methods.
 Restrict small size files as they can lead to denial of service attacks.
 Generate a random file name and add the previously generated extension.
 Limit the file size to a maximum value in order to prevent denial of service attacks.
 In case of having compressed file extract functions, contents of the compressed file
should be checked one by one as a new file.
Countermeasure
 Prevention Methods : File content
 use an algorithm to determine the filenames. For instance, a filename can be a MD5
hash of the name of file plus the date of the day.
 Prevent from overwriting a file in case of having the same hash for both.
o PHP Function :
• hash_file : Generate a hash value using the contents of a given file
• sha1_file: Calculate the sha1 hash of a file
Countermeasure
 Prevention Methods : File content
 Uploaded directory should not have any “execute” permission.
 If possible, upload the files in a directory outside the server root.
 Prevent overwriting of existing files (to prevent the .htaccess overwrite attack).
 Use an absolute path to point exactly where you want to store/retrieve the file from.
 For downloads you will need to write a simple script which dumps the file to the
browser after doing some authentication checks.
Countermeasure
 Prevention Methods : upload file Directory
 Define a .htaccess file that will only allow access to files with allowed extensions.
o Config server to avoide owerriting .htaccess
o Do not place the .htaccess file in the same directory where the uploaded files will be
stored. It should be placed in the parent directory.
o A typical .htaccess which allows only gif, jpg, jpeg and png files should include the
following (adapt it for your own need). This will also prevent double extension attacks.
deny from all
<Files ~ "^w+.(gif|jpe?g|png)$">
order deny,allow
allow from all
</Files>
Countermeasure
 Prevention Methods : upload file Directory
 Prevent from directory listting. If you create a new directory (or folder) on your website, and do not put
an "index.html" file in it, you may be surprised to find that your visitors can get a directory listing of all
the files in that folder.
 For example, if you create a folder called "incoming", you can see everything in that directory simply by
typing "http://www.example.com/incoming/" in your browser. No password or anything is needed.
 Add the following line to your .htaccess file. in this folder:
Options -Indexes
Countermeasure
 Prevention Methods : PHP Functions
 Use file_info
 This extension is enabled by default as of PHP 5.3.0. Before this time, fileinfo was a PECL
extension but is no longer maintained there.
 For instalation
o Windows users: just edit php.ini and uncomment this line:
extension=php_fileinfo.dll
Countermeasure
 Prevention Methods : PHP Functions
 Fileinfo Functions
o finfo_buffer — Return information about a string buffer
o finfo_close — Close fileinfo resource
 finfo_file — Return information about a file
o finfo_open — Create a new fileinfo resource
o finfo_set_flags— Set libmagic configuration options
o mime_content_type — Detect MIME Content-type for a file (deprecated)
Path traversal & File Inclusion

More Related Content

What's hot

Web application security
Web application securityWeb application security
Web application securityKapil Sharma
 
Intro to Web Application Security
Intro to Web Application SecurityIntro to Web Application Security
Intro to Web Application SecurityRob Ragan
 
Methods to Bypass a Web Application Firewall Eng
Methods to Bypass a Web Application Firewall EngMethods to Bypass a Web Application Firewall Eng
Methods to Bypass a Web Application Firewall EngDmitry Evteev
 
Application Security Vulnerabilities: OWASP Top 10 -2007
Application Security Vulnerabilities: OWASP Top 10  -2007Application Security Vulnerabilities: OWASP Top 10  -2007
Application Security Vulnerabilities: OWASP Top 10 -2007Vaibhav Gupta
 
Owasp Top 10 - Owasp Pune Chapter - January 2008
Owasp Top 10 - Owasp Pune Chapter - January 2008Owasp Top 10 - Owasp Pune Chapter - January 2008
Owasp Top 10 - Owasp Pune Chapter - January 2008abhijitapatil
 
Common Web Application Attacks
Common Web Application Attacks Common Web Application Attacks
Common Web Application Attacks Ahmed Sherif
 
Web application attacks
Web application attacksWeb application attacks
Web application attackshruth
 
OWASP Secure Coding Practices - Quick Reference Guide
OWASP Secure Coding Practices - Quick Reference GuideOWASP Secure Coding Practices - Quick Reference Guide
OWASP Secure Coding Practices - Quick Reference GuideLudovic Petit
 
Sql injection bypassing hand book blackrose
Sql injection bypassing hand book blackroseSql injection bypassing hand book blackrose
Sql injection bypassing hand book blackroseNoaman Aziz
 
Web application sec_3
Web application sec_3Web application sec_3
Web application sec_3vhimsikal
 
Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)Brian Huff
 
Secure code practices
Secure code practicesSecure code practices
Secure code practicesHina Rawal
 
Application security 101
Application security 101Application security 101
Application security 101Vlad Garbuz
 
DVWA BruCON Workshop
DVWA BruCON WorkshopDVWA BruCON Workshop
DVWA BruCON Workshoptestuser1223
 
Hacking web applications
Hacking web applicationsHacking web applications
Hacking web applicationsAdeel Javaid
 
AppSec 2007 - .NET Web Services Hacking
AppSec 2007 - .NET Web Services HackingAppSec 2007 - .NET Web Services Hacking
AppSec 2007 - .NET Web Services HackingShreeraj Shah
 
DVWA(Damn Vulnerabilities Web Application)
DVWA(Damn Vulnerabilities Web Application)DVWA(Damn Vulnerabilities Web Application)
DVWA(Damn Vulnerabilities Web Application)Soham Kansodaria
 
PCI security requirements secure coding and code review 2014
PCI security requirements   secure coding and code review 2014PCI security requirements   secure coding and code review 2014
PCI security requirements secure coding and code review 2014Haitham Raik
 

What's hot (20)

Web application security
Web application securityWeb application security
Web application security
 
Intro to Web Application Security
Intro to Web Application SecurityIntro to Web Application Security
Intro to Web Application Security
 
Methods to Bypass a Web Application Firewall Eng
Methods to Bypass a Web Application Firewall EngMethods to Bypass a Web Application Firewall Eng
Methods to Bypass a Web Application Firewall Eng
 
Application Security Vulnerabilities: OWASP Top 10 -2007
Application Security Vulnerabilities: OWASP Top 10  -2007Application Security Vulnerabilities: OWASP Top 10  -2007
Application Security Vulnerabilities: OWASP Top 10 -2007
 
Owasp Top 10 - Owasp Pune Chapter - January 2008
Owasp Top 10 - Owasp Pune Chapter - January 2008Owasp Top 10 - Owasp Pune Chapter - January 2008
Owasp Top 10 - Owasp Pune Chapter - January 2008
 
Common Web Application Attacks
Common Web Application Attacks Common Web Application Attacks
Common Web Application Attacks
 
Web application attacks
Web application attacksWeb application attacks
Web application attacks
 
OWASP Secure Coding Practices - Quick Reference Guide
OWASP Secure Coding Practices - Quick Reference GuideOWASP Secure Coding Practices - Quick Reference Guide
OWASP Secure Coding Practices - Quick Reference Guide
 
Sql injection bypassing hand book blackrose
Sql injection bypassing hand book blackroseSql injection bypassing hand book blackrose
Sql injection bypassing hand book blackrose
 
Web application sec_3
Web application sec_3Web application sec_3
Web application sec_3
 
Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)Top 10 Web Security Vulnerabilities (OWASP Top 10)
Top 10 Web Security Vulnerabilities (OWASP Top 10)
 
Secure code practices
Secure code practicesSecure code practices
Secure code practices
 
Application security 101
Application security 101Application security 101
Application security 101
 
DVWA BruCON Workshop
DVWA BruCON WorkshopDVWA BruCON Workshop
DVWA BruCON Workshop
 
Hacking web applications
Hacking web applicationsHacking web applications
Hacking web applications
 
AppSec 2007 - .NET Web Services Hacking
AppSec 2007 - .NET Web Services HackingAppSec 2007 - .NET Web Services Hacking
AppSec 2007 - .NET Web Services Hacking
 
Cyber ppt
Cyber pptCyber ppt
Cyber ppt
 
Owasp first5 presentation
Owasp first5 presentationOwasp first5 presentation
Owasp first5 presentation
 
DVWA(Damn Vulnerabilities Web Application)
DVWA(Damn Vulnerabilities Web Application)DVWA(Damn Vulnerabilities Web Application)
DVWA(Damn Vulnerabilities Web Application)
 
PCI security requirements secure coding and code review 2014
PCI security requirements   secure coding and code review 2014PCI security requirements   secure coding and code review 2014
PCI security requirements secure coding and code review 2014
 

Similar to Session9-File Upload Security

"15 Technique to Exploit File Upload Pages", Ebrahim Hegazy
"15 Technique to Exploit File Upload Pages", Ebrahim Hegazy"15 Technique to Exploit File Upload Pages", Ebrahim Hegazy
"15 Technique to Exploit File Upload Pages", Ebrahim HegazyHackIT Ukraine
 
Php File Upload
Php File UploadPhp File Upload
Php File Uploadsaeel005
 
File System Interface
File System InterfaceFile System Interface
File System InterfaceAmir Payberah
 
File management53(1)
File management53(1)File management53(1)
File management53(1)myrajendra
 
Secure Code Warrior - Local file inclusion
Secure Code Warrior - Local file inclusionSecure Code Warrior - Local file inclusion
Secure Code Warrior - Local file inclusionSecure Code Warrior
 
Tricorder: Diagnose and heal your software (without science fiction)
Tricorder: Diagnose and heal your software (without science fiction)Tricorder: Diagnose and heal your software (without science fiction)
Tricorder: Diagnose and heal your software (without science fiction)Davide Tampellini
 
File Management and manipulation in C++ Programming
File Management and manipulation in C++ ProgrammingFile Management and manipulation in C++ Programming
File Management and manipulation in C++ ProgrammingChereLemma2
 
File system interface
File system interfaceFile system interface
File system interfaceDayan Ahmed
 
Privileged file operations_bug_on_windows
Privileged file operations_bug_on_windowsPrivileged file operations_bug_on_windows
Privileged file operations_bug_on_windowsSai Lay
 
7.Canon & Dt
7.Canon & Dt7.Canon & Dt
7.Canon & Dtphanleson
 
Directory_Traversel.pdf
Directory_Traversel.pdfDirectory_Traversel.pdf
Directory_Traversel.pdfOkan YILDIZ
 
File handling4.pdf
File handling4.pdfFile handling4.pdf
File handling4.pdfsulekha24
 
Learn about the File Concept in operating systems ppt
Learn about the File Concept in operating systems pptLearn about the File Concept in operating systems ppt
Learn about the File Concept in operating systems pptgeethasenthil2706
 
file management_osnotes.ppt
file management_osnotes.pptfile management_osnotes.ppt
file management_osnotes.pptHelalMirzad
 
File Handling
File HandlingFile Handling
File HandlingWaqar Ali
 
IIS Critical Vulnerability 23/12/09
IIS Critical Vulnerability 23/12/09IIS Critical Vulnerability 23/12/09
IIS Critical Vulnerability 23/12/09shlominar
 
Chapter 10 - File System Interface
Chapter 10 - File System InterfaceChapter 10 - File System Interface
Chapter 10 - File System InterfaceWayne Jones Jnr
 

Similar to Session9-File Upload Security (20)

"15 Technique to Exploit File Upload Pages", Ebrahim Hegazy
"15 Technique to Exploit File Upload Pages", Ebrahim Hegazy"15 Technique to Exploit File Upload Pages", Ebrahim Hegazy
"15 Technique to Exploit File Upload Pages", Ebrahim Hegazy
 
Php File Upload
Php File UploadPhp File Upload
Php File Upload
 
File System Interface
File System InterfaceFile System Interface
File System Interface
 
File management53(1)
File management53(1)File management53(1)
File management53(1)
 
Secure Code Warrior - Local file inclusion
Secure Code Warrior - Local file inclusionSecure Code Warrior - Local file inclusion
Secure Code Warrior - Local file inclusion
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
 
File uploads
File uploadsFile uploads
File uploads
 
Tricorder: Diagnose and heal your software (without science fiction)
Tricorder: Diagnose and heal your software (without science fiction)Tricorder: Diagnose and heal your software (without science fiction)
Tricorder: Diagnose and heal your software (without science fiction)
 
File Management and manipulation in C++ Programming
File Management and manipulation in C++ ProgrammingFile Management and manipulation in C++ Programming
File Management and manipulation in C++ Programming
 
File system interface
File system interfaceFile system interface
File system interface
 
Privileged file operations_bug_on_windows
Privileged file operations_bug_on_windowsPrivileged file operations_bug_on_windows
Privileged file operations_bug_on_windows
 
7.Canon & Dt
7.Canon & Dt7.Canon & Dt
7.Canon & Dt
 
Directory_Traversel.pdf
Directory_Traversel.pdfDirectory_Traversel.pdf
Directory_Traversel.pdf
 
File handling4.pdf
File handling4.pdfFile handling4.pdf
File handling4.pdf
 
File handling3.pdf
File handling3.pdfFile handling3.pdf
File handling3.pdf
 
Learn about the File Concept in operating systems ppt
Learn about the File Concept in operating systems pptLearn about the File Concept in operating systems ppt
Learn about the File Concept in operating systems ppt
 
file management_osnotes.ppt
file management_osnotes.pptfile management_osnotes.ppt
file management_osnotes.ppt
 
File Handling
File HandlingFile Handling
File Handling
 
IIS Critical Vulnerability 23/12/09
IIS Critical Vulnerability 23/12/09IIS Critical Vulnerability 23/12/09
IIS Critical Vulnerability 23/12/09
 
Chapter 10 - File System Interface
Chapter 10 - File System InterfaceChapter 10 - File System Interface
Chapter 10 - File System Interface
 

More from zakieh alizadeh

Session11-NoSQL InjectionPHP Injection
Session11-NoSQL InjectionPHP Injection Session11-NoSQL InjectionPHP Injection
Session11-NoSQL InjectionPHP Injection zakieh alizadeh
 
Session6-Protecct Sensetive Data
Session6-Protecct Sensetive DataSession6-Protecct Sensetive Data
Session6-Protecct Sensetive Datazakieh alizadeh
 
Session1-Introduce Http-HTTP Security headers
Session1-Introduce Http-HTTP Security headers Session1-Introduce Http-HTTP Security headers
Session1-Introduce Http-HTTP Security headers zakieh alizadeh
 
Validating and Sanitizing User Data
Validating and Sanitizing  User DataValidating and Sanitizing  User Data
Validating and Sanitizing User Datazakieh alizadeh
 
Session3 data-validation
Session3 data-validationSession3 data-validation
Session3 data-validationzakieh alizadeh
 

More from zakieh alizadeh (8)

Session11-NoSQL InjectionPHP Injection
Session11-NoSQL InjectionPHP Injection Session11-NoSQL InjectionPHP Injection
Session11-NoSQL InjectionPHP Injection
 
Session6-Protecct Sensetive Data
Session6-Protecct Sensetive DataSession6-Protecct Sensetive Data
Session6-Protecct Sensetive Data
 
Session1-Introduce Http-HTTP Security headers
Session1-Introduce Http-HTTP Security headers Session1-Introduce Http-HTTP Security headers
Session1-Introduce Http-HTTP Security headers
 
yii framework
yii frameworkyii framework
yii framework
 
Web security Contents
Web security ContentsWeb security Contents
Web security Contents
 
Validating and Sanitizing User Data
Validating and Sanitizing  User DataValidating and Sanitizing  User Data
Validating and Sanitizing User Data
 
Session3 data-validation
Session3 data-validationSession3 data-validation
Session3 data-validation
 
Introduce Yii
Introduce YiiIntroduce Yii
Introduce Yii
 

Recently uploaded

Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburgmasabamasaba
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyviewmasabamasaba
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationShrmpro
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Hararemasabamasaba
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfayushiqss
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durbanmasabamasaba
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 

Recently uploaded (20)

Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 

Session9-File Upload Security

  • 1. Web Application Security (PHP) Zakieh Alizadeh zakiehalizadeh@gmail.com APA Laboratory – Ferdowsi University of Mashhad
  • 2. Session 9 Path traversal & File Inclusion
  • 3. Path traversal & File Inclusion Scenario  Preventing Path traversal & File Inclusion in College Library Website  Table Of Content  File System Concept o Permissions  Path traversal & File Inclusion  Introducing Risk Factors of File Uploads  Weak Protection Methods  Countermeasure
  • 4. Path traversal & File Inclusion File System Concept Path traversal & File Inclusion Introducing Risk Factors of File Uploads Weak Protection Methods Countermeasure
  • 5. File System Concept File System Concept  The filesystem is the view of your disks as seen by your operating system. For example: in a default install, Apache httpd resides at o Unix Filesestem : /usr/local/apache2 o Windows filesystem "c:/Program Files/Apache Group/Apache2“ .
  • 6. File System Concept Filesystem Structure  Directory: same as windows directories  Filesystem: same as windows drives  Windows: C:, D:, …  Linux: /
  • 7. File System Concept  Directory vs Filesystem  Directory: same as windows directories  Filesystem: same as windows drives
  • 9. File System Concept Filesystem  Windows: FAT, FAT32, NTFS  Linux: ext2, ext3, ext4,
  • 11. File System Concept  File Permissions  Note : The user is not the person who is logged into your application - that, and their role in the application (admin, etc) is completely irrelevant to the scenario.  The user is the linux system user that the process runs under. The code of your website is run as only one user - it may be the user of your webserver (which isn't really a good thing), or it may be a user specific to your site (which is much better). Permissions Users Example Read: r Write: w Execute: x User: u Group: g Other: o u+w: User can write g-x: Group can not execute o-r: Others can not read
  • 12. File System Concept File Permissions Numerical Representation Example Read: r = 4 Write: w = 2 Execute: x = 1 4 2 1 rwx = 7 r-x = 5 r-- = 1
  • 13. File System Concept File Permissions  Permission 754 is: rwxr-xr-- Numerical Representation Numeric User: can read, write and execute USER == > rwx=4+2+1=7 Group: can read and execute Group== > rwx=4+0+1=5 Others: just can read Others== > rwx=4+0+0=4
  • 14. File System Concept File Permissions Permision Numeric aplication owner =600 uploads/ user-Grroup-Other = 600
  • 15. File System Concept Webspace Concept  the webspace is the view of your site as delivered by the web server and seen by the client.  So the path /dir/ in the webspace corresponds to the path /usr/local/apache2/htdocs/dir/ in the filesystem of a default Apache httpd install on Unix.  The webspace need not map directly to the filesystem, since webpages may be generated dynamically from databases or other locations.
  • 16. Path traversal & File Inclusion File System Concept Path traversal & File Inclusion Introducing Risk Factors of File Uploads Weak Protection Methods Countermeasure
  • 17. Path traversal & File Inclusion  File Upload  File upload helps in increasing your business efficiency.  File uploads are allowed in social network web applications, such as Facebook and Twitter. They are also allowed in blogs, forums, e-banking sites, YouTube and also in corporate support portals, to give the opportunity to the end user to efficiently share files with corporate employees.  The more functionality provided to the end user, the greater is the risk of having a vulnerable web application
  • 18. Path traversal & File Inclusion  File Upload  When PHP receives a POST request with encoding type multipart/form-data, it will create a temporary file with a random name in a temp directory (e.g. /var/tmp/php6yXOVs). PhP will also populate the global array $_FILES with the information about the uploaded file: o $_FILES[‘uploadedfile’][‘name’]: The original name of the file on the client machine o $_FILES[‘uploadedfile’][‘type’]: The mime type of the file o $_FILES[‘uploadedfile’][‘size’]: The size of the file in bytes o $_FILES[‘uploadedfile’][‘tmp_name’]: The temporary filename in which the uploaded file was stored on the server.
  • 19. Path traversal & File Inclusion  Why File Upload Forms are a Major Security Threat?  The first step in many attacks is to get some code to the system to be attacked. Then the attack only needs to find a way to get the code executed. Using a file upload helps the attacker accomplish the first step.  The consequences of unrestricted file upload can vary, including complete system takeover, an overloaded file system, forwarding attacks to backend systems, and simple defacement. It depends on : o what the application does with the uploaded file o including where it is stored
  • 20. Path traversal & File Inclusion  Why File Upload Forms are a Major Security Threat?  There are really two different classes of problems in File upload forms:  File metadata(path , filename) o The term metadata refers to "data about data". o Example of threat :storing the file in a bad location.  File content o The range of problems here depends entirely on what the file is used for
  • 21. Path traversal & File Inclusion File System Concept Path traversal & File Inclusion Introducing Risk Factors of File Uploads Weak Protection Methods Countermeasure
  • 22. Risk Factors Risk Factors  The impact of this vulnerability is high but the likelihood is low. So, the severity of this type of vulnerability is Medium.  The website can be defaced.  The web server can be compromised by uploading and executing a web-shell which can: o run a command o browse the system files o browse the local resources o attack to other servers
  • 23. Risk Factors Risk Factors  An attacker might be able to put a phishing page into the website.  Local file inclusion vulnerabilities can be exploited by uploading a malicious file into the server.  A malicious file can be uploaded on the server in order to have a chance to be executed by administrator or webmaster later.
  • 24. Path traversal & File Inclusion File System Concept Path traversal & File Inclusion Introducing Risk Factors of File Uploads Weak Protection Methods Countermeasure
  • 25. Weak Protection Methods Weak Protection Methods  Using Black-List for Files’ Extensions  Using White-List for Files’ Extensions  Using “Content-Type” from the Header  Using a File Type Recogniser
  • 26. Weak Protection Methods Attacks on application platform  Upload .gif to be resized - image library flaw exploited  Upload huge files - file space denial of service  Upload file using malicious path or name - overwrite critical file  Upload file containing personal data - other users access it  Upload file containing "tags" - tags get executed as part of being "included" in a web page
  • 27. Weak Protection Methods Using Black-List for Files’ Extensions  Bypass by changing some letters of extension to the capital form (example: “file.aSp” or “file.PHp3”).  Using trailing spaces and/or dots at the end of the These spaces and/or dots at the end of the filename will be removed when the file wants to be saved on the hard disk automatically (example: “file.asp ... ... . . .. ..”, “file.asp ”, or “file.asp.”).  A web-server may use the first extension after the first dot (“.”) in the file name (example: “file.php.jpg”).
  • 28. Weak Protection Methods Using Black-List for Files’ Extensions  This protection can be completely bypassed by using the most famous control character. (example: “file.asp%00.jpg”)
  • 29. Weak Protection Methods Using White-List for Files’ Extensions  Although using white-list is one of the recommendations, it is not enough on its own. Without having input validation: o A web-server may use the first extension after the first dot (“.”) in the file name .(example: “file.php.jpg”). o Using trailing spaces and/or dots at the end of the These spaces and/or dots at the end of the filename will be removed when the file wants to be saved on the hard disk automatically (example: “file.asp ... ... . . .. ..”, “file.asp ”, or “file.asp.”).
  • 30. Weak Protection Methods Using “Content-Type” from the Header  “Content-Type” entity in the header of the request indicates the Internet media t o It is possible to bypass this protection by changing this parameter in the request header by using a local proxy.
  • 31. Weak Protection Methods Using a File Type Recogniser  use some functions (or APIs) to check the type of the file in order to do further process. For instance, in case of having image resizing, it is probable to have image type recogniser. o Sometimes the recognisers just read the few first characters (or header) of the files .(malicious code after some valid header) o There are always some places in the structure of the files which are for the comments section and have no effect on the main file. And, an attacker can insert malicious codes in these points. o
  • 32. Weak Protection Methods Prevention Methods : File Meta Data  It is necessary to have a list of only permitted extensions on the web application. And, file extension should be selected from the list. Use your extention instead user input extention of file.
  • 33. Path traversal & File Inclusion File System Concept Path traversal & File Inclusion Introducing Risk Factors of File Uploads Weak Protection Methods Countermeasure
  • 34. Countermeasure Prevention Methods : File Meta Data  All the control characters and Unicode ones should be removed from the filenames.  Also, the special characters such as “;”, “:”, “>”, “<”, “/” ,””, additional “.”, “*”, “%”, “$”, and so on should be discarded as well  recommended to only accept (regular expression: [a-zA-Z0-9]{1,200}.[a- zA-Z0-9]{1,10}).  Always Check both forward slashes and backslashes. May the file system may support both.
  • 35. Countermeasure Prevention Methods : File Meta Data  Awarefrom Encoding:
  • 36. Countermeasure  Prevention Methods : File Meta Data  Limit the filename length.  Try to use POST method instead of PUT (or GET!)  Prevent from overwriting a file in case of having the same hash for both.  Create a list of accepted mime-types (map extensions from these mime types).  Log users’ activities. However, the logging mechanism should be secured against log forgery and code injection itself.
  • 37. Countermeasure  Prevention Methods : File content  Use Cross Site Request Forgery protection methods.  Restrict small size files as they can lead to denial of service attacks.  Generate a random file name and add the previously generated extension.  Limit the file size to a maximum value in order to prevent denial of service attacks.  In case of having compressed file extract functions, contents of the compressed file should be checked one by one as a new file.
  • 38. Countermeasure  Prevention Methods : File content  use an algorithm to determine the filenames. For instance, a filename can be a MD5 hash of the name of file plus the date of the day.  Prevent from overwriting a file in case of having the same hash for both. o PHP Function : • hash_file : Generate a hash value using the contents of a given file • sha1_file: Calculate the sha1 hash of a file
  • 39. Countermeasure  Prevention Methods : File content  Uploaded directory should not have any “execute” permission.  If possible, upload the files in a directory outside the server root.  Prevent overwriting of existing files (to prevent the .htaccess overwrite attack).  Use an absolute path to point exactly where you want to store/retrieve the file from.  For downloads you will need to write a simple script which dumps the file to the browser after doing some authentication checks.
  • 40. Countermeasure  Prevention Methods : upload file Directory  Define a .htaccess file that will only allow access to files with allowed extensions. o Config server to avoide owerriting .htaccess o Do not place the .htaccess file in the same directory where the uploaded files will be stored. It should be placed in the parent directory. o A typical .htaccess which allows only gif, jpg, jpeg and png files should include the following (adapt it for your own need). This will also prevent double extension attacks. deny from all <Files ~ "^w+.(gif|jpe?g|png)$"> order deny,allow allow from all </Files>
  • 41. Countermeasure  Prevention Methods : upload file Directory  Prevent from directory listting. If you create a new directory (or folder) on your website, and do not put an "index.html" file in it, you may be surprised to find that your visitors can get a directory listing of all the files in that folder.  For example, if you create a folder called "incoming", you can see everything in that directory simply by typing "http://www.example.com/incoming/" in your browser. No password or anything is needed.  Add the following line to your .htaccess file. in this folder: Options -Indexes
  • 42. Countermeasure  Prevention Methods : PHP Functions  Use file_info  This extension is enabled by default as of PHP 5.3.0. Before this time, fileinfo was a PECL extension but is no longer maintained there.  For instalation o Windows users: just edit php.ini and uncomment this line: extension=php_fileinfo.dll
  • 43. Countermeasure  Prevention Methods : PHP Functions  Fileinfo Functions o finfo_buffer — Return information about a string buffer o finfo_close — Close fileinfo resource  finfo_file — Return information about a file o finfo_open — Create a new fileinfo resource o finfo_set_flags— Set libmagic configuration options o mime_content_type — Detect MIME Content-type for a file (deprecated)
  • 44. Path traversal & File Inclusion