SlideShare una empresa de Scribd logo
1 de 39
Descargar para leer sin conexión
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 1/39© 2019 Rogue Wave Software, Inc. All rights reserved
Webinar series: PHP security best practices
Part 2: Web security best practices for PHP
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 2/39© 2019 Rogue Wave Software, Inc. All rights reserved
PHPsecuritybestpracticesPHPsecuritybestpractices
by Daryl Wood
Senior Technical Trainer
Webinar, April 25, 2019
Rogue Wave Software, Inc.
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 3/39© 2019 Rogue Wave Software, Inc. All rights reserved
SessiononerecapSessiononerecap
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 4/39© 2019 Rogue Wave Software, Inc. All rights reserved
PHPsecuritybestpracticesPHPsecuritybestpractices
FirstsessionrecapFirstsessionrecap
Part one of this series included:
Security attack types
Log monitoring
Attack injection
Attack severities and impacts
PHP version end of life
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 5/39© 2019 Rogue Wave Software, Inc. All rights reserved
PHPapplicationsecurityPHPapplicationsecurity
BestpracticefundamentalsBestpracticefundamentals
Today's part of this includes:
Code: Injection handling input and output
Logs: Web server (Apache) and PHP application
Code: Di erent logs for di erent severities
Updating PHP on a staging server
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 6/39© 2019 Rogue Wave Software, Inc. All rights reserved
CodeCode
InjectionhandlinginputandoutputInjectionhandlinginputandoutput
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 7/39© 2019 Rogue Wave Software, Inc. All rights reserved
Code:InjectionhandlinginputandoutputCode:Injectionhandlinginputandoutput
InputreviewInputreview
What's considered data input:
A request from a web client
A data payload from a web service call
A data payload from an asynchronous (AJAX) request
Data from a persistent storage mechanism
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 8/39© 2019 Rogue Wave Software, Inc. All rights reserved
Crosssiteinjection(XSS)Crosssiteinjection(XSS)
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 9/39© 2019 Rogue Wave Software, Inc. All rights reserved
Code:InjectionhandlinginputandoutputCode:Injectionhandlinginputandoutput
InputfilteringforXSSinjectionInputfilteringforXSSinjection
VulnerablecodeVulnerablecode
// Simulate injected post data
$_POST['username'] = 'pablo';
$_POST['comment'] = '<script>alert("document.cookie")</script>';
if($_POST && isset($_POST['username') && isset($_POST['comment'])) {
$result = null;
try {
$pdo = new PDO('mysql:unix_socket=/var/run/mysqld/mysqld.sock;dbname=blog',
'vagrant', 'vagrant');
$stmt = $pdo->query("INSERT INTO blog (username, comment) VALUES ({$_POST['username']},
{$_POST['comment']})");
if($stmt) $stmt->execute();
// Then subsequently
$result = $pdo->exec("SELECT * FROM blog WHERE username='{$_POST['username']}'");
} catch (Throwable $e){
// Handle ...
}
if($result){
echo $result['comment'];
}
}
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 10/39© 2019 Rogue Wave Software, Inc. All rights reserved
Code:InjectionhandlinginputandoutputCode:Injectionhandlinginputandoutput
InputfilteringforXSSinjectionInputfilteringforXSSinjection
FilteredcodeFilteredcode
// Simulate injected post data
$_POST['username'] = 'pablo';
$_POST['comment'] = '<script>alert("document.cookie")</script>';
// This code should be owned by the initial domain input handling
if($_POST && isset($_POST['username') && isset($_POST['comment'])) {
// Looking for an alpha numeric value
$cleanUsername = ctype_alnum($_POST['username']) ? $_POST['username'] : false;
// Looking for tag-based injection and stripping the tags
$cleanComment = strip_tags($_POST['comment']) ?? false;
if($cleanUsername && $cleanComment) {
// Persist the data with $cleanUsername and $cleanComment escaping with:
// * htmlspecialchars()
// * htmlentities()
// * or your framework escaping mechanism
}
}
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 11/39© 2019 Rogue Wave Software, Inc. All rights reserved
SQLinjectionSQLinjection
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 12/39© 2019 Rogue Wave Software, Inc. All rights reserved
Code:InjectionhandlinginputandoutputCode:Injectionhandlinginputandoutput
InputfilteringforSQLinjectionInputfilteringforSQLinjection
VulnerablecodeVulnerablecode
// Simulate injected get data
$_GET['id'] = ';update blog set username = attacker where user_id = 1;';
$_GET['new-password'] = 'e44sxdfg3';
$_GET['submit'] = 'submit';
if ($_GET && isset($_GET['Submit'])) {
//Employ ACL to determine access
try {
$pdo = new PDO('mysql:unix_socket=/var/run/mysqld/mysqld.sock;dbname=blog',
'vagrant', 'vagrant');
$stmt = $pdo->query("SELECT first_name, last_name FROM blog
WHERE user_id = '{$_GET['id']}'");
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
// Handle ...
}
}
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 13/39© 2019 Rogue Wave Software, Inc. All rights reserved
Code:InjectionhandlinginputandoutputCode:Injectionhandlinginputandoutput
InputfilteringforSQLinjectionInputfilteringforSQLinjection
FilteredcodeFilteredcode
// Simulate injected get data
$_GET['id'] = ';update blog set username = attacker where user_id = 1;';
$_GET['new-password'] = 'e44sxdfg3';
$_GET['submit'] = 'submit';
if ($_GET && isset($_GET['id']) && isset($_GET['Submit'])) {
//Employ ACL to determine access
// Filter by type coercion on integer-type identifier
$cleanId = (int)$_GET['id'];
// Filter by using the ctype_alnum() function for none integer-type
// identifiers, and assuming here alpha numeric
$cleanId = ctype_alnum($_GET['id']) ? $_GET['id'] : false;
// Filter by stripping tags, as passwords can be just about any character combination
$cleanPass = strip_tags($_GET['new-password']);
if($cleanId && $cleanPass) {
// Escape, then persist and update the data with $cleanId and $cleanPass ...
} else {
echo 'Data invalid';
}
}
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 14/39© 2019 Rogue Wave Software, Inc. All rights reserved
BrokensessionmanagementBrokensessionmanagement
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 15/39© 2019 Rogue Wave Software, Inc. All rights reserved
Code:InjectionhandlinginputandoutputCode:Injectionhandlinginputandoutput
BrokensessionmanagementBrokensessionmanagement
VulnerablecodeVulnerablecode
// A controller responsible for login/logout actions
class LoginController {
// ...
public function logoutAction() {
$this->view->setTemplate('login');
$this->view->render();
}
// ...
}
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 16/39© 2019 Rogue Wave Software, Inc. All rights reserved
Code:InjectionhandlinginputandoutputCode:Injectionhandlinginputandoutput
BrokensessionmanagementBrokensessionmanagement
RepairedcodeRepairedcode
// Assuming a controller handles the fix directly, or indirectly.
class LoginController {
// ...
public function logoutAction() {
// Destroy the session here,
session_destroy();
// or with some injected and dedicated Session-responsible
// object calling its destroy() method.
$this->session->destroy();
$this->view->setTemplate('login');
$this->view->render();
}
// ...
}
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 17/39© 2019 Rogue Wave Software, Inc. All rights reserved
BruteforceBruteforce
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 18/39© 2019 Rogue Wave Software, Inc. All rights reserved
Code:InjectionhandlinginputandoutputCode:Injectionhandlinginputandoutput
BruteforceBruteforce
VulnerablecodeVulnerablecode
// Simulate a billion-fold brute force attempt with minor changes to the password.
$_POST['username'] = 'admin';
$_POST['password'] = 'pA$$wORD';
if($_POST && isset($_POST['username']) && isset($_POST['password'])) {
$result = false;
$password = md5($_POST['password']);
try{
$stmt = $this->getPdo()->query("SELECT * FROM users WHERE
username='{$_POST['username']}' AND password='$password'");
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
}catch(PDOException $e){ // Handle ...
}
if($result && count($result)) { // On success
// Redirect to password-protected area
} else { // On failure
echo "<p>Login unsuccessful</p>";
}
}
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 19/39© 2019 Rogue Wave Software, Inc. All rights reserved
Code:InjectionhandlinginputandoutputCode:Injectionhandlinginputandoutput
BruteforceBruteforce
RepairedcodeRepairedcode
// Simulate a billion-fold brute force attempt with minor changes to the password.
$_POST['username'] = 'admin';
$_POST['password'] = 'pA$$wORD';
if($_POST && isset($_POST['username']) && isset($_POST['password'])) {
// Execute brute force detection code here ...
$cleanUser = ctype_alnum($_POST['username']) ? $_POST['username'] : false;
if($cleanUser){
try{
$stmt = $this->getPdo()->query("SELECT * FROM users WHERE username='$cleanUser'");
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
}catch(PDOException $e) { // Handle ...
}
}
if($result && count($result) && password_verify($_POST['password'], $result['password']) ) {
// Login successful, redirect to password-protected area escaping any input used ...
} else { //Login failed
echo "<p>Login unsuccessful</p>";
// Execute brute force detection code to record failed attempt
}
}
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 20/39© 2019 Rogue Wave Software, Inc. All rights reserved
LogsLogs
Webserver(Apache)andPHPapplicationWebserver(Apache)andPHPapplication
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 21/39© 2019 Rogue Wave Software, Inc. All rights reserved
Logs:Webserver(Apache)andPHPapplicationLogs:Webserver(Apache)andPHPapplication
LoglocationLoglocation
Here restated are the default log locations for a Debian-based Linux
server and PHP installation:
Syslog: /var/log/syslog
Apache access: /var/log/apache2/access.log
Apache error: /var/log/apache2/error.log
PHP error When enabled, and by default, is the syslog.
Instead of these defaults, we concern ourselves with Apache access
and error logging for a speci c host, and separate logs for critical PHP
error severities from all other severities.
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 22/39© 2019 Rogue Wave Software, Inc. All rights reserved
Logs:Webserver(Apache)andPHPapplicationLogs:Webserver(Apache)andPHPapplication
SpecificApachehostloggingSpecificApachehostlogging
This code block shows an Apache virtual host con guration for host-
speci c access and error logging.
https://httpd.apache.org/
<VirtualHost *:80>
ServerName rockets.com
DocumentRoot /var/www/rockets
<Directory /var/www/rockets/>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Require all granted
</Directory>
# Custom host-specific logging
ErrorLog /var/www/rockets/error.log
CustomLog /var/www/rockets/access.log combined
</VirtualHost>
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 23/39© 2019 Rogue Wave Software, Inc. All rights reserved
Logs:Webserver(Apache)andPHPapplicationLogs:Webserver(Apache)andPHPapplication
PHPapplicationerrorloggingPHPapplicationerrorlogging
These code blocks shows production environment PHP con guration
directives enabling error reporting, logging, and location for
application-speci c PHP error logging.
In a web server php.ini con guration le:
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
log_errors = On
error_log = /var/www/rocket/logs/error.log
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 24/39© 2019 Rogue Wave Software, Inc. All rights reserved
CodeCode
DifferentlogsfordifferentseveritiesDifferentlogsfordifferentseverities
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 25/39© 2019 Rogue Wave Software, Inc. All rights reserved
CodeCode
DifferentlogsfordifferentseveritiesDifferentlogsfordifferentseverities
It is often helpful to direct speci c error severities to dedicated log les.
The next few slides de ne one way of doing that in object-oriented
code.
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 26/39© 2019 Rogue Wave Software, Inc. All rights reserved
Code:DifferentlogsfordifferentseveritiesCode:Differentlogsfordifferentseverities
ALoggerclassALoggerclass
class Logger{
public static $critical_log, $warning_notice_log;
protected static $error;
public static function handler(...$error) {
self::$error = $error;
// Checks if error code is not part of error_reporting and bail
if (!(error_reporting() & self::$error[0])) return;
self::log();
}
public static function log(){
$logEntry = date('Ymd.h.m.s').'|'.self::$error[1].'|'.self::$error[2].'|'.
self::$error[3] . PHP_EOL;
switch (true){
case (self::$error[0] === E_ERROR || self::$error[0] === E_USER_ERROR):
return error_log($logEntry, 3, self::$critical_log);
case (self::$error[0] === E_WARNING || self::$error[0] === E_NOTICE):
return error_log($logEntry, 3, self::$warning_notice_log);
// ...
}
return false;
}
}
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 27/39© 2019 Rogue Wave Software, Inc. All rights reserved
Code:DifferentlogsfordifferentseveritiesCode:Differentlogsfordifferentseverities
TheloggerruntimeTheloggerruntime
require 'Logger.php'; // Import the logger
set_error_handler(['Logger', 'handler']); // Set the handler code
// Set log entry destination for warnings and notices
Logger::$warning_notice_log = 'logs/warning_notice.log';
// Set log entry destination for critical errors
Logger::$critical_log = 'logs/critical.log';
// Force simulate a warning error with an empty explode function call,
explode();
// or force a triggered warning
trigger_error("A warning error happened", E_WARNING);
// Force simulate a critical error with an unloaded class.
try{
$object = new MissingObject();
} catch (Throwable $e){
Logger::handler(E_ERROR, $e->getMessage(), $e->getFile(), $e->getLine());
echo 'Server unable to grant request at this time';
}
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 28/39© 2019 Rogue Wave Software, Inc. All rights reserved
Code:DifferentlogsfordifferentseveritiesCode:Differentlogsfordifferentseverities
LogentriesLogentries
The Critical log entry:
20190414.11.04.27|Class 'MissingObject' not found|<path/to/runtime.php>|25
The Warning and Notice log entries:
20190414.11.04.29|explode() expects at least 2 parameters, 0 given|<path/to/runtime.php>|18
20190414.11.04.58|Invalid error type specified|<path/to/runtime.php>|21
Don'tforgettomonitorthelogs!Don'tforgettomonitorthelogs!
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 29/39© 2019 Rogue Wave Software, Inc. All rights reserved
UpdatingPHPonastagingserverUpdatingPHPonastagingserver
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 30/39© 2019 Rogue Wave Software, Inc. All rights reserved
UpdatingPHPonastagingserverUpdatingPHPonastagingserver
Production servers must be kept up to date for the security, bug xes,
and system optimization bene ts.
A staging server is a server environment that:
Matches a production server
Same software
Same software update process
Identical in deployment process
Can fail without production impact
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 31/39© 2019 Rogue Wave Software, Inc. All rights reserved
UpdatingPHPonastagingserverUpdatingPHPonastagingserver
A Staging server allows re nements to all update, deployment, and
continuous delivery processes.
But, should be subject to the same rigor as a production server,
including:
Assessment process
Functionality
Performance requirements
Security
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 32/39© 2019 Rogue Wave Software, Inc. All rights reserved
RecapRecap
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 33/39© 2019 Rogue Wave Software, Inc. All rights reserved
RecapRecap
Let's recap:
Input injection handling of a few of the most predominate attacks
The di erence between the Web server and PHP application error
logging
Setup di erent logs for di erent severities
Staging server purpose and recommendations
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 34/39© 2019 Rogue Wave Software, Inc. All rights reserved
$3.86 million
Average cost of a data breach
197 days
Mean time to identify a breach
75%
of attacks occur on web apps
27%
likelihood of a recurring material breach
over the next two years
Over 60%
are running on vulnerable, unsupported
PHP runtime versions
BusinessimpactofapplicationsecurityBusinessimpactofapplicationsecurity
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 35/39© 2019 Rogue Wave Software, Inc. All rights reserved
Zend Server is a commercially
supported & secure PHP
destribution
Wide range of professional
services including migration,
audits & custom consulting
Online & onsite PHP training
from beginner to advanced, plus
PHP certi cation
HowcanRogueWavehelp?HowcanRogueWavehelp?
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 36/39© 2019 Rogue Wave Software, Inc. All rights reserved
What'snext?What'snext?
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 37/39© 2019 Rogue Wave Software, Inc. All rights reserved
ResourcesResources
Some followup resources:
Zend Server: zend.com/en/products/zend_server
PHP Security, support and migration: zend.com/phpsecurity
Training, PHP security and more: zend.com/en/services/training
2019 State of PHP Survey: https://www.surveymonkey.com/r/2019-
state-of-php
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 38/39© 2019 Rogue Wave Software, Inc. All rights reserved
Q&AQ&A
4/24/2019 Security Best Practices
webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 39/39© 2019 Rogue Wave Software, Inc. All rights reserved
Thankyou!Thankyou!
Contact Ryan: ryan.krszjzaniek@roguewave.com
Contact Daryl: daryl.wood@roguewave.com
Follow me on Twitter: @datashuttle

Más contenido relacionado

Más de Zend by Rogue Wave Software

Fundamentals of performance tuning PHP on IBM i
Fundamentals of performance tuning PHP on IBM i  Fundamentals of performance tuning PHP on IBM i
Fundamentals of performance tuning PHP on IBM i Zend by Rogue Wave Software
 
Standard CMS on standard PHP Stack - Drupal and Zend Server
Standard CMS on standard PHP Stack - Drupal and Zend ServerStandard CMS on standard PHP Stack - Drupal and Zend Server
Standard CMS on standard PHP Stack - Drupal and Zend ServerZend by Rogue Wave Software
 

Más de Zend by Rogue Wave Software (20)

Middleware web APIs in PHP 7.x
Middleware web APIs in PHP 7.xMiddleware web APIs in PHP 7.x
Middleware web APIs in PHP 7.x
 
Ongoing management of your PHP 7 application
Ongoing management of your PHP 7 applicationOngoing management of your PHP 7 application
Ongoing management of your PHP 7 application
 
Developing web APIs using middleware in PHP 7
Developing web APIs using middleware in PHP 7Developing web APIs using middleware in PHP 7
Developing web APIs using middleware in PHP 7
 
The Docker development template for PHP
The Docker development template for PHPThe Docker development template for PHP
The Docker development template for PHP
 
The most exciting features of PHP 7.1
The most exciting features of PHP 7.1The most exciting features of PHP 7.1
The most exciting features of PHP 7.1
 
Unit testing for project managers
Unit testing for project managersUnit testing for project managers
Unit testing for project managers
 
The new features of PHP 7
The new features of PHP 7The new features of PHP 7
The new features of PHP 7
 
Deploying PHP apps on the cloud
Deploying PHP apps on the cloudDeploying PHP apps on the cloud
Deploying PHP apps on the cloud
 
Data is dead. Long live data!
Data is dead. Long live data! Data is dead. Long live data!
Data is dead. Long live data!
 
Optimizing performance
Optimizing performanceOptimizing performance
Optimizing performance
 
Resolving problems & high availability
Resolving problems & high availabilityResolving problems & high availability
Resolving problems & high availability
 
Developing apps faster
Developing apps fasterDeveloping apps faster
Developing apps faster
 
Keeping up with PHP
Keeping up with PHPKeeping up with PHP
Keeping up with PHP
 
Fundamentals of performance tuning PHP on IBM i
Fundamentals of performance tuning PHP on IBM i  Fundamentals of performance tuning PHP on IBM i
Fundamentals of performance tuning PHP on IBM i
 
Getting started with PHP on IBM i
Getting started with PHP on IBM iGetting started with PHP on IBM i
Getting started with PHP on IBM i
 
Continuous Delivery e-book
Continuous Delivery e-bookContinuous Delivery e-book
Continuous Delivery e-book
 
Standard CMS on standard PHP Stack - Drupal and Zend Server
Standard CMS on standard PHP Stack - Drupal and Zend ServerStandard CMS on standard PHP Stack - Drupal and Zend Server
Standard CMS on standard PHP Stack - Drupal and Zend Server
 
Dev & Prod - PHP Applications in the Cloud
Dev & Prod - PHP Applications in the CloudDev & Prod - PHP Applications in the Cloud
Dev & Prod - PHP Applications in the Cloud
 
The Truth about Lambdas and Closures in PHP
The Truth about Lambdas and Closures in PHPThe Truth about Lambdas and Closures in PHP
The Truth about Lambdas and Closures in PHP
 
Application Deployment on IBM i
Application Deployment on IBM iApplication Deployment on IBM i
Application Deployment on IBM i
 

Último

Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonApplitools
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...OnePlan Solutions
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingShane Coughlan
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesKrzysztofKkol1
 
Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Anthony Dahanne
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxRTS corp
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingShane Coughlan
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
SoftTeco - Software Development Company Profile
SoftTeco - Software Development Company ProfileSoftTeco - Software Development Company Profile
SoftTeco - Software Development Company Profileakrivarotava
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptxVinzoCenzo
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogueitservices996
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencessuser9e7c64
 

Último (20)

Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
 
Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
SoftTeco - Software Development Company Profile
SoftTeco - Software Development Company ProfileSoftTeco - Software Development Company Profile
SoftTeco - Software Development Company Profile
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptx
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogue
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conference
 

PHP application code best practices

  • 1. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 1/39© 2019 Rogue Wave Software, Inc. All rights reserved Webinar series: PHP security best practices Part 2: Web security best practices for PHP
  • 2. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 2/39© 2019 Rogue Wave Software, Inc. All rights reserved PHPsecuritybestpracticesPHPsecuritybestpractices by Daryl Wood Senior Technical Trainer Webinar, April 25, 2019 Rogue Wave Software, Inc.
  • 3. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 3/39© 2019 Rogue Wave Software, Inc. All rights reserved SessiononerecapSessiononerecap
  • 4. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 4/39© 2019 Rogue Wave Software, Inc. All rights reserved PHPsecuritybestpracticesPHPsecuritybestpractices FirstsessionrecapFirstsessionrecap Part one of this series included: Security attack types Log monitoring Attack injection Attack severities and impacts PHP version end of life
  • 5. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 5/39© 2019 Rogue Wave Software, Inc. All rights reserved PHPapplicationsecurityPHPapplicationsecurity BestpracticefundamentalsBestpracticefundamentals Today's part of this includes: Code: Injection handling input and output Logs: Web server (Apache) and PHP application Code: Di erent logs for di erent severities Updating PHP on a staging server
  • 6. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 6/39© 2019 Rogue Wave Software, Inc. All rights reserved CodeCode InjectionhandlinginputandoutputInjectionhandlinginputandoutput
  • 7. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 7/39© 2019 Rogue Wave Software, Inc. All rights reserved Code:InjectionhandlinginputandoutputCode:Injectionhandlinginputandoutput InputreviewInputreview What's considered data input: A request from a web client A data payload from a web service call A data payload from an asynchronous (AJAX) request Data from a persistent storage mechanism
  • 8. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 8/39© 2019 Rogue Wave Software, Inc. All rights reserved Crosssiteinjection(XSS)Crosssiteinjection(XSS)
  • 9. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 9/39© 2019 Rogue Wave Software, Inc. All rights reserved Code:InjectionhandlinginputandoutputCode:Injectionhandlinginputandoutput InputfilteringforXSSinjectionInputfilteringforXSSinjection VulnerablecodeVulnerablecode // Simulate injected post data $_POST['username'] = 'pablo'; $_POST['comment'] = '<script>alert("document.cookie")</script>'; if($_POST && isset($_POST['username') && isset($_POST['comment'])) { $result = null; try { $pdo = new PDO('mysql:unix_socket=/var/run/mysqld/mysqld.sock;dbname=blog', 'vagrant', 'vagrant'); $stmt = $pdo->query("INSERT INTO blog (username, comment) VALUES ({$_POST['username']}, {$_POST['comment']})"); if($stmt) $stmt->execute(); // Then subsequently $result = $pdo->exec("SELECT * FROM blog WHERE username='{$_POST['username']}'"); } catch (Throwable $e){ // Handle ... } if($result){ echo $result['comment']; } }
  • 10. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 10/39© 2019 Rogue Wave Software, Inc. All rights reserved Code:InjectionhandlinginputandoutputCode:Injectionhandlinginputandoutput InputfilteringforXSSinjectionInputfilteringforXSSinjection FilteredcodeFilteredcode // Simulate injected post data $_POST['username'] = 'pablo'; $_POST['comment'] = '<script>alert("document.cookie")</script>'; // This code should be owned by the initial domain input handling if($_POST && isset($_POST['username') && isset($_POST['comment'])) { // Looking for an alpha numeric value $cleanUsername = ctype_alnum($_POST['username']) ? $_POST['username'] : false; // Looking for tag-based injection and stripping the tags $cleanComment = strip_tags($_POST['comment']) ?? false; if($cleanUsername && $cleanComment) { // Persist the data with $cleanUsername and $cleanComment escaping with: // * htmlspecialchars() // * htmlentities() // * or your framework escaping mechanism } }
  • 11. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 11/39© 2019 Rogue Wave Software, Inc. All rights reserved SQLinjectionSQLinjection
  • 12. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 12/39© 2019 Rogue Wave Software, Inc. All rights reserved Code:InjectionhandlinginputandoutputCode:Injectionhandlinginputandoutput InputfilteringforSQLinjectionInputfilteringforSQLinjection VulnerablecodeVulnerablecode // Simulate injected get data $_GET['id'] = ';update blog set username = attacker where user_id = 1;'; $_GET['new-password'] = 'e44sxdfg3'; $_GET['submit'] = 'submit'; if ($_GET && isset($_GET['Submit'])) { //Employ ACL to determine access try { $pdo = new PDO('mysql:unix_socket=/var/run/mysqld/mysqld.sock;dbname=blog', 'vagrant', 'vagrant'); $stmt = $pdo->query("SELECT first_name, last_name FROM blog WHERE user_id = '{$_GET['id']}'"); $stmt->execute(); $result = $stmt->fetch(PDO::FETCH_ASSOC); } catch (PDOException $e) { // Handle ... } }
  • 13. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 13/39© 2019 Rogue Wave Software, Inc. All rights reserved Code:InjectionhandlinginputandoutputCode:Injectionhandlinginputandoutput InputfilteringforSQLinjectionInputfilteringforSQLinjection FilteredcodeFilteredcode // Simulate injected get data $_GET['id'] = ';update blog set username = attacker where user_id = 1;'; $_GET['new-password'] = 'e44sxdfg3'; $_GET['submit'] = 'submit'; if ($_GET && isset($_GET['id']) && isset($_GET['Submit'])) { //Employ ACL to determine access // Filter by type coercion on integer-type identifier $cleanId = (int)$_GET['id']; // Filter by using the ctype_alnum() function for none integer-type // identifiers, and assuming here alpha numeric $cleanId = ctype_alnum($_GET['id']) ? $_GET['id'] : false; // Filter by stripping tags, as passwords can be just about any character combination $cleanPass = strip_tags($_GET['new-password']); if($cleanId && $cleanPass) { // Escape, then persist and update the data with $cleanId and $cleanPass ... } else { echo 'Data invalid'; } }
  • 14. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 14/39© 2019 Rogue Wave Software, Inc. All rights reserved BrokensessionmanagementBrokensessionmanagement
  • 15. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 15/39© 2019 Rogue Wave Software, Inc. All rights reserved Code:InjectionhandlinginputandoutputCode:Injectionhandlinginputandoutput BrokensessionmanagementBrokensessionmanagement VulnerablecodeVulnerablecode // A controller responsible for login/logout actions class LoginController { // ... public function logoutAction() { $this->view->setTemplate('login'); $this->view->render(); } // ... }
  • 16. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 16/39© 2019 Rogue Wave Software, Inc. All rights reserved Code:InjectionhandlinginputandoutputCode:Injectionhandlinginputandoutput BrokensessionmanagementBrokensessionmanagement RepairedcodeRepairedcode // Assuming a controller handles the fix directly, or indirectly. class LoginController { // ... public function logoutAction() { // Destroy the session here, session_destroy(); // or with some injected and dedicated Session-responsible // object calling its destroy() method. $this->session->destroy(); $this->view->setTemplate('login'); $this->view->render(); } // ... }
  • 17. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 17/39© 2019 Rogue Wave Software, Inc. All rights reserved BruteforceBruteforce
  • 18. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 18/39© 2019 Rogue Wave Software, Inc. All rights reserved Code:InjectionhandlinginputandoutputCode:Injectionhandlinginputandoutput BruteforceBruteforce VulnerablecodeVulnerablecode // Simulate a billion-fold brute force attempt with minor changes to the password. $_POST['username'] = 'admin'; $_POST['password'] = 'pA$$wORD'; if($_POST && isset($_POST['username']) && isset($_POST['password'])) { $result = false; $password = md5($_POST['password']); try{ $stmt = $this->getPdo()->query("SELECT * FROM users WHERE username='{$_POST['username']}' AND password='$password'"); $stmt->execute(); $result = $stmt->fetch(PDO::FETCH_ASSOC); }catch(PDOException $e){ // Handle ... } if($result && count($result)) { // On success // Redirect to password-protected area } else { // On failure echo "<p>Login unsuccessful</p>"; } }
  • 19. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 19/39© 2019 Rogue Wave Software, Inc. All rights reserved Code:InjectionhandlinginputandoutputCode:Injectionhandlinginputandoutput BruteforceBruteforce RepairedcodeRepairedcode // Simulate a billion-fold brute force attempt with minor changes to the password. $_POST['username'] = 'admin'; $_POST['password'] = 'pA$$wORD'; if($_POST && isset($_POST['username']) && isset($_POST['password'])) { // Execute brute force detection code here ... $cleanUser = ctype_alnum($_POST['username']) ? $_POST['username'] : false; if($cleanUser){ try{ $stmt = $this->getPdo()->query("SELECT * FROM users WHERE username='$cleanUser'"); $stmt->execute(); $result = $stmt->fetch(PDO::FETCH_ASSOC); }catch(PDOException $e) { // Handle ... } } if($result && count($result) && password_verify($_POST['password'], $result['password']) ) { // Login successful, redirect to password-protected area escaping any input used ... } else { //Login failed echo "<p>Login unsuccessful</p>"; // Execute brute force detection code to record failed attempt } }
  • 20. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 20/39© 2019 Rogue Wave Software, Inc. All rights reserved LogsLogs Webserver(Apache)andPHPapplicationWebserver(Apache)andPHPapplication
  • 21. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 21/39© 2019 Rogue Wave Software, Inc. All rights reserved Logs:Webserver(Apache)andPHPapplicationLogs:Webserver(Apache)andPHPapplication LoglocationLoglocation Here restated are the default log locations for a Debian-based Linux server and PHP installation: Syslog: /var/log/syslog Apache access: /var/log/apache2/access.log Apache error: /var/log/apache2/error.log PHP error When enabled, and by default, is the syslog. Instead of these defaults, we concern ourselves with Apache access and error logging for a speci c host, and separate logs for critical PHP error severities from all other severities.
  • 22. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 22/39© 2019 Rogue Wave Software, Inc. All rights reserved Logs:Webserver(Apache)andPHPapplicationLogs:Webserver(Apache)andPHPapplication SpecificApachehostloggingSpecificApachehostlogging This code block shows an Apache virtual host con guration for host- speci c access and error logging. https://httpd.apache.org/ <VirtualHost *:80> ServerName rockets.com DocumentRoot /var/www/rockets <Directory /var/www/rockets/> Options Indexes FollowSymLinks MultiViews AllowOverride All Require all granted </Directory> # Custom host-specific logging ErrorLog /var/www/rockets/error.log CustomLog /var/www/rockets/access.log combined </VirtualHost>
  • 23. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 23/39© 2019 Rogue Wave Software, Inc. All rights reserved Logs:Webserver(Apache)andPHPapplicationLogs:Webserver(Apache)andPHPapplication PHPapplicationerrorloggingPHPapplicationerrorlogging These code blocks shows production environment PHP con guration directives enabling error reporting, logging, and location for application-speci c PHP error logging. In a web server php.ini con guration le: error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT log_errors = On error_log = /var/www/rocket/logs/error.log
  • 24. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 24/39© 2019 Rogue Wave Software, Inc. All rights reserved CodeCode DifferentlogsfordifferentseveritiesDifferentlogsfordifferentseverities
  • 25. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 25/39© 2019 Rogue Wave Software, Inc. All rights reserved CodeCode DifferentlogsfordifferentseveritiesDifferentlogsfordifferentseverities It is often helpful to direct speci c error severities to dedicated log les. The next few slides de ne one way of doing that in object-oriented code.
  • 26. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 26/39© 2019 Rogue Wave Software, Inc. All rights reserved Code:DifferentlogsfordifferentseveritiesCode:Differentlogsfordifferentseverities ALoggerclassALoggerclass class Logger{ public static $critical_log, $warning_notice_log; protected static $error; public static function handler(...$error) { self::$error = $error; // Checks if error code is not part of error_reporting and bail if (!(error_reporting() & self::$error[0])) return; self::log(); } public static function log(){ $logEntry = date('Ymd.h.m.s').'|'.self::$error[1].'|'.self::$error[2].'|'. self::$error[3] . PHP_EOL; switch (true){ case (self::$error[0] === E_ERROR || self::$error[0] === E_USER_ERROR): return error_log($logEntry, 3, self::$critical_log); case (self::$error[0] === E_WARNING || self::$error[0] === E_NOTICE): return error_log($logEntry, 3, self::$warning_notice_log); // ... } return false; } }
  • 27. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 27/39© 2019 Rogue Wave Software, Inc. All rights reserved Code:DifferentlogsfordifferentseveritiesCode:Differentlogsfordifferentseverities TheloggerruntimeTheloggerruntime require 'Logger.php'; // Import the logger set_error_handler(['Logger', 'handler']); // Set the handler code // Set log entry destination for warnings and notices Logger::$warning_notice_log = 'logs/warning_notice.log'; // Set log entry destination for critical errors Logger::$critical_log = 'logs/critical.log'; // Force simulate a warning error with an empty explode function call, explode(); // or force a triggered warning trigger_error("A warning error happened", E_WARNING); // Force simulate a critical error with an unloaded class. try{ $object = new MissingObject(); } catch (Throwable $e){ Logger::handler(E_ERROR, $e->getMessage(), $e->getFile(), $e->getLine()); echo 'Server unable to grant request at this time'; }
  • 28. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 28/39© 2019 Rogue Wave Software, Inc. All rights reserved Code:DifferentlogsfordifferentseveritiesCode:Differentlogsfordifferentseverities LogentriesLogentries The Critical log entry: 20190414.11.04.27|Class 'MissingObject' not found|<path/to/runtime.php>|25 The Warning and Notice log entries: 20190414.11.04.29|explode() expects at least 2 parameters, 0 given|<path/to/runtime.php>|18 20190414.11.04.58|Invalid error type specified|<path/to/runtime.php>|21 Don'tforgettomonitorthelogs!Don'tforgettomonitorthelogs!
  • 29. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 29/39© 2019 Rogue Wave Software, Inc. All rights reserved UpdatingPHPonastagingserverUpdatingPHPonastagingserver
  • 30. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 30/39© 2019 Rogue Wave Software, Inc. All rights reserved UpdatingPHPonastagingserverUpdatingPHPonastagingserver Production servers must be kept up to date for the security, bug xes, and system optimization bene ts. A staging server is a server environment that: Matches a production server Same software Same software update process Identical in deployment process Can fail without production impact
  • 31. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 31/39© 2019 Rogue Wave Software, Inc. All rights reserved UpdatingPHPonastagingserverUpdatingPHPonastagingserver A Staging server allows re nements to all update, deployment, and continuous delivery processes. But, should be subject to the same rigor as a production server, including: Assessment process Functionality Performance requirements Security
  • 32. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 32/39© 2019 Rogue Wave Software, Inc. All rights reserved RecapRecap
  • 33. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 33/39© 2019 Rogue Wave Software, Inc. All rights reserved RecapRecap Let's recap: Input injection handling of a few of the most predominate attacks The di erence between the Web server and PHP application error logging Setup di erent logs for di erent severities Staging server purpose and recommendations
  • 34. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 34/39© 2019 Rogue Wave Software, Inc. All rights reserved $3.86 million Average cost of a data breach 197 days Mean time to identify a breach 75% of attacks occur on web apps 27% likelihood of a recurring material breach over the next two years Over 60% are running on vulnerable, unsupported PHP runtime versions BusinessimpactofapplicationsecurityBusinessimpactofapplicationsecurity
  • 35. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 35/39© 2019 Rogue Wave Software, Inc. All rights reserved Zend Server is a commercially supported & secure PHP destribution Wide range of professional services including migration, audits & custom consulting Online & onsite PHP training from beginner to advanced, plus PHP certi cation HowcanRogueWavehelp?HowcanRogueWavehelp?
  • 36. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 36/39© 2019 Rogue Wave Software, Inc. All rights reserved What'snext?What'snext?
  • 37. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 37/39© 2019 Rogue Wave Software, Inc. All rights reserved ResourcesResources Some followup resources: Zend Server: zend.com/en/products/zend_server PHP Security, support and migration: zend.com/phpsecurity Training, PHP security and more: zend.com/en/services/training 2019 State of PHP Survey: https://www.surveymonkey.com/r/2019- state-of-php
  • 38. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 38/39© 2019 Rogue Wave Software, Inc. All rights reserved Q&AQ&A
  • 39. 4/24/2019 Security Best Practices webinars/SecurityBestPractices2/Webinar_Materials/?print-pdf#/ 39/39© 2019 Rogue Wave Software, Inc. All rights reserved Thankyou!Thankyou! Contact Ryan: ryan.krszjzaniek@roguewave.com Contact Daryl: daryl.wood@roguewave.com Follow me on Twitter: @datashuttle