SlideShare uma empresa Scribd logo
1 de 59
Baixar para ler offline
Web Application Security (PHP)
Zakieh Alizadeh
zakiehalizadeh@gmail.com
APA Laboratory – Ferdowsi University of Mashhad
Session 10
Security Misconfiguration
Security Misconfiguration
Scenario
 Review of Other Vulnerabilities of Web Application
Table Of Content
 The OWASP Top Ten
o Invalidated Redirect and Forwards
 Security Misconfiguration
 Application Fingerprint
 Error handling And Logging
o Noise
 PHP Guidelines
Security Misconfiguration
The OWASP Top Ten
Invalidated Redirect and Forwards
Security Misconfiguration
Application Fingerprint
Error handling And Logging
PHP Guidelines
Top 10 Owasp
Top 10 Owasp
 OWASP Top Ten is released every 3 years - this is the fourth release since
2004 launch.
 The OWASP TOP 10 has been designed to raise awareness about crucial
security threats faced by organisations.
 The top 10 are selected on the basis of exploitability, detectability and
impact estimate from over 500,000 vulnerabilities spanning over hundreds
of organisations and thousands of applications. The purpose of which is to
educate developers, designers, architects, managers and organisations
regarding web application security weaknesses.
Top 10 Owasp
Top Ten Owasp
Top 10 Owasp
Top Ten Owasp
Top 10 Owasp
Top Ten Owasp
Top 10 Owasp
Top Ten Owasp
Security Misconfiguration
 What Is Security Misconfiguration
 System admins, DBAs and developers leave security holes in the configuration of
computer systems.
Security Misconfiguration
Typical Impact Typical Impact
Security Misconfiguration
Security Misconfiguration Illustrated
 Security misconfiguration can happen at any level of an
application stack, including:
 the platform
 web server
 application server
 framework
 and custom code
Security Misconfiguration
Security Misconfiguration Illustrated
Security Misconfiguration
Scenario 1: framework misconfiguration
 Your application relies on a powerful framework like Yii.
 XSS flaws are found in these framework components you rely on.
 An update is released to fix these flaws but you don’t update your
libraries.
 Until you do, attackers can easily find and exploit these flaws in your app.
Security Misconfiguration
Scenario 2: framework misconfiguration
• The app server admin console is automatically installed and not
removed.
• Default accounts aren’t changed.
• Attacker discovers the standard admin pages are on your server, logs in
with default passwords and takes over.
Security Misconfiguration
Security Misconfiguration Countermeasure
• Change default user accounts.
• Delete unused pages and user accounts.
• Turn off unused services .
• Disable directory listings if they are not necessary, or set access controls to deny
all requests.
• Stay up-to date on patches.
• Consider internal attackers as well as external. 
• Use automated scanners.
Security Misconfiguration
Security Msconfiguration Countermeasure
 When you install an OS or server tool ,it has a default root account with a
default password. Examples:
 Windows - "Administrator"&"Administrator“
 SQL Server - “ sa “ & no password 
 Oracle "MASTER"&"PASSWORD“
 Apache "root"&“ change this“
Security Misconfiguration
Security Msconfiguration Countermeasure
 As soon as an employee or contractor leaves, change his password.
 Change his username. 
 Move files and delete the account 
 Look for old client accounts and delete them.
Security Misconfiguration
Security Msconfiguration Countermeasure
 Look through all running services, If they're not being used, turn them
off.
 Pay particular attention to: 
o Services enabled upon install
• Remote debugging
• Remote registry
• Content management
Security Misconfiguration
PHP Configuration :safe_mode
 The PHP safe mode includes a set of restrictions for PHP scripts and can
really increase the security in a shared server environment. To name a
few of these restrictions: A script can only access/modify files and folders
which has the same owner as the script itself. Some functions/operators
are completely disabled or restricted.
Security Misconfiguration
 PHP Configuration :Restrict PHP Information Leakage
 To restrict PHP information leakage disable expose_php. Edit php.ini and
set the following directive:
expose_php=Off
Security Misconfiguration
 PHP Configuration : Log All PHP Errors
 Do not expose PHP error messages to all site visitors. Edit php.ini and set
the following directive:
 Make sure you log all php errors to a log file:
display_errors=Off
log_errors=On
error_log=/var/log/httpd/php_scripts_error.log
Security Misconfiguration
 PHP Configuration : Disallow Uploading Files
 If users of your application need to upload files, turn this feature on by setting
upload_max_filesize limits the maximum size of files that PHP will accept through uploads:
file_uploads=Off
file_uploads=On # user can only upload upto 1MB via php upload
_max_filesize=1M
Security Misconfiguration
 PHP Configuration : Turn Off Remote Code Execution
 The allow_url_fopen option allows PHP's file functions - such as file_get_contents() and the
include and require statements - can retrieve data from remote locations using ftp or http
protocols.
 A large number of code injection vulnerabilities reported in PHP-based web applications are
caused by the combination of enabling allow_url_fopen and bad input filtering. Edit
/etc/php.d/php.ini and set the following directive:
allow_url_fopen=Off
allow_url_include=Off
Security Misconfiguration
 PHP Configuration : Resource Control (DoS Control)
 You can set maximum execution time of each php script, in seconds. Another recommend
