SlideShare a Scribd company logo
Explicit Code & QA
So, who are you, anyway?

                  Bryan C. Geraghty
          Security Consultant at Security PS
                     @archwisp

  I’m a Sr. PHP developer with a systems and security
   engineering background - turned application security
                       consultant
Remember, layers
Simpler is easier to test
Don’t make assumptions
Compromised browser = game over
These are not specifically security activities but they produce more
stable code
Don’t rely on the server’s configuration
  Your bootstrap should       Absolute Minimum
  set the defaults for any     Include paths
  PHP core functionality       Error reporting
  that your application is
                               Time zones
  using.
  These must be
  customizable for every
  environment
  e.g. (dev, staging, live)
Example Bootstrap
<?php

// All environment configuration for this application is done from this file

ini_set('display_errors', 0);
ini_set('error_reporting', -1);

date_default_timezone_set('UTC');

$rootPath = dirname(__FILE__);

set_include_path(sprintf(
   '%s%s%s%s',
   $rootPath, PATH_SEPARATOR, $rootPath, '/third-party'
));

require_once('MindFrame2/AutoLoad.php');
MindFrame2_AutoLoad::install();
Creating "Secure" PHP Applications, Part 1, Explicit Code & QA
Don’t use global constants, variables, or registries

 You can’t be certain that nobody else will ever use the
  same global constant name
 Tracking down where a value is assigned to a global
  variable is usually very difficult
 Global variables remove control of that variable from the
  current scope
 Global registries are really just fancy global variables and
  the same problems apply
Value Reference Rules
 Values should only be referenced in one of the following
  ways:
   A direct reference in the current scope:
    $limit = $this->_objectPool->getConfig()-
      >getDefaultLimit();
   A parameter:
    public function getUsers($limit) {
      return $this->_objectPool-
      >getMapper(‘User’)->fetchAll($limit);
    }
Don’t use function parameter defaults
   "There should be one-- and preferably only one --
   obvious way to do it." - Tim Peters

 Reduces understanding from the caller perspective
 Often add unnecessary complexity
 Represents the most common use-case
 Other use-cases are often ignored entirely
 Changing the default breaks all implementations
 Adding parameters breaks default implementations
Default parameter example
class User
{
   public function __construct($name, $email, $status = self::STATUS_ACTIVE) {
          $this->_name = $name;
          $this->_email = $email;
          $this->_status = $status;
   }
}