option is to set maximum amount of time each script may spend parsing request data, and
maximum amount of memory a script may consume. Edit /etc/php.d/php.ini and set the
following directives:
# set in seconds
max_execution_time = 30
max_input_time = 30
memory_limit = 40M
Security Misconfiguration
 PHP Configuration : Session Path
 Session support in PHP consists of a way to preserve certain data across subsequent
accesses.
 Make sure path is outside /var/www/html and not readable or writeable by any other
system users:
session.save_path="/var/lib/php/session" ;
Set the temporary directory used for storing files when doing file upload
upload_tmp_dir="/var/lib/php/session"
Security Misconfiguration
PHP Configuration
 disable_functions
o This directive can be used to disable functions of our choosing.
 allow_url_fopen
o With this option set PHP can operate on remote files with functions like
include and fopen.Recommended: off
Security Misconfiguration
PHP Configuration
 error_reporting
o We want to write as clean code as possible and thus we want PHP to
throw all warnings etc at us.
o Recommended: E_ALL allow_url_fopen
 display_errors
o error_reporting, will be sent to the browser. This is desired in a
development environment but not on a production server, since it could
expose sensitive information about our code, database or web server.
o Recommended: off (production), on (development)
Security Misconfiguration
 Shared Hosts
 When on a shared host, security simply isn't going to be as strong as when on
a dedicated host.
 The safe_mode directive can prevent this and similar safety concerns, but
since it only applies to PHP, it doesn't address the root cause of the problem.
Attackers can simply use other languages.
 The safe_mode directive can prevent this particular script, but what about
one written in another language?
 A good solution is to store sensitive data in a database and use the technique
mentioned earlier to protect your database access credentials.
Security Misconfiguration
 A Note About PHP Backdoors
 You may come across php scripts or so called common backdoors such as c99,
c99madshell, r57 and so on. A backdoor php script is nothing but a hidden script for
bypassing all authentication and access your server on demand. It is installed by an
attackers to access your server while attempting to remain undetected. Typically a PHP
(or any other CGI script) script by mistake allows inclusion of code exploiting
vulnerabilities in the web browser. An attacker can use such exploiting vulnerabilities
to upload backdoor shells which can give him or her a number of capabilities such as:
o Download files
o Upload files
o Install rootkits
o Set a spam mail servers / relay server
Security Misconfiguration
How Do we Search PHP Backdoors?
 Use Unix / Linux grep command to search c99 or r57 shell:
# grep -iR 'c99' /var/www/html/
# grep -iR 'r57' /var/www/html/
# find /var/www/html/ -name *.php -type f -print0 | xargs -0 grep c99
# grep -RPn "(passthru|shell_exec|system|base64_decode|fopen|fclose|eval)"
/var/www/html/
Application Fingerprint
 Testing for Web Application Fingerprint
 Web server fingerprinting is a critical task for the Penetration tester.
Knowing the version and type of a running web server allows testers to
determine known vulnerabilities and the appropriate exploits to use
during testing.
Application Fingerprint
 Fingerprinting Methodology
 We will outline fingerprinting techniques for the following categories:
o Identify Web Architecture/Topology
o Identify Web Server Version
o Identify Web Application Software
o Identify Backend Database Version
Application Fingerprint
 Fingerprinting Methodology
 Identify Web Architecture/Topology
o It is advantageous to an attacker to accurately identify any intermediary web-
based systems such as proxy servers, load-balancers or web application
firewalls.
 Identify Web Server Version
o Correctly identifying the web server version can find by
• Reviewing the Server banner Information
• Implementation differences of the HTTP Protocol
• Error Pages
Application Fingerprint
 Fingerprinting Methodology
 Identify Web Application Software
o confirm what web application technologies are being used such as ASP, .NET,
PHP and Java.
• he first portion of the URL to inspect would be the file extensions used.
• Review Error Pages
Application Fingerprint
 Fingerprinting Methodology
 Identify Backend Database Version
o Determining the database engine type is fundamental if an attacker is to attempt
to successfully execute an SQL Injection attack.
• Review Error Pages
Application Fingerprint
 How can I fake the banners or rewrite the headers from my
web server?
 Banners will generally have the server name and the version number in it. We can
address this problem by either configuring the server not to display the banner at
all or by changing it to make the server look like something else.
 There are a number of tools that help in faking the banners.
o mod_security has a feature for changing the identity of the Apache web server.
 Use custom Error page
Application Fingerprint
 Once I fake the banners, can my web server still be
fingerprinted?
 Yes. Unfortunately there are tools that fingerprint the web server without relying
on the banners. Different web servers may implement features not specified in
HTTP RFCs differently. Suppose we make a database of these special requests and
the responses of each web server.
 We can now send these requests to the web server we want to fingerprint and
compare the responses with the database. This is the technique used by tools like
Fire & Water.
Application Fingerprint
 Run web server on a non-standard port. Is that right?
 A web server generally needs to be accessed by a lot of people on the internet.
Since it normally runs on port 80 and all browsers are configured to access port
80 of the web server, users are able to browse the site. If we change the port, the
users will have to specify the port in addition to the domain name.
 But this is a good idea for an intranet application where all users know where to
connect. It is more secure since the web server will not be targeted by automated
attacks like worms that scan port 80 and other standard ports.
Error Handling
 Description
 Error handling, debug messages, auditing and logging are different
aspects of the same topic: how to track events within an application:
 Error handling takes two forms:
o structured exception handling
o functional error checking
 Motivated attackers like to see error messages as they might leak
information that leads to further attacks, or may leak privacy related
information.
Error Handling
 Fail safe
 Applications should always fail safe. If an application fails to an unknown
state, it is likely that an attacker
o Inspect the application’s fatal error handler.
o Does it fail safe? If so, how?
o Is the fatal error handler called frequently enough?
o What happens to in-flight transactions and ephemeral data?
Error Handling
 Exception handling
 Does the code use structured exception handlers (try {} catch {} etc) or
function-based error handling?
 If the code uses function-based error handling, does it check every return
value and handle the error appropriately?
Logging
What is Log?
 Logs are a source of time-ordered events about everything happening
with your app.
Log File
 A file that lists actions that have occurred. For example, Web servers
maintain log files listing every request made to the server.
Logging
What to Log
 Some application exceptions
 Some application events should
o Modification of any data characteristics, including access control
permissions or file system.
o Administrative functions and changes in configuration regardless of
overlap.
o Writing of data logs also where and with what mode (append, replace)
o Some security-related events may be logged such as unauthorized
URL access attempts, user logins
Logging
What to Log
 Some application states
 Executed SQLs may be logged
 User HTTP requests may be logged
 Some debug information may be logged
o In some applications, you may have some errors and can’t find why
this is happening. You may add some debug logs into your code and
redeploy it to diagnose the problem.
Logging
 Where to log to?
 Logs should be written so that the log file attributes are such that only
new information can be written (older records cannot be rewritten or
deleted).
 All logging components should be synced with a timeserver so that all
logging can be co
 Logs are useful in reconstructing events after a problem has occurred,
security related or not.nsolidated effectively without latency errors.
 Logs are often the only record that suspicious behavior is taking place
Logging
 Logging benefits
 Handling
 General Debugging
 Forensics evidence
 Attack detection
 Proof of validity
 Quality of service
Noise
Description
 Noise is intentionally invoking security errors to fill an error log with
entries (noise) that hide the incriminating evidence of a successful
intrusion.
 When the administrator or log parser application reviews the logs, there
is every chance that they will summarize the volume of log entries as a
denial of service attempt rather than identifying the 'needle in the
haystack'.
Noise
 Solution
 Failing that, an error log audit tool that can reduce the bulk of the noise,
based on repetition of events or originating from the same source for
example.
 It is also useful if the log viewer can display the events in order of severity
level, rather than just time based.
PHP Guidelines
register_globals
 The register_globals directive makes input from GET, POST and COOKIE,
as well as session variables and uploaded files, directly accessible as
global variables in PHP. This single directive, if set in php.ini, is the root of
many vulnerabilities in web applications.
if ($bIsAlwaysFalse)
{
$sFilename = 'somefile.php';
}
if ( $sFilename != '' )
{
Include( $sFilename );
}
PHP Guidelines
register_globals
 If we were to call this page like:
 page.php?sFilename=/etc/passwd
 with register_globalsset, it would be the same as to write the following:
$sFilename = '/etc/passwd'; // This is done internally by PHP
if ($bIsAlwaysFalse)
{
$sFilename = 'somefile.php';
}
if ( $sFilename != '' )
{
Include( $sFilename );
}
PHP Guidelines
register_globals : solotion
1. Solution is So turning off register_globals might be a solution but what if
our code ends up on a server with register_globals on.We must bear in
mind that all variables in global scope could have been tampered with. And
initialize variable:
$sFilename =“ ”; //initial variables
if ($bIsAlwaysFalse)
{
$sFilename = 'somefile.php';
}
if ( $sFilename != '' )
{
Include( $sFilename );
}
PHP Guidelines
register_globals : solotion
 Another solution would be to have as little code as possible in global
scope. Object oriented programming (OOP) is a real beauty when done
right and I would highly recommend you to take that approach.
 The correct way to get input from GET, POST, COOKIE.
PHP Guidelines
Includes and Remote files
 The PHP functions include() and require() provides an easy way of
including and evaluating files.
 If the allow_url_fopen directive is enabled in php.ini you can specify the
file to be included using an URL.
 Note: The allow_url_fopen directive is enabled by default.
PHP Guidelines
Includes and Remote files
 If can’t turn off can use this solution
// file.php
define('SECURITY_CHECK', true);
$sIncludePath = '/inc/';
include($sIncludePath . 'functions.php');
...
// functions.php
if ( !defined('SECURITY_CHECK') ) {
// Output error message and exit.
...
}
PHP Guidelines
Why htmlspecialchars is not always enough ?
 Let's take a look at the following code : ( This page is meant to be called like:
page.php?sImage=filename.jpg)
 Since we are already in a HTML tag we do not need < or > to be able to inject malicious
code. Look at the following:// page.php?sImage=javascript:alert(document.cookie);
echo '<img src= “' . htmlspecialchars($_GET['sImage']) . '” />';
// Same code as before:
echo '<img src= “' . htmlspecialchars($_GET['sImage']) . '” />'; <!—
The above would result in:
--> <img src= “javascript:alert(document.cookie);” />
PHP Guidelines
Why htmlspecialchars is not always enough ?
 Solution : There is no generic solution here other than to only accept