function createUser($name, $email, $status) {
   $user = new User($name, email);
   return $this->_objectPoool->getMapper(‘User’)->create($user);
}
Use explicit operators whenever possible
This was actual production code.
if ($sincedate && (int)$sincedate) {
 $param["UpdatedSinceDate"] =
    date("Y-m-d H:i:s", strtotime(time() - ((int)$sincedate)*60*60);
} elseif ($sincedate && strtotime($sincedate)) {
 $param["UpdatedSinceDate"] =
    date("Y-m-d H:i:s", strtotime($sincedate));
} elseif(!isset($param["UpdatedSinceDate"])) {
 exit ("Invalid param UpdatedSinceDate");
}



Do you think this code worked as the author intended when $sincedate was set to
'2011-05-31'?
Use constants for possible values
Constants cannot be re-defined, so using a constant for configuration limits your code
to only ever be able to run in one configuration in a given stack.


// Bad: This code cannot execute differently in the same stack
define(‘PDO_FETCH_MODE’, 2);
$dbi->fetchAll(PDO_FETCH_MODE);

// Better: The value can change but this literal value means nothing without
// referencing the documentation
$dbi->fetchAll(2);

// Best: Implemented using a meaningful constant which represents a *possible* value
$dbi->fetchAll(PDO::FETCH_ASSOC);
Use wrappers for super-globals
 $_REQUEST, $_GET, $_SESSION, and $_FILES are the most
  commonly used PHP super-globals but there are others
 It’s easy to create some serious security problems
 It’s best to use a wrapper for interacting with these
  variables
Simulate strong/static types
PHP is dynamically typed, so we cannot do true strong or static typing but we can
put controls in place which provide the same protection.

private function _buildSelectDatabaseTableSql($database_name, $table_name,
     array $select_data, array $order_by_columns, $offset, $limit)
  {
     MindFrame2_Core::assertArgumentIsNotBlank($database_name, 1, 'database_name');
     MindFrame2_Core::assertArgumentIsNotBlank($table_name, 2, 'table_name');
     MindFrame2_Core::assertArgumentIsInt($offset, 5, 'offset');
     MindFrame2_Core::assertArgumentIsInt($limit, 6, 'limit');

      $skel = "SELECTn   %snFROMn   %s.%sn%s%s%s%s;";

      $sql = sprintf($skel,
         $this->_buildSelectTableSqlFieldClause($table_name),
         $this->getSharedModule()->escapeDbElementName($database_name),
         $this->getSharedModule()->escapeDbElementName($table_name),
         $this->_buildSelectTableSqlJoinClause(
            $this->getSharedModule()->getDatabase()->getName(), $table_name),
         $this->_buildSelectTableSqlWhereClause($table_name, $select_data),
         $this->_buildSelectTableSqlOrderByClause(
            $table_name, $order_by_columns),
         $this->_buildSelectTableSqlLimitClause($offset, $limit));

      return $sql;
  }
Example Typing Assertions
public static function assertArgumentIsInt($value, $position, $name)
{
   if (!is_int($value)) {
      $skel = 'Expected integer value for argument #%d (%s), %s given';
      $message = sprintf($skel, $position, $name, gettype($value));
      throw new InvalidArgumentException($message);
   }
}

public static function assertArgumentIsNotBlank($value, $position, $name)
{
   if (trim($value) === '') {
      $skel = 'Argument #%d (%s) cannot be blank';
      $message = sprintf($skel, $position, $name);

        throw new InvalidArgumentException($message);
    }
}
Use PHPMD & CodeSniffer
This is the ./bin/codecheck script in MindFrame2
#!/bin/bash

WD="`/usr/bin/dirname $0`/../";
echo Changing to working directory: $WD;
cd $WD;

if [ -z $1 ]; then
     DIR='.';
else
     DIR=$1;
fi

phpmd --exclude coverage $DIR text codesize,unusedcode,naming,design
phpcs --ignore=coverage --standard=`pwd`/Standards/MindFrame2 $DIR
phpcs --ignore=coverage --report=source --standard=`pwd`/Standards/MindFrame2 $DIR
Example PHPMD Output
bryan@ubuntu-virtual ~/Code/MindFrame2 [130] $ ./bin/codecheck Dbms/Dbi
Changing to working directory: ./bin/../

/home/bryan/Code/MindFrame2/Dbms/Dbi/Distributed.php:128         Avoid unused local
variables such as '$partner'.
/home/bryan/Code/MindFrame2/Dbms/Dbi/Distributed.php:185         Avoid unused local
variables such as '$data'.
/home/bryan/Code/MindFrame2/Dbms/Dbi/Distributed.php:199         Avoid unused local
variables such as '$index'.
/home/bryan/Code/MindFrame2/Dbms/Dbi/Distributed.php:240         Avoid unused private
methods such as '_buildReplicaDatabaseSuffix'.
/home/bryan/Code/MindFrame2/Dbms/Dbi/Single.php:25       This class has too many
methods, consider refactoring it.
/home/bryan/Code/MindFrame2/Dbms/Dbi/Single.php:150      Avoid unused parameters such as
'$options'.
Example PHPCS Output
FILE: /home/bryan/Code/MindFrame2/Dbms/Dbi/Single.php
--------------------------------------------------------------------------------
FOUND 6 ERROR(S) AFFECTING 6 LINE(S)
--------------------------------------------------------------------------------
  39 | ERROR | Public member variables ("_connection") are forbidden
  62 | ERROR | Whitespace found at end of line
 144 | ERROR | Whitespace found at end of line
 160 | ERROR | Line exceeds maximum limit of 80 characters; contains 97
     |       | characters
 195 | ERROR | Whitespace found at end of line
 298 | ERROR | Line exceeds maximum limit of 80 characters; contains 81
     |       | characters
--------------------------------------------------------------------------------
Unit testing / TDD
 Test critical functionality at a minimum
 Add edge cases to regression tests as they are discovered
 Test-driven development only works if the entire team is
  dedicated to it
 I personally don’t trust code that isn’t regression-tested;
  even if it was written by me
Continuous Integration
 Automated system for code analysis and regression
  testing
 There are a lot of continuous integration systems for PHP
 If your tests aren’t automated, very few people will know
  or care when they break
Deployment
 Manually copying files is riddled with problems
 Tagging releases and re-deploying is a complicated and
  time-consuming process
 Deployment systems automate the build and deployment
  process
ACLs
MAC
Thread limits
Unwanted services
If you’re interested in an application security career, come talk with
me.

More Related Content

What's hot (20)

Beginning PHPUnit
Beginning PHPUnitBeginning PHPUnit
Beginning PHPUnit
Jace Ju
 
Php security3895
Php security3895Php security3895
Php security3895
PrinceGuru MS
 
Functional Structures in PHP
Functional Structures in PHPFunctional Structures in PHP
Functional Structures in PHP
Marcello Duarte
 
Dsl
DslDsl
Dsl
phoet
 
Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4
Jeff Carouth
 
Perl6 in-production
Perl6 in-productionPerl6 in-production
Perl6 in-production
Andrew Shitov
 
Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8
PrinceGuru MS
 
The Joy of Smartmatch
The Joy of SmartmatchThe Joy of Smartmatch
The Joy of Smartmatch
Andrew Shitov
 
The Art Of Readable Code
The Art Of Readable CodeThe Art Of Readable Code
The Art Of Readable Code
Baidu, Inc.
 
Text in search queries with examples in Perl 6
Text in search queries with examples in Perl 6Text in search queries with examples in Perl 6
Text in search queries with examples in Perl 6
Andrew Shitov
 
Introduction to Twig
Introduction to TwigIntroduction to Twig
Introduction to Twig
markstory
 
Improving Dev Assistant
Improving Dev AssistantImproving Dev Assistant
Improving Dev Assistant
Dave Cross
 
(Parameterized) Roles
(Parameterized) Roles(Parameterized) Roles
(Parameterized) Roles
sartak
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
Lorna Mitchell
 
Symfony2 and Doctrine2 Integration
Symfony2 and Doctrine2 IntegrationSymfony2 and Doctrine2 Integration
Symfony2 and Doctrine2 Integration
Jonathan Wage
 
Smarty
SmartySmarty
Smarty
Mohammad Bagher Adib Behrooz
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
Kang-min Liu
 
The art of readable code (ch1~ch4)
The art of readable code (ch1~ch4)The art of readable code (ch1~ch4)
The art of readable code (ch1~ch4)
Ki Sung Bae
 
Perl6 grammars
Perl6 grammarsPerl6 grammars
Perl6 grammars
Andrew Shitov
 
Making the most of 2.2
Making the most of 2.2Making the most of 2.2
Making the most of 2.2
markstory
 
Beginning PHPUnit
Beginning PHPUnitBeginning PHPUnit
Beginning PHPUnit
Jace Ju
 
Functional Structures in PHP
Functional Structures in PHPFunctional Structures in PHP
Functional Structures in PHP
Marcello Duarte
 
Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4
Jeff Carouth
 
Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8
PrinceGuru MS
 
The Joy of Smartmatch
The Joy of SmartmatchThe Joy of Smartmatch
The Joy of Smartmatch
Andrew Shitov
 
The Art Of Readable Code
The Art Of Readable CodeThe Art Of Readable Code
The Art Of Readable Code
Baidu, Inc.
 
Text in search queries with examples in Perl 6
Text in search queries with examples in Perl 6Text in search queries with examples in Perl 6
Text in search queries with examples in Perl 6
Andrew Shitov
 
Introduction to Twig
Introduction to TwigIntroduction to Twig
Introduction to Twig
markstory
 
Improving Dev Assistant
Improving Dev AssistantImproving Dev Assistant
Improving Dev Assistant
Dave Cross
 
(Parameterized) Roles
(Parameterized) Roles(Parameterized) Roles
(Parameterized) Roles
sartak
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
Lorna Mitchell
 
Symfony2 and Doctrine2 Integration
Symfony2 and Doctrine2 IntegrationSymfony2 and Doctrine2 Integration
Symfony2 and Doctrine2 Integration
Jonathan Wage
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
Kang-min Liu
 
The art of readable code (ch1~ch4)
The art of readable code (ch1~ch4)The art of readable code (ch1~ch4)
The art of readable code (ch1~ch4)
Ki Sung Bae
 
Making the most of 2.2
Making the most of 2.2Making the most of 2.2
Making the most of 2.2
markstory
 

Similar to Creating "Secure" PHP Applications, Part 1, Explicit Code & QA (20)

Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
Michelangelo van Dam
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010
Michelangelo van Dam
 
Preparing for the next PHP version (5.6)
Preparing for the next PHP version (5.6)Preparing for the next PHP version (5.6)
Preparing for the next PHP version (5.6)
Damien Seguy
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012
Michelangelo van Dam
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
chartjes
 
php programming.pptx
php programming.pptxphp programming.pptx
php programming.pptx
rani marri
 
Static analysis saved my code tonight
Static analysis saved my code tonightStatic analysis saved my code tonight
Static analysis saved my code tonight
Damien Seguy
 
08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards
Denis Ristic
 
Php Best Practices
Php Best PracticesPhp Best Practices
Php Best Practices
Ansar Ahmed
 
Php Best Practices
Php Best PracticesPhp Best Practices
Php Best Practices
Ansar Ahmed
 
Php5 certification mock exams
Php5 certification mock examsPhp5 certification mock exams
Php5 certification mock exams
echo liu
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
Rowan Merewood
 
Workshop quality assurance for php projects - phpdublin
Workshop quality assurance for php projects - phpdublinWorkshop quality assurance for php projects - phpdublin
Workshop quality assurance for php projects - phpdublin
Michelangelo van Dam
 
Php Crash Course - Macq Electronique 2010
Php Crash Course - Macq Electronique 2010Php Crash Course - Macq Electronique 2010
Php Crash Course - Macq Electronique 2010
Michelangelo van Dam
 
Tool up your lamp stack
Tool up your lamp stackTool up your lamp stack
Tool up your lamp stack
AgileOnTheBeach
 
Tool Up Your LAMP Stack
Tool Up Your LAMP StackTool Up Your LAMP Stack
Tool Up Your LAMP Stack
Lorna Mitchell
 
Secure programming with php
Secure programming with phpSecure programming with php
Secure programming with php
Mohmad Feroz
 
Continuous feature-development
Continuous feature-developmentContinuous feature-development
Continuous feature-development
nhm taveer hossain khan
 
Introduction in php part 2
Introduction in php part 2Introduction in php part 2
Introduction in php part 2
Bozhidar Boshnakov
 
Dutch PHP Conference 2013: Distilled
Dutch PHP Conference 2013: DistilledDutch PHP Conference 2013: Distilled
Dutch PHP Conference 2013: Distilled
Zumba Fitness - Technology Team
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
Michelangelo van Dam
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010
Michelangelo van Dam
 
Preparing for the next PHP version (5.6)
Preparing for the next PHP version (5.6)Preparing for the next PHP version (5.6)
Preparing for the next PHP version (5.6)
Damien Seguy
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012
Michelangelo van Dam
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
chartjes
 
php programming.pptx
php programming.pptxphp programming.pptx
php programming.pptx
rani marri
 
Static analysis saved my code tonight
Static analysis saved my code tonightStatic analysis saved my code tonight
Static analysis saved my code tonight
Damien Seguy
 
08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards08 Advanced PHP #burningkeyboards
08 Advanced PHP #burningkeyboards
Denis Ristic
 
Php Best Practices
Php Best PracticesPhp Best Practices
Php Best Practices
Ansar Ahmed
 
Php Best Practices
Php Best PracticesPhp Best Practices
Php Best Practices
Ansar Ahmed
 
Php5 certification mock exams
Php5 certification mock examsPhp5 certification mock exams
Php5 certification mock exams
echo liu
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
Rowan Merewood
 
Workshop quality assurance for php projects - phpdublin
Workshop quality assurance for php projects - phpdublinWorkshop quality assurance for php projects - phpdublin
Workshop quality assurance for php projects - phpdublin
Michelangelo van Dam
 
Php Crash Course - Macq Electronique 2010
Php Crash Course - Macq Electronique 2010Php Crash Course - Macq Electronique 2010
Php Crash Course - Macq Electronique 2010
Michelangelo van Dam
 
Tool Up Your LAMP Stack
Tool Up Your LAMP StackTool Up Your LAMP Stack
Tool Up Your LAMP Stack
Lorna Mitchell
 
Secure programming with php
Secure programming with phpSecure programming with php
Secure programming with php
Mohmad Feroz
 
Ad

Recently uploaded (20)

Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdfArtificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Safe Software
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
Edge AI and Vision Alliance
 
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
Edge AI and Vision Alliance
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptxFIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Alliance
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
SOFTTECHHUB
 
High Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdfHigh Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdf
Safe Software
 
Data Validation and System Interoperability
Data Validation and System InteroperabilityData Validation and System Interoperability
Data Validation and System Interoperability
Safe Software
 
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
Safe Software
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data ResilienceFloods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
Edge AI and Vision Alliance
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
Safe Software
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API CatalogMuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdfArtificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Safe Software
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
Edge AI and Vision Alliance
 
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
Edge AI and Vision Alliance
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptxFIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Alliance
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
SOFTTECHHUB
 
High Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdfHigh Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdf
Safe Software
 
Data Validation and System Interoperability
Data Validation and System InteroperabilityData Validation and System Interoperability
Data Validation and System Interoperability
Safe Software
 
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
FME for Good: Integrating Multiple Data Sources with APIs to Support Local Ch...
Safe Software
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data ResilienceFloods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
Edge AI and Vision Alliance
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
Safe Software
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API CatalogMuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
Ad

Creating "Secure" PHP Applications, Part 1, Explicit Code & QA

  • 2. So, who are you, anyway? Bryan C. Geraghty Security Consultant at Security PS @archwisp I’m a Sr. PHP developer with a systems and security engineering background - turned application security consultant
  • 3. Remember, layers Simpler is easier to test Don’t make assumptions Compromised browser = game over
  • 4. These are not specifically security activities but they produce more stable code
  • 5. Don’t rely on the server’s configuration Your bootstrap should Absolute Minimum set the defaults for any  Include paths PHP core functionality  Error reporting that your application is  Time zones using. These must be customizable for every environment e.g. (dev, staging, live)
  • 6. Example Bootstrap <?php // All environment configuration for this application is done from this file ini_set('display_errors', 0); ini_set('error_reporting', -1); date_default_timezone_set('UTC'); $rootPath = dirname(__FILE__); set_include_path(sprintf( '%s%s%s%s', $rootPath, PATH_SEPARATOR, $rootPath, '/third-party' )); require_once('MindFrame2/AutoLoad.php'); MindFrame2_AutoLoad::install();
  • 8. Don’t use global constants, variables, or registries  You can’t be certain that nobody else will ever use the same global constant name  Tracking down where a value is assigned to a global variable is usually very difficult  Global variables remove control of that variable from the current scope  Global registries are really just fancy global variables and the same problems apply
  • 9. Value Reference Rules  Values should only be referenced in one of the following ways:  A direct reference in the current scope: $limit = $this->_objectPool->getConfig()- >getDefaultLimit();  A parameter: public function getUsers($limit) { return $this->_objectPool- >getMapper(‘User’)->fetchAll($limit); }
  • 10. Don’t use function parameter defaults "There should be one-- and preferably only one -- obvious way to do it." - Tim Peters  Reduces understanding from the caller perspective  Often add unnecessary complexity  Represents the most common use-case  Other use-cases are often ignored entirely  Changing the default breaks all implementations  Adding parameters breaks default implementations
  • 11. Default parameter example class User { public function __construct($name, $email, $status = self::STATUS_ACTIVE) { $this->_name = $name; $this->_email = $email; $this->_status = $status; } } function createUser($name, $email, $status) { $user = new User($name, email); return $this->_objectPoool->getMapper(‘User’)->create($user); }
  • 12. Use explicit operators whenever possible This was actual production code. if ($sincedate && (int)$sincedate) { $param["UpdatedSinceDate"] = date("Y-m-d H:i:s", strtotime(time() - ((int)$sincedate)*60*60); } elseif ($sincedate && strtotime($sincedate)) { $param["UpdatedSinceDate"] = date("Y-m-d H:i:s", strtotime($sincedate)); } elseif(!isset($param["UpdatedSinceDate"])) { exit ("Invalid param UpdatedSinceDate"); } Do you think this code worked as the author intended when $sincedate was set to '2011-05-31'?
  • 13. Use constants for possible values Constants cannot be re-defined, so using a constant for configuration limits your code to only ever be able to run in one configuration in a given stack. // Bad: This code cannot execute differently in the same stack define(‘PDO_FETCH_MODE’, 2); $dbi->fetchAll(PDO_FETCH_MODE); // Better: The value can change but this literal value means nothing without // referencing the documentation $dbi->fetchAll(2); // Best: Implemented using a meaningful constant which represents a *possible* value $dbi->fetchAll(PDO::FETCH_ASSOC);
  • 14. Use wrappers for super-globals  $_REQUEST, $_GET, $_SESSION, and $_FILES are the most commonly used PHP super-globals but there are others  It’s easy to create some serious security problems  It’s best to use a wrapper for interacting with these variables
  • 15. Simulate strong/static types PHP is dynamically typed, so we cannot do true strong or static typing but we can put controls in place which provide the same protection. private function _buildSelectDatabaseTableSql($database_name, $table_name, array $select_data, array $order_by_columns, $offset, $limit) { MindFrame2_Core::assertArgumentIsNotBlank($database_name, 1, 'database_name'); MindFrame2_Core::assertArgumentIsNotBlank($table_name, 2, 'table_name'); MindFrame2_Core::assertArgumentIsInt($offset, 5, 'offset'); MindFrame2_Core::assertArgumentIsInt($limit, 6, 'limit'); $skel = "SELECTn %snFROMn %s.%sn%s%s%s%s;"; $sql = sprintf($skel, $this->_buildSelectTableSqlFieldClause($table_name), $this->getSharedModule()->escapeDbElementName($database_name), $this->getSharedModule()->escapeDbElementName($table_name), $this->_buildSelectTableSqlJoinClause( $this->getSharedModule()->getDatabase()->getName(), $table_name), $this->_buildSelectTableSqlWhereClause($table_name, $select_data), $this->_buildSelectTableSqlOrderByClause( $table_name, $order_by_columns), $this->_buildSelectTableSqlLimitClause($offset, $limit)); return $sql; }
  • 16. Example Typing Assertions public static function assertArgumentIsInt($value, $position, $name) { if (!is_int($value)) { $skel = 'Expected integer value for argument #%d (%s), %s given'; $message = sprintf($skel, $position, $name, gettype($value)); throw new InvalidArgumentException($message); } } public static function assertArgumentIsNotBlank($value, $position, $name) { if (trim($value) === '') { $skel = 'Argument #%d (%s) cannot be blank'; $message = sprintf($skel, $position, $name); throw new InvalidArgumentException($message); } }
  • 17. Use PHPMD & CodeSniffer This is the ./bin/codecheck script in MindFrame2 #!/bin/bash WD="`/usr/bin/dirname $0`/../"; echo Changing to working directory: $WD; cd $WD; if [ -z $1 ]; then DIR='.'; else DIR=$1; fi phpmd --exclude coverage $DIR text codesize,unusedcode,naming,design phpcs --ignore=coverage --standard=`pwd`/Standards/MindFrame2 $DIR phpcs --ignore=coverage --report=source --standard=`pwd`/Standards/MindFrame2 $DIR
  • 18. Example PHPMD Output bryan@ubuntu-virtual ~/Code/MindFrame2 [130] $ ./bin/codecheck Dbms/Dbi Changing to working directory: ./bin/../ /home/bryan/Code/MindFrame2/Dbms/Dbi/Distributed.php:128 Avoid unused local variables such as '$partner'. /home/bryan/Code/MindFrame2/Dbms/Dbi/Distributed.php:185 Avoid unused local variables such as '$data'. /home/bryan/Code/MindFrame2/Dbms/Dbi/Distributed.php:199 Avoid unused local variables such as '$index'. /home/bryan/Code/MindFrame2/Dbms/Dbi/Distributed.php:240 Avoid unused private methods such as '_buildReplicaDatabaseSuffix'. /home/bryan/Code/MindFrame2/Dbms/Dbi/Single.php:25 This class has too many methods, consider refactoring it. /home/bryan/Code/MindFrame2/Dbms/Dbi/Single.php:150 Avoid unused parameters such as '$options'.
  • 19. Example PHPCS Output FILE: /home/bryan/Code/MindFrame2/Dbms/Dbi/Single.php -------------------------------------------------------------------------------- FOUND 6 ERROR(S) AFFECTING 6 LINE(S) -------------------------------------------------------------------------------- 39 | ERROR | Public member variables ("_connection") are forbidden 62 | ERROR | Whitespace found at end of line 144 | ERROR | Whitespace found at end of line 160 | ERROR | Line exceeds maximum limit of 80 characters; contains 97 | | characters 195 | ERROR | Whitespace found at end of line 298 | ERROR | Line exceeds maximum limit of 80 characters; contains 81 | | characters --------------------------------------------------------------------------------
  • 20. Unit testing / TDD  Test critical functionality at a minimum  Add edge cases to regression tests as they are discovered  Test-driven development only works if the entire team is dedicated to it  I personally don’t trust code that isn’t regression-tested; even if it was written by me
  • 21. Continuous Integration  Automated system for code analysis and regression testing  There are a lot of continuous integration systems for PHP  If your tests aren’t automated, very few people will know or care when they break
  • 22. Deployment  Manually copying files is riddled with problems  Tagging releases and re-deploying is a complicated and time-consuming process  Deployment systems automate the build and deployment process
  • 24. If you’re interested in an application security career, come talk with me.