input we know is safe, trying to filter out bad input is hard and we are
bound to miss something. Our final code would look like the following:
// We only accept input we know is safe (in this case a valid filename)
if ( preg_match('/^[0-9a-z_]+.[a-z]+$/i', $_GET['sImage']) ) {
echo '<img src="' . $_GET['sImage'] . '" />;';
}
PHP Guidelines
Why htmlspecialchars is not always enough ?
 also see function "urlencode()", useful for passing text with ampersand
and other special chars through url.
<?php
echo "<a href='foo.php?text=".urlencode("foo?&bar!")."'>link</a>";
?>
Security Misconfiguration

Mais conteúdo relacionado

Mais procurados

6 buffer overflows
6   buffer overflows6   buffer overflows
6 buffer overflows
drewz lin
 
Proactive Threat Hunting: Game-Changing Endpoint Protection Beyond Alerting
Proactive Threat Hunting: Game-Changing Endpoint Protection Beyond AlertingProactive Threat Hunting: Game-Changing Endpoint Protection Beyond Alerting
Proactive Threat Hunting: Game-Changing Endpoint Protection Beyond Alerting
CrowdStrike
 

Mais procurados (20)

CompTIA Security+.pptx
CompTIA Security+.pptxCompTIA Security+.pptx
CompTIA Security+.pptx
 
Defense in Depth – Your Security Castle
Defense in Depth – Your Security CastleDefense in Depth – Your Security Castle
Defense in Depth – Your Security Castle
 
Program security chapter 3
Program security chapter 3Program security chapter 3
Program security chapter 3
 
EDR, ETDR, Next Gen AV is all the rage, so why am I ENRAGED?
EDR, ETDR, Next Gen AV is all the rage, so why am I ENRAGED?EDR, ETDR, Next Gen AV is all the rage, so why am I ENRAGED?
EDR, ETDR, Next Gen AV is all the rage, so why am I ENRAGED?
 
Types of Malware (CEH v11)
Types of Malware (CEH v11)Types of Malware (CEH v11)
Types of Malware (CEH v11)
 
6 buffer overflows
6   buffer overflows6   buffer overflows
6 buffer overflows
 
Containerizing your Security Operations Center
Containerizing your Security Operations CenterContainerizing your Security Operations Center
Containerizing your Security Operations Center
 
Message digest 5
Message digest 5Message digest 5
Message digest 5
 
Port scanning
Port scanningPort scanning
Port scanning
 
Ceh v5 module 11 hacking webservers
Ceh v5 module 11 hacking webserversCeh v5 module 11 hacking webservers
Ceh v5 module 11 hacking webservers
 
Privilege escalation from 1 to 0 Workshop
Privilege escalation from 1 to 0 Workshop Privilege escalation from 1 to 0 Workshop
Privilege escalation from 1 to 0 Workshop
 
Proactive Threat Hunting: Game-Changing Endpoint Protection Beyond Alerting
Proactive Threat Hunting: Game-Changing Endpoint Protection Beyond AlertingProactive Threat Hunting: Game-Changing Endpoint Protection Beyond Alerting
Proactive Threat Hunting: Game-Changing Endpoint Protection Beyond Alerting
 
Secure coding practices
Secure coding practicesSecure coding practices
Secure coding practices
 
Programme de cybersécurité : Implementer le framework NIST CSF en entreprise
Programme de cybersécurité : Implementer le framework NIST CSF en entrepriseProgramme de cybersécurité : Implementer le framework NIST CSF en entreprise
Programme de cybersécurité : Implementer le framework NIST CSF en entreprise
 
certified-ethical-hacker-cehv12_course_content.pdf
certified-ethical-hacker-cehv12_course_content.pdfcertified-ethical-hacker-cehv12_course_content.pdf
certified-ethical-hacker-cehv12_course_content.pdf
 
You can detect PowerShell attacks
You can detect PowerShell attacksYou can detect PowerShell attacks
You can detect PowerShell attacks
 
CNIT 126 2: Malware Analysis in Virtual Machines & 3: Basic Dynamic Analysis
CNIT 126 2: Malware Analysis in Virtual Machines & 3: Basic Dynamic AnalysisCNIT 126 2: Malware Analysis in Virtual Machines & 3: Basic Dynamic Analysis
CNIT 126 2: Malware Analysis in Virtual Machines & 3: Basic Dynamic Analysis
 
Practical Malware Analysis Ch12
Practical Malware Analysis Ch12Practical Malware Analysis Ch12
Practical Malware Analysis Ch12
 
Intrusion detection
Intrusion detectionIntrusion detection
Intrusion detection
 
Cyber Threat Intelligence: Building and maturing an intelligence program that...
Cyber Threat Intelligence: Building and maturing an intelligence program that...Cyber Threat Intelligence: Building and maturing an intelligence program that...
Cyber Threat Intelligence: Building and maturing an intelligence program that...
 

Semelhante a Session10-PHP Misconfiguration

LAMP security practices
LAMP security practicesLAMP security practices
LAMP security practices
Amit Kejriwal
 
Web sever environmentA Web server is a program that uses HTTP (Hy.pdf
Web sever environmentA Web server is a program that uses HTTP (Hy.pdfWeb sever environmentA Web server is a program that uses HTTP (Hy.pdf
Web sever environmentA Web server is a program that uses HTTP (Hy.pdf
aquacareser
 

Semelhante a Session10-PHP Misconfiguration (20)

Php
PhpPhp
Php
 
Secure programming with php
Secure programming with phpSecure programming with php
Secure programming with php
 
Secure PHP Coding
Secure PHP CodingSecure PHP Coding
Secure PHP Coding
 
Php security
Php securityPhp security
Php security
 
Php Ppt
Php PptPhp Ppt
Php Ppt
 
OWASP Top10 2010
OWASP Top10 2010OWASP Top10 2010
OWASP Top10 2010
 
Download It
Download ItDownload It
Download It
 
Crime Reporting System.pptx
Crime Reporting System.pptxCrime Reporting System.pptx
Crime Reporting System.pptx
 
LAMP security practices
LAMP security practicesLAMP security practices
LAMP security practices
 
Web application penetration testing lab setup guide
Web application penetration testing lab setup guideWeb application penetration testing lab setup guide
Web application penetration testing lab setup guide
 
PHP Security
PHP SecurityPHP Security
PHP Security
 
Web sever environmentA Web server is a program that uses HTTP (Hy.pdf
Web sever environmentA Web server is a program that uses HTTP (Hy.pdfWeb sever environmentA Web server is a program that uses HTTP (Hy.pdf
Web sever environmentA Web server is a program that uses HTTP (Hy.pdf
 
Unit 1
Unit 1Unit 1
Unit 1
 
Web-servers & Application Hacking
Web-servers & Application HackingWeb-servers & Application Hacking
Web-servers & Application Hacking
 
DevOpsDays Singapore - Continuous Auditing with Compliance as Code
DevOpsDays Singapore - Continuous Auditing with Compliance as CodeDevOpsDays Singapore - Continuous Auditing with Compliance as Code
DevOpsDays Singapore - Continuous Auditing with Compliance as Code
 
Securing Your Web Server
Securing Your Web ServerSecuring Your Web Server
Securing Your Web Server
 
OWASP Portland - OWASP Top 10 For JavaScript Developers
OWASP Portland - OWASP Top 10 For JavaScript DevelopersOWASP Portland - OWASP Top 10 For JavaScript Developers
OWASP Portland - OWASP Top 10 For JavaScript Developers
 
My Saminar On Php
My Saminar On PhpMy Saminar On Php
My Saminar On Php
 
Security misconfiguration
Security misconfigurationSecurity misconfiguration
Security misconfiguration
 
DevSec Delight with Compliance as Code - Matt Ray - AgileNZ 2017
DevSec Delight with Compliance as Code - Matt Ray - AgileNZ 2017DevSec Delight with Compliance as Code - Matt Ray - AgileNZ 2017
DevSec Delight with Compliance as Code - Matt Ray - AgileNZ 2017
 

Mais de zakieh alizadeh

Session3 data-validation
Session3 data-validationSession3 data-validation
Session3 data-validation
zakieh alizadeh
 

Mais de zakieh alizadeh (15)

Session11-NoSQL InjectionPHP Injection
Session11-NoSQL InjectionPHP Injection Session11-NoSQL InjectionPHP Injection
Session11-NoSQL InjectionPHP Injection
 
Session9-File Upload Security
Session9-File Upload SecuritySession9-File Upload Security
Session9-File Upload Security
 
S8-Session Managment
S8-Session ManagmentS8-Session Managment
S8-Session Managment
 
Session7-XSS & CSRF
Session7-XSS & CSRFSession7-XSS & CSRF
Session7-XSS & CSRF
 
Session6-Protecct Sensetive Data
Session6-Protecct Sensetive DataSession6-Protecct Sensetive Data
Session6-Protecct Sensetive Data
 
S5-Authorization
S5-AuthorizationS5-Authorization
S5-Authorization
 
Session4-Authentication
Session4-AuthenticationSession4-Authentication
Session4-Authentication
 
Session3 data-validation-sql injection
Session3 data-validation-sql injectionSession3 data-validation-sql injection
Session3 data-validation-sql injection
 
Session2-Application Threat Modeling
Session2-Application Threat ModelingSession2-Application Threat Modeling
Session2-Application Threat Modeling
 
Session1-Introduce Http-HTTP Security headers
Session1-Introduce Http-HTTP Security headers Session1-Introduce Http-HTTP Security headers
Session1-Introduce Http-HTTP Security headers
 
yii framework
yii frameworkyii framework
yii framework
 
Web security Contents
Web security ContentsWeb security Contents
Web security Contents
 
Validating and Sanitizing User Data
Validating and Sanitizing  User DataValidating and Sanitizing  User Data
Validating and Sanitizing User Data
 
Session3 data-validation
Session3 data-validationSession3 data-validation
Session3 data-validation
 
Introduce Yii
Introduce YiiIntroduce Yii
Introduce Yii
 

Último

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 

Último (20)

%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 

Session10-PHP Misconfiguration

  • 1. Web Application Security (PHP) Zakieh Alizadeh zakiehalizadeh@gmail.com APA Laboratory – Ferdowsi University of Mashhad
  • 3. Security Misconfiguration Scenario  Review of Other Vulnerabilities of Web Application Table Of Content  The OWASP Top Ten o Invalidated Redirect and Forwards  Security Misconfiguration  Application Fingerprint  Error handling And Logging o Noise  PHP Guidelines
  • 4. Security Misconfiguration The OWASP Top Ten Invalidated Redirect and Forwards Security Misconfiguration Application Fingerprint Error handling And Logging PHP Guidelines
  • 5. Top 10 Owasp Top 10 Owasp  OWASP Top Ten is released every 3 years - this is the fourth release since 2004 launch.  The OWASP TOP 10 has been designed to raise awareness about crucial security threats faced by organisations.  The top 10 are selected on the basis of exploitability, detectability and impact estimate from over 500,000 vulnerabilities spanning over hundreds of organisations and thousands of applications. The purpose of which is to educate developers, designers, architects, managers and organisations regarding web application security weaknesses.
  • 10. Security Misconfiguration  What Is Security Misconfiguration  System admins, DBAs and developers leave security holes in the configuration of computer systems.
  • 12. Security Misconfiguration Security Misconfiguration Illustrated  Security misconfiguration can happen at any level of an application stack, including:  the platform  web server  application server  framework  and custom code
  • 14. Security Misconfiguration Scenario 1: framework misconfiguration  Your application relies on a powerful framework like Yii.  XSS flaws are found in these framework components you rely on.  An update is released to fix these flaws but you don’t update your libraries.  Until you do, attackers can easily find and exploit these flaws in your app.
  • 15. Security Misconfiguration Scenario 2: framework misconfiguration • The app server admin console is automatically installed and not removed. • Default accounts aren’t changed. • Attacker discovers the standard admin pages are on your server, logs in with default passwords and takes over.
  • 16. Security Misconfiguration Security Misconfiguration Countermeasure • Change default user accounts. • Delete unused pages and user accounts. • Turn off unused services . • Disable directory listings if they are not necessary, or set access controls to deny all requests. • Stay up-to date on patches. • Consider internal attackers as well as external.  • Use automated scanners.
  • 17. Security Misconfiguration Security Msconfiguration Countermeasure  When you install an OS or server tool ,it has a default root account with a default password. Examples:  Windows - "Administrator"&"Administrator“  SQL Server - “ sa “ & no password   Oracle "MASTER"&"PASSWORD“  Apache "root"&“ change this“
  • 18. Security Misconfiguration Security Msconfiguration Countermeasure  As soon as an employee or contractor leaves, change his password.  Change his username.   Move files and delete the account   Look for old client accounts and delete them.
  • 19. Security Misconfiguration Security Msconfiguration Countermeasure  Look through all running services, If they're not being used, turn them off.  Pay particular attention to:  o Services enabled upon install • Remote debugging • Remote registry • Content management
  • 20. Security Misconfiguration PHP Configuration :safe_mode  The PHP safe mode includes a set of restrictions for PHP scripts and can really increase the security in a shared server environment. To name a few of these restrictions: A script can only access/modify files and folders which has the same owner as the script itself. Some functions/operators are completely disabled or restricted.
  • 21. Security Misconfiguration  PHP Configuration :Restrict PHP Information Leakage  To restrict PHP information leakage disable expose_php. Edit php.ini and set the following directive: expose_php=Off
  • 22. Security Misconfiguration  PHP Configuration : Log All PHP Errors  Do not expose PHP error messages to all site visitors. Edit php.ini and set the following directive:  Make sure you log all php errors to a log file: display_errors=Off log_errors=On error_log=/var/log/httpd/php_scripts_error.log
  • 23. Security Misconfiguration  PHP Configuration : Disallow Uploading Files  If users of your application need to upload files, turn this feature on by setting upload_max_filesize limits the maximum size of files that PHP will accept through uploads: file_uploads=Off file_uploads=On # user can only upload upto 1MB via php upload _max_filesize=1M
  • 24. Security Misconfiguration  PHP Configuration : Turn Off Remote Code Execution  The allow_url_fopen option allows PHP's file functions - such as file_get_contents() and the include and require statements - can retrieve data from remote locations using ftp or http protocols.  A large number of code injection vulnerabilities reported in PHP-based web applications are caused by the combination of enabling allow_url_fopen and bad input filtering. Edit /etc/php.d/php.ini and set the following directive: allow_url_fopen=Off allow_url_include=Off
  • 25. Security Misconfiguration  PHP Configuration : Resource Control (DoS Control)  You can set maximum execution time of each php script, in seconds. Another recommend option is to set maximum amount of time each script may spend parsing request data, and maximum amount of memory a script may consume. Edit /etc/php.d/php.ini and set the following directives: # set in seconds max_execution_time = 30 max_input_time = 30 memory_limit = 40M
  • 26. Security Misconfiguration  PHP Configuration : Session Path  Session support in PHP consists of a way to preserve certain data across subsequent accesses.  Make sure path is outside /var/www/html and not readable or writeable by any other system users: session.save_path="/var/lib/php/session" ; Set the temporary directory used for storing files when doing file upload upload_tmp_dir="/var/lib/php/session"
  • 27. Security Misconfiguration PHP Configuration  disable_functions o This directive can be used to disable functions of our choosing.  allow_url_fopen o With this option set PHP can operate on remote files with functions like include and fopen.Recommended: off
  • 28. Security Misconfiguration PHP Configuration  error_reporting o We want to write as clean code as possible and thus we want PHP to throw all warnings etc at us. o Recommended: E_ALL allow_url_fopen  display_errors o error_reporting, will be sent to the browser. This is desired in a development environment but not on a production server, since it could expose sensitive information about our code, database or web server. o Recommended: off (production), on (development)
  • 29. Security Misconfiguration  Shared Hosts  When on a shared host, security simply isn't going to be as strong as when on a dedicated host.  The safe_mode directive can prevent this and similar safety concerns, but since it only applies to PHP, it doesn't address the root cause of the problem. Attackers can simply use other languages.  The safe_mode directive can prevent this particular script, but what about one written in another language?  A good solution is to store sensitive data in a database and use the technique mentioned earlier to protect your database access credentials.
  • 30. Security Misconfiguration  A Note About PHP Backdoors  You may come across php scripts or so called common backdoors such as c99, c99madshell, r57 and so on. A backdoor php script is nothing but a hidden script for bypassing all authentication and access your server on demand. It is installed by an attackers to access your server while attempting to remain undetected. Typically a PHP (or any other CGI script) script by mistake allows inclusion of code exploiting vulnerabilities in the web browser. An attacker can use such exploiting vulnerabilities to upload backdoor shells which can give him or her a number of capabilities such as: o Download files o Upload files o Install rootkits o Set a spam mail servers / relay server
  • 31. Security Misconfiguration How Do we Search PHP Backdoors?  Use Unix / Linux grep command to search c99 or r57 shell: # grep -iR 'c99' /var/www/html/ # grep -iR 'r57' /var/www/html/ # find /var/www/html/ -name *.php -type f -print0 | xargs -0 grep c99 # grep -RPn "(passthru|shell_exec|system|base64_decode|fopen|fclose|eval)" /var/www/html/
  • 32. Application Fingerprint  Testing for Web Application Fingerprint  Web server fingerprinting is a critical task for the Penetration tester. Knowing the version and type of a running web server allows testers to determine known vulnerabilities and the appropriate exploits to use during testing.
  • 33. Application Fingerprint  Fingerprinting Methodology  We will outline fingerprinting techniques for the following categories: o Identify Web Architecture/Topology o Identify Web Server Version o Identify Web Application Software o Identify Backend Database Version
  • 34. Application Fingerprint  Fingerprinting Methodology  Identify Web Architecture/Topology o It is advantageous to an attacker to accurately identify any intermediary web- based systems such as proxy servers, load-balancers or web application firewalls.  Identify Web Server Version o Correctly identifying the web server version can find by • Reviewing the Server banner Information • Implementation differences of the HTTP Protocol • Error Pages
  • 35. Application Fingerprint  Fingerprinting Methodology  Identify Web Application Software o confirm what web application technologies are being used such as ASP, .NET, PHP and Java. • he first portion of the URL to inspect would be the file extensions used. • Review Error Pages
  • 36. Application Fingerprint  Fingerprinting Methodology  Identify Backend Database Version o Determining the database engine type is fundamental if an attacker is to attempt to successfully execute an SQL Injection attack. • Review Error Pages
  • 37. Application Fingerprint  How can I fake the banners or rewrite the headers from my web server?  Banners will generally have the server name and the version number in it. We can address this problem by either configuring the server not to display the banner at all or by changing it to make the server look like something else.  There are a number of tools that help in faking the banners. o mod_security has a feature for changing the identity of the Apache web server.  Use custom Error page
  • 38. Application Fingerprint  Once I fake the banners, can my web server still be fingerprinted?  Yes. Unfortunately there are tools that fingerprint the web server without relying on the banners. Different web servers may implement features not specified in HTTP RFCs differently. Suppose we make a database of these special requests and the responses of each web server.  We can now send these requests to the web server we want to fingerprint and compare the responses with the database. This is the technique used by tools like Fire & Water.
  • 39. Application Fingerprint  Run web server on a non-standard port. Is that right?  A web server generally needs to be accessed by a lot of people on the internet. Since it normally runs on port 80 and all browsers are configured to access port 80 of the web server, users are able to browse the site. If we change the port, the users will have to specify the port in addition to the domain name.  But this is a good idea for an intranet application where all users know where to connect. It is more secure since the web server will not be targeted by automated attacks like worms that scan port 80 and other standard ports.
  • 40. Error Handling  Description  Error handling, debug messages, auditing and logging are different aspects of the same topic: how to track events within an application:  Error handling takes two forms: o structured exception handling o functional error checking  Motivated attackers like to see error messages as they might leak information that leads to further attacks, or may leak privacy related information.
  • 41. Error Handling  Fail safe  Applications should always fail safe. If an application fails to an unknown state, it is likely that an attacker o Inspect the application’s fatal error handler. o Does it fail safe? If so, how? o Is the fatal error handler called frequently enough? o What happens to in-flight transactions and ephemeral data?
  • 42. Error Handling  Exception handling  Does the code use structured exception handlers (try {} catch {} etc) or function-based error handling?  If the code uses function-based error handling, does it check every return value and handle the error appropriately?
  • 43. Logging What is Log?  Logs are a source of time-ordered events about everything happening with your app. Log File  A file that lists actions that have occurred. For example, Web servers maintain log files listing every request made to the server.
  • 44. Logging What to Log  Some application exceptions  Some application events should o Modification of any data characteristics, including access control permissions or file system. o Administrative functions and changes in configuration regardless of overlap. o Writing of data logs also where and with what mode (append, replace) o Some security-related events may be logged such as unauthorized URL access attempts, user logins
  • 45. Logging What to Log  Some application states  Executed SQLs may be logged  User HTTP requests may be logged  Some debug information may be logged o In some applications, you may have some errors and can’t find why this is happening. You may add some debug logs into your code and redeploy it to diagnose the problem.
  • 46. Logging  Where to log to?  Logs should be written so that the log file attributes are such that only new information can be written (older records cannot be rewritten or deleted).  All logging components should be synced with a timeserver so that all logging can be co  Logs are useful in reconstructing events after a problem has occurred, security related or not.nsolidated effectively without latency errors.  Logs are often the only record that suspicious behavior is taking place
  • 47. Logging  Logging benefits  Handling  General Debugging  Forensics evidence  Attack detection  Proof of validity  Quality of service
  • 48. Noise Description  Noise is intentionally invoking security errors to fill an error log with entries (noise) that hide the incriminating evidence of a successful intrusion.  When the administrator or log parser application reviews the logs, there is every chance that they will summarize the volume of log entries as a denial of service attempt rather than identifying the 'needle in the haystack'.
  • 49. Noise  Solution  Failing that, an error log audit tool that can reduce the bulk of the noise, based on repetition of events or originating from the same source for example.  It is also useful if the log viewer can display the events in order of severity level, rather than just time based.
  • 50. PHP Guidelines register_globals  The register_globals directive makes input from GET, POST and COOKIE, as well as session variables and uploaded files, directly accessible as global variables in PHP. This single directive, if set in php.ini, is the root of many vulnerabilities in web applications. if ($bIsAlwaysFalse) { $sFilename = 'somefile.php'; } if ( $sFilename != '' ) { Include( $sFilename ); }
  • 51. PHP Guidelines register_globals  If we were to call this page like:  page.php?sFilename=/etc/passwd  with register_globalsset, it would be the same as to write the following: $sFilename = '/etc/passwd'; // This is done internally by PHP if ($bIsAlwaysFalse) { $sFilename = 'somefile.php'; } if ( $sFilename != '' ) { Include( $sFilename ); }
  • 52. PHP Guidelines register_globals : solotion 1. Solution is So turning off register_globals might be a solution but what if our code ends up on a server with register_globals on.We must bear in mind that all variables in global scope could have been tampered with. And initialize variable: $sFilename =“ ”; //initial variables if ($bIsAlwaysFalse) { $sFilename = 'somefile.php'; } if ( $sFilename != '' ) { Include( $sFilename ); }
  • 53. PHP Guidelines register_globals : solotion  Another solution would be to have as little code as possible in global scope. Object oriented programming (OOP) is a real beauty when done right and I would highly recommend you to take that approach.  The correct way to get input from GET, POST, COOKIE.
  • 54. PHP Guidelines Includes and Remote files  The PHP functions include() and require() provides an easy way of including and evaluating files.  If the allow_url_fopen directive is enabled in php.ini you can specify the file to be included using an URL.  Note: The allow_url_fopen directive is enabled by default.
  • 55. PHP Guidelines Includes and Remote files  If can’t turn off can use this solution // file.php define('SECURITY_CHECK', true); $sIncludePath = '/inc/'; include($sIncludePath . 'functions.php'); ... // functions.php if ( !defined('SECURITY_CHECK') ) { // Output error message and exit. ... }
  • 56. PHP Guidelines Why htmlspecialchars is not always enough ?  Let's take a look at the following code : ( This page is meant to be called like: page.php?sImage=filename.jpg)  Since we are already in a HTML tag we do not need < or > to be able to inject malicious code. Look at the following:// page.php?sImage=javascript:alert(document.cookie); echo '<img src= “' . htmlspecialchars($_GET['sImage']) . '” />'; // Same code as before: echo '<img src= “' . htmlspecialchars($_GET['sImage']) . '” />'; <!— The above would result in: --> <img src= “javascript:alert(document.cookie);” />
  • 57. PHP Guidelines Why htmlspecialchars is not always enough ?  Solution : There is no generic solution here other than to only accept input we know is safe, trying to filter out bad input is hard and we are bound to miss something. Our final code would look like the following: // We only accept input we know is safe (in this case a valid filename) if ( preg_match('/^[0-9a-z_]+.[a-z]+$/i', $_GET['sImage']) ) { echo '<img src="' . $_GET['sImage'] . '" />;'; }
  • 58. PHP Guidelines Why htmlspecialchars is not always enough ?  also see function "urlencode()", useful for passing text with ampersand and other special chars through url. <?php echo "<a href='foo.php?text=".urlencode("foo?&bar!")."'>link</a>"; ?>