SlideShare ist ein Scribd-Unternehmen logo
1 von 107
Downloaden Sie, um offline zu lesen
Defensive Coding

Crash Course
Mark Niebergall
https://joind.in/talk/d4c29
About Mark Niebergall
• PHP since 2005
• Masters degree in MIS
• Senior Software Engineer
• Drug screening project
• UPHPU President
• CSSLP, SSCP Certified and SME
• Drones, fishing, skiing, father, husband
Defensive Coding

Crash Course
Defensive Coding

Crash Course
• Why defensive coding
• How to code defensively
• Community trends with best practices
Why Defensive Coding
Why Defensive Coding
• Denver Broncos
- 2 recent Super Bowl appearances: 2013 and 2015
- What was the difference?
Why Defensive Coding
• Rogue One - The Empire
- Single point of failure
- No encryption of sensitive data
- Missing authentication
- Bad error handling
Why Defensive Coding
• The Three R’s:
- Reliability
- Resiliency
- Recoverability
Why Defensive Coding
• Reliability
- Predictable behavior
- Likelihood of failure is low
- Achieved by writing resilient code
Why Defensive Coding
• Resiliency
- Ability to recover from problems
- How errors are handled
Why Defensive Coding
• Resiliency
- Avoid assumptions
Why Defensive Coding
• Resiliency
- Use correct data types
- Use type hinting
- Use return types
- Use visibility modifiers
Why Defensive Coding
• Resiliency
- function do_something($thing) {

$thing->do_ThatThing();

}
- public function doSomething(Thing $thing) : bool

{

return $thing->doThatThing();

}
Why Defensive Coding
• Recoverability
- Application can come back from crashes and
failures
Why Defensive Coding
• Recoverability
- Good exception handling
- try { … } catch (SomeException $exception) { … }
- Hope for the best, code for the worst
Why Defensive Coding
• Good code qualities
Why Defensive Coding
• Good code qualities
- Efficient
‣ High performance
‣ foreach ($array as $thing) {

$db = new $Db;

$db->update(‘thing’, $thing);

}
Why Defensive Coding
• Good code qualities
- Efficient
‣ Separation of services
‣ class Pet

{

public function walkDog(Dog $dog) {…}

public function feedFish(Fish $fish) {…}

public function cleanDishes(Dish $dish) {…}

}
Why Defensive Coding
• Good code qualities
- Efficient
‣ Loosely coupled
‣ protected function driveCar()

{

$car = new Car;

$driver = new Person;

…

}
Why Defensive Coding
• Good code qualities
- Secure
‣ Strong cryptography
• password_hash and password_verify
‣ Proven approaches to reduce vulnerabilities
‣ Secure architecture
Why Defensive Coding
• Good code qualities
- Maintain
‣ Good code organization, file structure, domains
‣ Documentation, doc blocks
‣ Adaptability
Why Defensive Coding
• Achieved by practicing effective defensive coding
Why Defensive Coding
How to Code Defensively
How to Code Defensively
• Cover a variety of techniques
How to Code Defensively
• Attack surfaces
• Input validation
• Canonicalization
• Secure type checking
• External library vetting
• Cryptographic agility
• Exception management
• Code reviews
• Unit and behavioral testing
How to Code Defensively
• Attack surfaces
• Input validation
• Canonicalization
• Secure type checking
• External library vetting
• Cryptographic agility
• Exception management
• Code reviews
• Unit and behavioral testing
How to Code Defensively
• Attack surfaces
- Measurement of exposure of being exploited by
threats
- Part of threat modeling
- Ability of software to be attacked
How to Code Defensively
• Attack surfaces
- Each accessible entry and exit point
‣ Everything in public/
‣ Every route
- Every feature is an attack vector
How to Code Defensively
• Attack surfaces
- Attack surface evaluation
‣ Features that may be exploited
‣ Given a weight based on severity of impact
‣ Controls prioritized based on weight
How to Code Defensively
• Attack surfaces
- Relative Attack Surface Quotient (RASQ)
‣ 3 Dimensions
• Targets and Enablers (resources)
• Channels and Protocols (communication)
• Access Rights (privileges)
How to Code Defensively
• Attack surfaces
- High value resources
‣ Data
‣ Functionality
How to Code Defensively
• Attack surfaces
• Input validation
• Canonicalization
• Secure type checking
• External library vetting
• Cryptographic agility
• Exception management
• Code reviews
• Unit and behavioral testing
How to Code Defensively
• Input validation
- Source
- Type
- Format
- Length
- Range
- Values
- Canonical
How to Code Defensively
• Input validation
- Source
‣ Unsafe superglobals includes $_GET, $_POST,
$_SERVER, $_COOKIE, $_FILES, $_REQUEST
‣ Scrutinize trusted sources
‣ Any user input should be treated as unsafe
How to Code Defensively
• Input validation
- Type
‣ is_x functions
‣ Name then all?
How to Code Defensively
• Input validation
- Type
‣ is_string($name)
‣ is_int($age)
‣ is_float($percentage)
‣ is_bool($isAccepted)
‣ is_null($questionableThing)
‣ is_array($keyValueData)
‣ is_object($jsonDecoded)
‣ is_resource($fileHandle)
How to Code Defensively
• Input validation
- Type
‣ if ($thing instanceof SomeThing) {…}
• class
• abstract
• interface
• trait
How to Code Defensively
• Input validation
- Format
‣ Phone number: preg_match(/^d{10}$/, $phone)
‣ Email address (complicated)
‣ Country code: preg_match(/^[A-Z]{2}$/, $code)
‣ Character patterns
How to Code Defensively
• Input validation
- Length
‣ Minimum: strlen($string) >= 5
‣ Maximum: preg_match(/^[a-zA-Z0-9]{1,10}$/,
$number)
‣ Is it required?
How to Code Defensively
• Input validation
- Range
‣ Between 1 and 10: $value >= 1 && $value <= 10
‣ Date range
‣ AA to ZZ
‣ Start and end values
How to Code Defensively
• Input validation
- Values
‣ Whitelist: in_array($checking, [1, 2, 3], true)
‣ Blacklist: !in_array($checking, [‘X’, ‘Y’, ‘Z’])
‣ Regular expressions
‣ Alphanumeric
‣ Free text
‣ Allowed values
How to Code Defensively
• Input validation
- Injection prevention
- Malicious
How to Code Defensively
• Input validation
- Techniques
‣ Filtration
‣ Sanitization
How to Code Defensively
• Input validation
- Techniques
‣ Filtration
• Whitelist and blacklist
• Regular expressions with preg_match
• preg_match(/^d{10}$/, $number)
• preg_match(/^[a-zA-Z0-9]$/, $string)
How to Code Defensively
• Input validation
- Techniques
‣ Filtration
• filter_input(TYPE, $variableName, $filter [,
$options])
• boolean false if filter fails
• NULL if variable is not set
• variable upon success
How to Code Defensively
• Input validation
- Techniques
‣ Filtration
• filter_input(INPUT_POST, ‘key’,
FILTER_VALIDATE_INT)
• filter_input(INPUT_GET, ‘search’,
FILTER_VALIDATE_REGEXP, [‘options’ =>
[‘regexp’ => ‘/^d{10}$/‘]])
How to Code Defensively
• Input validation
- Techniques
‣ Filtration
• filter_var($email, FILTER_VALIDATE_EMAIL)
• filter_var($id, FILTER_VALIDATE_INT)
• filter_var($bool, FILTER_VALIDATE_BOOLEAN)
How to Code Defensively
• Input validation
- Techniques
‣ Sanitization
• Remove unwanted characters or patterns
• str_replace([‘ ‘, ‘-‘, ‘(‘, ‘)’], ‘’, $phone)
• preg_replace([‘/A/‘, ‘/B/‘, ‘/C/‘], [1, 2, 3],
$subject)
• strip_tags($text, ‘<marquee>’)
• Clean up the data
How to Code Defensively
• Input validation
- Techniques
‣ Sanitization
• filter_input(INPUT_POST, ‘user_email’,
FILTER_SANITIZE_EMAIL)
• filter_input(INPUT_COOKIE, ‘some_url’,
FILTER_SANITIZE_URL)
How to Code Defensively
• Input validation
- When to validate data
‣ Frontend (client)
‣ Backend (server)
‣ Filter input, escape output
How to Code Defensively
• Attack surfaces
• Input validation
• Canonicalization
• Secure type checking
• External library vetting
• Cryptographic agility
• Exception management
• Code reviews
• Unit and behavioral testing
How to Code Defensively
• Canonicalization
- Translating input to a standardized value
‣ Encoding
‣ Character set
‣ Aliases
‣ Alternative spellings, formats
How to Code Defensively
• Canonicalization
- Translating input to a standardized value
‣ 2017-08-17
‣ 8/17/17
‣ 17/8/17
‣ Thursday, August 17, 2017
How to Code Defensively
• Canonicalization
- Translating input to a standardized value
‣ Yes
‣ On
‣ 1
‣ true
‣ T
How to Code Defensively
• Canonicalization
- Translating input to a standardized value
‣ Free text vs pre-defined choices
• Proper foreign keys in relational data
• Utilize database integrity checks and
normalization
• Denormalize to an extent for optimizations
How to Code Defensively
• Attack surfaces
• Input validation
• Canonicalization
• Secure type checking
• External library vetting
• Cryptographic agility
• Exception management
• Code reviews
• Unit and behavioral testing
How to Code Defensively
• Secure type checking
- Part of Code Access Security (CAS)
‣ Only trusted sources can run application
‣ Prevent trusted sources from compromising
security
How to Code Defensively
• Secure type checking
- PHP is a type-safe language
- C is not a type-safe language
How to Code Defensively
• Secure type checking
- PHP manages memory use for you
- C is unmanaged
‣ Susceptible to attacks like buffer overflow
How to Code Defensively
• Secure type checking
- Apply PHP security patches
- Vet third-party libraries
How to Code Defensively
• Attack surfaces
• Input validation
• Canonicalization
• Secure type checking
• External library vetting
• Cryptographic agility
• Exception management
• Code reviews
• Unit and behavioral testing
How to Code Defensively
• External library vetting
- Security
- Quality
How to Code Defensively
• External library vetting
- Security
‣ Secure implementation
‣ Security audit
‣ Handling security issues
‣ Use trusted projects
How to Code Defensively
• External library vetting
- Quality
‣ Unit tests
‣ Actively maintained
‣ Popularity
‣ Ease of use
‣ Coding standards
‣ Community acceptance
How to Code Defensively
• Attack surfaces
• Input validation
• Canonicalization
• Secure type checking
• External library vetting
• Cryptographic agility
• Exception management
• Code reviews
• Unit and behavioral testing
How to Code Defensively
• Cryptographic agility
- Ability to stay current
How to Code Defensively
• Cryptographic agility
- Use vetted and trusted algorithms
- Avoid:
‣ Broken algorithms
‣ Weak algorithms
‣ Custom-made algorithms
• Cryptography is complex, please don’t make
your own algorithm
How to Code Defensively
• Cryptographic agility
- PHP password_hash and password_verify
How to Code Defensively
• Cryptographic agility
- PHP 7.2 includes libsodium in core
‣ Modern security library
‣ Vetted
‣ Passed security audit
- PHP 7.1 deprecated mcrypt
‣ Upgrade to libsodium or openssl
How to Code Defensively
• Attack surfaces
• Input validation
• Canonicalization
• Secure type checking
• External library vetting
• Cryptographic agility
• Exception management
• Code reviews
• Unit and behavioral testing
How to Code Defensively
• Exception management
- Handle errors with try/catch blocks
‣ try {...} catch (Exception $e) {…}
How to Code Defensively
• Exception management
- Do not display PHP errors except in development
environment
‣ dev: display_errors = On
‣ others: display_errors = Off
How to Code Defensively
• Exception management
- Log errors and review them actively
‣ dev: error_reporting = E_ALL
‣ prod: E_ALL & ~E_DEPRECATED & ~E_STRICT
‣ E_ALL
‣ E_NOTICE
‣ E_STRICT
‣ E_DEPRECATED
How to Code Defensively
• Attack surfaces
• Input validation
• Canonicalization
• Secure type checking
• External library vetting
• Cryptographic agility
• Exception management
• Code reviews
• Unit and behavioral testing
How to Code Defensively
• Code reviews
- Static
- Dynamic
How to Code Defensively
• Code reviews
- Peers reviewing code changes
‣ Web-based tools
‣ Manual/static code review
- Automatic code review
‣ Commit hooks
‣ Coding standards
‣ Run tests
How to Code Defensively
• Code reviews
- Constructive feedback
How to Code Defensively
• Code reviews
- Architecture direction
How to Code Defensively
• Code reviews
- Coding standards
How to Code Defensively
• Code reviews
- Security issues
‣ Cryptographic agility
‣ Injection flaws
- Business rules
- Related functionality
- Exception handling
How to Code Defensively
• Code reviews
- Automatic code reviews
‣ Coding standard enforcement
‣ Run unit and behavioral tests
‣ Continuous integration tools
How to Code Defensively
• Code reviews
- Automatic code reviews
‣ Statistics
‣ Security
‣ Design patterns
How to Code Defensively
• Attack surfaces
• Input validation
• Canonicalization
• Secure type checking
• External library vetting
• Cryptographic agility
• Exception management
• Code reviews
• Unit and behavioral testing
How to Code Defensively
• Unit and behavioral testing
- Unit tests to ensure logic
‣ PHPUnit
- Behavioral tests to ensure functionality
‣ behat
‣ codeception
How to Code Defensively
• Attack surfaces
• Input validation
• Canonicalization
• Secure type checking
• External library vetting
• Cryptographic agility
• Exception management
• Code reviews
• Unit and behavioral testing
How to Code Defensively
• Tips and Tricks
How to Code Defensively
• Tips and Tricks
- Hope for the best, plan for the worst
How to Code Defensively
• Tips and Tricks
- Abuse cases
‣ Harmful interactions
‣ Help identify threats
- Misuse cases
‣ Inverse of use case
‣ Highlights malicious acts
How to Code Defensively
• Tips and Tricks
- Limit class functionality
- Limit function lines of code
How to Code Defensively
• Tips and Tricks
- Leverage framework functionality
- Leverage built-in PHP functionality
How to Code Defensively
• Tips and Tricks
- Use type hinting
- Use return types
- Use correct data types
‣ Bool true or false instead of string ’T' or ‘false’
‣ Be aware of type casting issues
‣ Use strict type === comparisons when possible
‣ Use is_* checks
How to Code Defensively
• Tips and Tricks
- Use database integrity
‣ Have foreign keys
‣ Use correct data types
‣ Normalize data to good level
• Usually 2nd or 3rd level
• Beyond that usually slows performance
• Denormalize to improve performance but take
up more disk space
How to Code Defensively
• Community movements
How to Code Defensively
• Community movements
- PHP Standards Recommendations (PSR)
‣ Coding standard and style guide
‣ Autoloading
‣ Caching
‣ HTTP Message Interface
How to Code Defensively
• Community movements
- PHP Standards Recommendations
‣ Security issue reporting and handling
‣ Documentation
‣ Extended coding style guide
How to Code Defensively
• Community movements
- Security
‣ New OWASP Top 10
‣ Security at all parts of SDLC
‣ libsodium with PHP 7.2
‣ Sophisticated attacks
‣ MD5 sunset
‣ IoT
How to Code Defensively
• Community movements
- Security
‣ Increasing importance
‣ Good skill to complement development
‣ Core software feature
‣ Investment that can save a project
How to Code Defensively
• Community movements
- Conferences help set trends
- Magazines focus on topics monthly
- Blogs to dispense knowledge
- Social media to share ideas
- Instant messaging to get live help
How to Code Defensively
• Considerations
How to Code Defensively
• Considerations
- How could your project be attacked?
- What are weak points in your projects?
How to Code Defensively
• Considerations
- What will you do differently?
How to Code Defensively
• Considerations
- Make a plan
- Make a change
How to Code Defensively
How to Code Defensively
• Questions?
- Rate on joind.in
‣ https://joind.in/talk/d4c29

Weitere ähnliche Inhalte

Ähnlich wie Defensive Coding Crash Course - ZendCon 2017

ATLRUG Security Workshop - 9/10/2014
ATLRUG  Security Workshop - 9/10/2014 ATLRUG  Security Workshop - 9/10/2014
ATLRUG Security Workshop - 9/10/2014 jasnow
 
Managing Applications in CodeIgniter
Managing Applications in CodeIgniterManaging Applications in CodeIgniter
Managing Applications in CodeIgniterJamshid Hashimi
 
Ten Commandments of Secure Coding
Ten Commandments of Secure CodingTen Commandments of Secure Coding
Ten Commandments of Secure CodingMateusz Olejarka
 
Ten Commandments of Secure Coding - OWASP Top Ten Proactive Controls
Ten Commandments of Secure Coding - OWASP Top Ten Proactive ControlsTen Commandments of Secure Coding - OWASP Top Ten Proactive Controls
Ten Commandments of Secure Coding - OWASP Top Ten Proactive ControlsSecuRing
 
Smart Signatures—Experiments in Authentication (Stanford BPASE 2018 final)
Smart Signatures—Experiments in Authentication (Stanford BPASE 2018 final)Smart Signatures—Experiments in Authentication (Stanford BPASE 2018 final)
Smart Signatures—Experiments in Authentication (Stanford BPASE 2018 final)Christopher Allen
 
Marc Ruef: Adventures in a Decade of Tracking and Consolidating Security Vuln...
Marc Ruef: Adventures in a Decade of Tracking and Consolidating Security Vuln...Marc Ruef: Adventures in a Decade of Tracking and Consolidating Security Vuln...
Marc Ruef: Adventures in a Decade of Tracking and Consolidating Security Vuln...Area41
 
Adventures in a Decade of Tracking and Consolidating Security Vulnerabilities
Adventures in a Decade of Tracking and Consolidating Security VulnerabilitiesAdventures in a Decade of Tracking and Consolidating Security Vulnerabilities
Adventures in a Decade of Tracking and Consolidating Security VulnerabilitiesMarc Ruef
 
Security Code Review 101
Security Code Review 101Security Code Review 101
Security Code Review 101Paul Ionescu
 
RIoT (Raiding Internet of Things) by Jacob Holcomb
RIoT  (Raiding Internet of Things)  by Jacob HolcombRIoT  (Raiding Internet of Things)  by Jacob Holcomb
RIoT (Raiding Internet of Things) by Jacob HolcombPriyanka Aash
 
JavaScript security and tools evolution at 2017 OWASP Taiwan Week
JavaScript security and tools evolution at 2017 OWASP Taiwan WeekJavaScript security and tools evolution at 2017 OWASP Taiwan Week
JavaScript security and tools evolution at 2017 OWASP Taiwan Weekdcervigni
 
Secure Coding 101 - OWASP University of Ottawa Workshop
Secure Coding 101 - OWASP University of Ottawa WorkshopSecure Coding 101 - OWASP University of Ottawa Workshop
Secure Coding 101 - OWASP University of Ottawa WorkshopPaul Ionescu
 
The What, Why, and How of DevSecOps
The What, Why, and How of DevSecOpsThe What, Why, and How of DevSecOps
The What, Why, and How of DevSecOpsCprime
 
Integrating security into the application development process
Integrating security into the application development processIntegrating security into the application development process
Integrating security into the application development processJerod Brennen
 
Swift Micro-services and AWS Technologies
Swift Micro-services and AWS TechnologiesSwift Micro-services and AWS Technologies
Swift Micro-services and AWS TechnologiesSimonPilkington8
 
Building Software That Lasts
Building Software That LastsBuilding Software That Lasts
Building Software That LastsKristine Howard
 
AppSec in an Agile World
AppSec in an Agile WorldAppSec in an Agile World
AppSec in an Agile WorldDavid Lindner
 
Something Died Inside Your Git Repo
Something Died Inside Your Git RepoSomething Died Inside Your Git Repo
Something Died Inside Your Git RepoCliff Smith
 
WTF is Penetration Testing v.2
WTF is Penetration Testing v.2WTF is Penetration Testing v.2
WTF is Penetration Testing v.2Scott Sutherland
 
Software Security Initiative Capabilities: Where Do I Begin?
Software Security Initiative Capabilities: Where Do I Begin? Software Security Initiative Capabilities: Where Do I Begin?
Software Security Initiative Capabilities: Where Do I Begin? Cigital
 

Ähnlich wie Defensive Coding Crash Course - ZendCon 2017 (20)

ATLRUG Security Workshop - 9/10/2014
ATLRUG  Security Workshop - 9/10/2014 ATLRUG  Security Workshop - 9/10/2014
ATLRUG Security Workshop - 9/10/2014
 
Managing Applications in CodeIgniter
Managing Applications in CodeIgniterManaging Applications in CodeIgniter
Managing Applications in CodeIgniter
 
CodeChecker Overview Nov 2019
CodeChecker Overview Nov 2019CodeChecker Overview Nov 2019
CodeChecker Overview Nov 2019
 
Ten Commandments of Secure Coding
Ten Commandments of Secure CodingTen Commandments of Secure Coding
Ten Commandments of Secure Coding
 
Ten Commandments of Secure Coding - OWASP Top Ten Proactive Controls
Ten Commandments of Secure Coding - OWASP Top Ten Proactive ControlsTen Commandments of Secure Coding - OWASP Top Ten Proactive Controls
Ten Commandments of Secure Coding - OWASP Top Ten Proactive Controls
 
Smart Signatures—Experiments in Authentication (Stanford BPASE 2018 final)
Smart Signatures—Experiments in Authentication (Stanford BPASE 2018 final)Smart Signatures—Experiments in Authentication (Stanford BPASE 2018 final)
Smart Signatures—Experiments in Authentication (Stanford BPASE 2018 final)
 
Marc Ruef: Adventures in a Decade of Tracking and Consolidating Security Vuln...
Marc Ruef: Adventures in a Decade of Tracking and Consolidating Security Vuln...Marc Ruef: Adventures in a Decade of Tracking and Consolidating Security Vuln...
Marc Ruef: Adventures in a Decade of Tracking and Consolidating Security Vuln...
 
Adventures in a Decade of Tracking and Consolidating Security Vulnerabilities
Adventures in a Decade of Tracking and Consolidating Security VulnerabilitiesAdventures in a Decade of Tracking and Consolidating Security Vulnerabilities
Adventures in a Decade of Tracking and Consolidating Security Vulnerabilities
 
Security Code Review 101
Security Code Review 101Security Code Review 101
Security Code Review 101
 
RIoT (Raiding Internet of Things) by Jacob Holcomb
RIoT  (Raiding Internet of Things)  by Jacob HolcombRIoT  (Raiding Internet of Things)  by Jacob Holcomb
RIoT (Raiding Internet of Things) by Jacob Holcomb
 
JavaScript security and tools evolution at 2017 OWASP Taiwan Week
JavaScript security and tools evolution at 2017 OWASP Taiwan WeekJavaScript security and tools evolution at 2017 OWASP Taiwan Week
JavaScript security and tools evolution at 2017 OWASP Taiwan Week
 
Secure Coding 101 - OWASP University of Ottawa Workshop
Secure Coding 101 - OWASP University of Ottawa WorkshopSecure Coding 101 - OWASP University of Ottawa Workshop
Secure Coding 101 - OWASP University of Ottawa Workshop
 
The What, Why, and How of DevSecOps
The What, Why, and How of DevSecOpsThe What, Why, and How of DevSecOps
The What, Why, and How of DevSecOps
 
Integrating security into the application development process
Integrating security into the application development processIntegrating security into the application development process
Integrating security into the application development process
 
Swift Micro-services and AWS Technologies
Swift Micro-services and AWS TechnologiesSwift Micro-services and AWS Technologies
Swift Micro-services and AWS Technologies
 
Building Software That Lasts
Building Software That LastsBuilding Software That Lasts
Building Software That Lasts
 
AppSec in an Agile World
AppSec in an Agile WorldAppSec in an Agile World
AppSec in an Agile World
 
Something Died Inside Your Git Repo
Something Died Inside Your Git RepoSomething Died Inside Your Git Repo
Something Died Inside Your Git Repo
 
WTF is Penetration Testing v.2
WTF is Penetration Testing v.2WTF is Penetration Testing v.2
WTF is Penetration Testing v.2
 
Software Security Initiative Capabilities: Where Do I Begin?
Software Security Initiative Capabilities: Where Do I Begin? Software Security Initiative Capabilities: Where Do I Begin?
Software Security Initiative Capabilities: Where Do I Begin?
 

Mehr von Mark Niebergall

Filesystem Management with Flysystem - php[tek] 2023
Filesystem Management with Flysystem - php[tek] 2023Filesystem Management with Flysystem - php[tek] 2023
Filesystem Management with Flysystem - php[tek] 2023Mark Niebergall
 
Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - php[tek] 2023Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - php[tek] 2023Mark Niebergall
 
Filesystem Management with Flysystem at PHP UK 2023
Filesystem Management with Flysystem at PHP UK 2023Filesystem Management with Flysystem at PHP UK 2023
Filesystem Management with Flysystem at PHP UK 2023Mark Niebergall
 
Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022Mark Niebergall
 
Unit Testing from Setup to Deployment
Unit Testing from Setup to DeploymentUnit Testing from Setup to Deployment
Unit Testing from Setup to DeploymentMark Niebergall
 
BDD API Tests with Gherkin and Behat
BDD API Tests with Gherkin and BehatBDD API Tests with Gherkin and Behat
BDD API Tests with Gherkin and BehatMark Niebergall
 
BDD API Tests with Gherkin and Behat
BDD API Tests with Gherkin and BehatBDD API Tests with Gherkin and Behat
BDD API Tests with Gherkin and BehatMark Niebergall
 
Relational Database Design Bootcamp
Relational Database Design BootcampRelational Database Design Bootcamp
Relational Database Design BootcampMark Niebergall
 
Automatic PHP 7 Compatibility Checking Using php7cc (and PHPCompatibility)
Automatic PHP 7 Compatibility Checking Using php7cc (and PHPCompatibility)Automatic PHP 7 Compatibility Checking Using php7cc (and PHPCompatibility)
Automatic PHP 7 Compatibility Checking Using php7cc (and PHPCompatibility)Mark Niebergall
 
Debugging PHP with Xdebug - PHPUK 2018
Debugging PHP with Xdebug - PHPUK 2018Debugging PHP with Xdebug - PHPUK 2018
Debugging PHP with Xdebug - PHPUK 2018Mark Niebergall
 
Advanced PHP Simplified - Sunshine PHP 2018
Advanced PHP Simplified - Sunshine PHP 2018Advanced PHP Simplified - Sunshine PHP 2018
Advanced PHP Simplified - Sunshine PHP 2018Mark Niebergall
 
Inheritance: Vertical or Horizontal
Inheritance: Vertical or HorizontalInheritance: Vertical or Horizontal
Inheritance: Vertical or HorizontalMark Niebergall
 
Cybersecurity State of the Union
Cybersecurity State of the UnionCybersecurity State of the Union
Cybersecurity State of the UnionMark Niebergall
 
Cryptography With PHP - ZendCon 2017 Workshop
Cryptography With PHP - ZendCon 2017 WorkshopCryptography With PHP - ZendCon 2017 Workshop
Cryptography With PHP - ZendCon 2017 WorkshopMark Niebergall
 
Leveraging Composer in Existing Projects
Leveraging Composer in Existing ProjectsLeveraging Composer in Existing Projects
Leveraging Composer in Existing ProjectsMark Niebergall
 
Impostor Syndrome: Be Proud of Your Achievements!
Impostor Syndrome: Be Proud of Your Achievements!Impostor Syndrome: Be Proud of Your Achievements!
Impostor Syndrome: Be Proud of Your Achievements!Mark Niebergall
 
Cryptography with PHP (Workshop)
Cryptography with PHP (Workshop)Cryptography with PHP (Workshop)
Cryptography with PHP (Workshop)Mark Niebergall
 

Mehr von Mark Niebergall (20)

Filesystem Management with Flysystem - php[tek] 2023
Filesystem Management with Flysystem - php[tek] 2023Filesystem Management with Flysystem - php[tek] 2023
Filesystem Management with Flysystem - php[tek] 2023
 
Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - php[tek] 2023Leveling Up With Unit Testing - php[tek] 2023
Leveling Up With Unit Testing - php[tek] 2023
 
Filesystem Management with Flysystem at PHP UK 2023
Filesystem Management with Flysystem at PHP UK 2023Filesystem Management with Flysystem at PHP UK 2023
Filesystem Management with Flysystem at PHP UK 2023
 
Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022Leveling Up With Unit Testing - LonghornPHP 2022
Leveling Up With Unit Testing - LonghornPHP 2022
 
Developing SOLID Code
Developing SOLID CodeDeveloping SOLID Code
Developing SOLID Code
 
Unit Testing from Setup to Deployment
Unit Testing from Setup to DeploymentUnit Testing from Setup to Deployment
Unit Testing from Setup to Deployment
 
Stacking Up Middleware
Stacking Up MiddlewareStacking Up Middleware
Stacking Up Middleware
 
BDD API Tests with Gherkin and Behat
BDD API Tests with Gherkin and BehatBDD API Tests with Gherkin and Behat
BDD API Tests with Gherkin and Behat
 
BDD API Tests with Gherkin and Behat
BDD API Tests with Gherkin and BehatBDD API Tests with Gherkin and Behat
BDD API Tests with Gherkin and Behat
 
Hacking with PHP
Hacking with PHPHacking with PHP
Hacking with PHP
 
Relational Database Design Bootcamp
Relational Database Design BootcampRelational Database Design Bootcamp
Relational Database Design Bootcamp
 
Automatic PHP 7 Compatibility Checking Using php7cc (and PHPCompatibility)
Automatic PHP 7 Compatibility Checking Using php7cc (and PHPCompatibility)Automatic PHP 7 Compatibility Checking Using php7cc (and PHPCompatibility)
Automatic PHP 7 Compatibility Checking Using php7cc (and PHPCompatibility)
 
Debugging PHP with Xdebug - PHPUK 2018
Debugging PHP with Xdebug - PHPUK 2018Debugging PHP with Xdebug - PHPUK 2018
Debugging PHP with Xdebug - PHPUK 2018
 
Advanced PHP Simplified - Sunshine PHP 2018
Advanced PHP Simplified - Sunshine PHP 2018Advanced PHP Simplified - Sunshine PHP 2018
Advanced PHP Simplified - Sunshine PHP 2018
 
Inheritance: Vertical or Horizontal
Inheritance: Vertical or HorizontalInheritance: Vertical or Horizontal
Inheritance: Vertical or Horizontal
 
Cybersecurity State of the Union
Cybersecurity State of the UnionCybersecurity State of the Union
Cybersecurity State of the Union
 
Cryptography With PHP - ZendCon 2017 Workshop
Cryptography With PHP - ZendCon 2017 WorkshopCryptography With PHP - ZendCon 2017 Workshop
Cryptography With PHP - ZendCon 2017 Workshop
 
Leveraging Composer in Existing Projects
Leveraging Composer in Existing ProjectsLeveraging Composer in Existing Projects
Leveraging Composer in Existing Projects
 
Impostor Syndrome: Be Proud of Your Achievements!
Impostor Syndrome: Be Proud of Your Achievements!Impostor Syndrome: Be Proud of Your Achievements!
Impostor Syndrome: Be Proud of Your Achievements!
 
Cryptography with PHP (Workshop)
Cryptography with PHP (Workshop)Cryptography with PHP (Workshop)
Cryptography with PHP (Workshop)
 

Kürzlich hochgeladen

why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
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 Modelsaagamshah0812
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 

Kürzlich hochgeladen (20)

why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
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
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 

Defensive Coding Crash Course - ZendCon 2017

  • 1. Defensive Coding
 Crash Course Mark Niebergall https://joind.in/talk/d4c29
  • 2. About Mark Niebergall • PHP since 2005 • Masters degree in MIS • Senior Software Engineer • Drug screening project • UPHPU President • CSSLP, SSCP Certified and SME • Drones, fishing, skiing, father, husband
  • 3.
  • 4.
  • 6. Defensive Coding
 Crash Course • Why defensive coding • How to code defensively • Community trends with best practices
  • 8. Why Defensive Coding • Denver Broncos - 2 recent Super Bowl appearances: 2013 and 2015 - What was the difference?
  • 9. Why Defensive Coding • Rogue One - The Empire - Single point of failure - No encryption of sensitive data - Missing authentication - Bad error handling
  • 10. Why Defensive Coding • The Three R’s: - Reliability - Resiliency - Recoverability
  • 11. Why Defensive Coding • Reliability - Predictable behavior - Likelihood of failure is low - Achieved by writing resilient code
  • 12. Why Defensive Coding • Resiliency - Ability to recover from problems - How errors are handled
  • 13. Why Defensive Coding • Resiliency - Avoid assumptions
  • 14. Why Defensive Coding • Resiliency - Use correct data types - Use type hinting - Use return types - Use visibility modifiers
  • 15. Why Defensive Coding • Resiliency - function do_something($thing) {
 $thing->do_ThatThing();
 } - public function doSomething(Thing $thing) : bool
 {
 return $thing->doThatThing();
 }
  • 16. Why Defensive Coding • Recoverability - Application can come back from crashes and failures
  • 17. Why Defensive Coding • Recoverability - Good exception handling - try { … } catch (SomeException $exception) { … } - Hope for the best, code for the worst
  • 18. Why Defensive Coding • Good code qualities
  • 19. Why Defensive Coding • Good code qualities - Efficient ‣ High performance ‣ foreach ($array as $thing) {
 $db = new $Db;
 $db->update(‘thing’, $thing);
 }
  • 20. Why Defensive Coding • Good code qualities - Efficient ‣ Separation of services ‣ class Pet
 {
 public function walkDog(Dog $dog) {…}
 public function feedFish(Fish $fish) {…}
 public function cleanDishes(Dish $dish) {…}
 }
  • 21. Why Defensive Coding • Good code qualities - Efficient ‣ Loosely coupled ‣ protected function driveCar()
 {
 $car = new Car;
 $driver = new Person;
 …
 }
  • 22. Why Defensive Coding • Good code qualities - Secure ‣ Strong cryptography • password_hash and password_verify ‣ Proven approaches to reduce vulnerabilities ‣ Secure architecture
  • 23. Why Defensive Coding • Good code qualities - Maintain ‣ Good code organization, file structure, domains ‣ Documentation, doc blocks ‣ Adaptability
  • 24. Why Defensive Coding • Achieved by practicing effective defensive coding
  • 26. How to Code Defensively
  • 27. How to Code Defensively • Cover a variety of techniques
  • 28. How to Code Defensively • Attack surfaces • Input validation • Canonicalization • Secure type checking • External library vetting • Cryptographic agility • Exception management • Code reviews • Unit and behavioral testing
  • 29. How to Code Defensively • Attack surfaces • Input validation • Canonicalization • Secure type checking • External library vetting • Cryptographic agility • Exception management • Code reviews • Unit and behavioral testing
  • 30. How to Code Defensively • Attack surfaces - Measurement of exposure of being exploited by threats - Part of threat modeling - Ability of software to be attacked
  • 31. How to Code Defensively • Attack surfaces - Each accessible entry and exit point ‣ Everything in public/ ‣ Every route - Every feature is an attack vector
  • 32. How to Code Defensively • Attack surfaces - Attack surface evaluation ‣ Features that may be exploited ‣ Given a weight based on severity of impact ‣ Controls prioritized based on weight
  • 33. How to Code Defensively • Attack surfaces - Relative Attack Surface Quotient (RASQ) ‣ 3 Dimensions • Targets and Enablers (resources) • Channels and Protocols (communication) • Access Rights (privileges)
  • 34. How to Code Defensively • Attack surfaces - High value resources ‣ Data ‣ Functionality
  • 35. How to Code Defensively • Attack surfaces • Input validation • Canonicalization • Secure type checking • External library vetting • Cryptographic agility • Exception management • Code reviews • Unit and behavioral testing
  • 36. How to Code Defensively • Input validation - Source - Type - Format - Length - Range - Values - Canonical
  • 37. How to Code Defensively • Input validation - Source ‣ Unsafe superglobals includes $_GET, $_POST, $_SERVER, $_COOKIE, $_FILES, $_REQUEST ‣ Scrutinize trusted sources ‣ Any user input should be treated as unsafe
  • 38. How to Code Defensively • Input validation - Type ‣ is_x functions ‣ Name then all?
  • 39. How to Code Defensively • Input validation - Type ‣ is_string($name) ‣ is_int($age) ‣ is_float($percentage) ‣ is_bool($isAccepted) ‣ is_null($questionableThing) ‣ is_array($keyValueData) ‣ is_object($jsonDecoded) ‣ is_resource($fileHandle)
  • 40. How to Code Defensively • Input validation - Type ‣ if ($thing instanceof SomeThing) {…} • class • abstract • interface • trait
  • 41. How to Code Defensively • Input validation - Format ‣ Phone number: preg_match(/^d{10}$/, $phone) ‣ Email address (complicated) ‣ Country code: preg_match(/^[A-Z]{2}$/, $code) ‣ Character patterns
  • 42. How to Code Defensively • Input validation - Length ‣ Minimum: strlen($string) >= 5 ‣ Maximum: preg_match(/^[a-zA-Z0-9]{1,10}$/, $number) ‣ Is it required?
  • 43. How to Code Defensively • Input validation - Range ‣ Between 1 and 10: $value >= 1 && $value <= 10 ‣ Date range ‣ AA to ZZ ‣ Start and end values
  • 44. How to Code Defensively • Input validation - Values ‣ Whitelist: in_array($checking, [1, 2, 3], true) ‣ Blacklist: !in_array($checking, [‘X’, ‘Y’, ‘Z’]) ‣ Regular expressions ‣ Alphanumeric ‣ Free text ‣ Allowed values
  • 45. How to Code Defensively • Input validation - Injection prevention - Malicious
  • 46. How to Code Defensively • Input validation - Techniques ‣ Filtration ‣ Sanitization
  • 47. How to Code Defensively • Input validation - Techniques ‣ Filtration • Whitelist and blacklist • Regular expressions with preg_match • preg_match(/^d{10}$/, $number) • preg_match(/^[a-zA-Z0-9]$/, $string)
  • 48. How to Code Defensively • Input validation - Techniques ‣ Filtration • filter_input(TYPE, $variableName, $filter [, $options]) • boolean false if filter fails • NULL if variable is not set • variable upon success
  • 49. How to Code Defensively • Input validation - Techniques ‣ Filtration • filter_input(INPUT_POST, ‘key’, FILTER_VALIDATE_INT) • filter_input(INPUT_GET, ‘search’, FILTER_VALIDATE_REGEXP, [‘options’ => [‘regexp’ => ‘/^d{10}$/‘]])
  • 50. How to Code Defensively • Input validation - Techniques ‣ Filtration • filter_var($email, FILTER_VALIDATE_EMAIL) • filter_var($id, FILTER_VALIDATE_INT) • filter_var($bool, FILTER_VALIDATE_BOOLEAN)
  • 51. How to Code Defensively • Input validation - Techniques ‣ Sanitization • Remove unwanted characters or patterns • str_replace([‘ ‘, ‘-‘, ‘(‘, ‘)’], ‘’, $phone) • preg_replace([‘/A/‘, ‘/B/‘, ‘/C/‘], [1, 2, 3], $subject) • strip_tags($text, ‘<marquee>’) • Clean up the data
  • 52. How to Code Defensively • Input validation - Techniques ‣ Sanitization • filter_input(INPUT_POST, ‘user_email’, FILTER_SANITIZE_EMAIL) • filter_input(INPUT_COOKIE, ‘some_url’, FILTER_SANITIZE_URL)
  • 53. How to Code Defensively • Input validation - When to validate data ‣ Frontend (client) ‣ Backend (server) ‣ Filter input, escape output
  • 54. How to Code Defensively • Attack surfaces • Input validation • Canonicalization • Secure type checking • External library vetting • Cryptographic agility • Exception management • Code reviews • Unit and behavioral testing
  • 55. How to Code Defensively • Canonicalization - Translating input to a standardized value ‣ Encoding ‣ Character set ‣ Aliases ‣ Alternative spellings, formats
  • 56. How to Code Defensively • Canonicalization - Translating input to a standardized value ‣ 2017-08-17 ‣ 8/17/17 ‣ 17/8/17 ‣ Thursday, August 17, 2017
  • 57. How to Code Defensively • Canonicalization - Translating input to a standardized value ‣ Yes ‣ On ‣ 1 ‣ true ‣ T
  • 58. How to Code Defensively • Canonicalization - Translating input to a standardized value ‣ Free text vs pre-defined choices • Proper foreign keys in relational data • Utilize database integrity checks and normalization • Denormalize to an extent for optimizations
  • 59. How to Code Defensively • Attack surfaces • Input validation • Canonicalization • Secure type checking • External library vetting • Cryptographic agility • Exception management • Code reviews • Unit and behavioral testing
  • 60. How to Code Defensively • Secure type checking - Part of Code Access Security (CAS) ‣ Only trusted sources can run application ‣ Prevent trusted sources from compromising security
  • 61. How to Code Defensively • Secure type checking - PHP is a type-safe language - C is not a type-safe language
  • 62. How to Code Defensively • Secure type checking - PHP manages memory use for you - C is unmanaged ‣ Susceptible to attacks like buffer overflow
  • 63. How to Code Defensively • Secure type checking - Apply PHP security patches - Vet third-party libraries
  • 64. How to Code Defensively • Attack surfaces • Input validation • Canonicalization • Secure type checking • External library vetting • Cryptographic agility • Exception management • Code reviews • Unit and behavioral testing
  • 65. How to Code Defensively • External library vetting - Security - Quality
  • 66. How to Code Defensively • External library vetting - Security ‣ Secure implementation ‣ Security audit ‣ Handling security issues ‣ Use trusted projects
  • 67. How to Code Defensively • External library vetting - Quality ‣ Unit tests ‣ Actively maintained ‣ Popularity ‣ Ease of use ‣ Coding standards ‣ Community acceptance
  • 68. How to Code Defensively • Attack surfaces • Input validation • Canonicalization • Secure type checking • External library vetting • Cryptographic agility • Exception management • Code reviews • Unit and behavioral testing
  • 69. How to Code Defensively • Cryptographic agility - Ability to stay current
  • 70. How to Code Defensively • Cryptographic agility - Use vetted and trusted algorithms - Avoid: ‣ Broken algorithms ‣ Weak algorithms ‣ Custom-made algorithms • Cryptography is complex, please don’t make your own algorithm
  • 71. How to Code Defensively • Cryptographic agility - PHP password_hash and password_verify
  • 72. How to Code Defensively • Cryptographic agility - PHP 7.2 includes libsodium in core ‣ Modern security library ‣ Vetted ‣ Passed security audit - PHP 7.1 deprecated mcrypt ‣ Upgrade to libsodium or openssl
  • 73. How to Code Defensively • Attack surfaces • Input validation • Canonicalization • Secure type checking • External library vetting • Cryptographic agility • Exception management • Code reviews • Unit and behavioral testing
  • 74. How to Code Defensively • Exception management - Handle errors with try/catch blocks ‣ try {...} catch (Exception $e) {…}
  • 75. How to Code Defensively • Exception management - Do not display PHP errors except in development environment ‣ dev: display_errors = On ‣ others: display_errors = Off
  • 76. How to Code Defensively • Exception management - Log errors and review them actively ‣ dev: error_reporting = E_ALL ‣ prod: E_ALL & ~E_DEPRECATED & ~E_STRICT ‣ E_ALL ‣ E_NOTICE ‣ E_STRICT ‣ E_DEPRECATED
  • 77. How to Code Defensively • Attack surfaces • Input validation • Canonicalization • Secure type checking • External library vetting • Cryptographic agility • Exception management • Code reviews • Unit and behavioral testing
  • 78. How to Code Defensively • Code reviews - Static - Dynamic
  • 79. How to Code Defensively • Code reviews - Peers reviewing code changes ‣ Web-based tools ‣ Manual/static code review - Automatic code review ‣ Commit hooks ‣ Coding standards ‣ Run tests
  • 80. How to Code Defensively • Code reviews - Constructive feedback
  • 81. How to Code Defensively • Code reviews - Architecture direction
  • 82. How to Code Defensively • Code reviews - Coding standards
  • 83. How to Code Defensively • Code reviews - Security issues ‣ Cryptographic agility ‣ Injection flaws - Business rules - Related functionality - Exception handling
  • 84. How to Code Defensively • Code reviews - Automatic code reviews ‣ Coding standard enforcement ‣ Run unit and behavioral tests ‣ Continuous integration tools
  • 85. How to Code Defensively • Code reviews - Automatic code reviews ‣ Statistics ‣ Security ‣ Design patterns
  • 86. How to Code Defensively • Attack surfaces • Input validation • Canonicalization • Secure type checking • External library vetting • Cryptographic agility • Exception management • Code reviews • Unit and behavioral testing
  • 87. How to Code Defensively • Unit and behavioral testing - Unit tests to ensure logic ‣ PHPUnit - Behavioral tests to ensure functionality ‣ behat ‣ codeception
  • 88. How to Code Defensively • Attack surfaces • Input validation • Canonicalization • Secure type checking • External library vetting • Cryptographic agility • Exception management • Code reviews • Unit and behavioral testing
  • 89. How to Code Defensively • Tips and Tricks
  • 90. How to Code Defensively • Tips and Tricks - Hope for the best, plan for the worst
  • 91. How to Code Defensively • Tips and Tricks - Abuse cases ‣ Harmful interactions ‣ Help identify threats - Misuse cases ‣ Inverse of use case ‣ Highlights malicious acts
  • 92. How to Code Defensively • Tips and Tricks - Limit class functionality - Limit function lines of code
  • 93. How to Code Defensively • Tips and Tricks - Leverage framework functionality - Leverage built-in PHP functionality
  • 94. How to Code Defensively • Tips and Tricks - Use type hinting - Use return types - Use correct data types ‣ Bool true or false instead of string ’T' or ‘false’ ‣ Be aware of type casting issues ‣ Use strict type === comparisons when possible ‣ Use is_* checks
  • 95. How to Code Defensively • Tips and Tricks - Use database integrity ‣ Have foreign keys ‣ Use correct data types ‣ Normalize data to good level • Usually 2nd or 3rd level • Beyond that usually slows performance • Denormalize to improve performance but take up more disk space
  • 96. How to Code Defensively • Community movements
  • 97. How to Code Defensively • Community movements - PHP Standards Recommendations (PSR) ‣ Coding standard and style guide ‣ Autoloading ‣ Caching ‣ HTTP Message Interface
  • 98. How to Code Defensively • Community movements - PHP Standards Recommendations ‣ Security issue reporting and handling ‣ Documentation ‣ Extended coding style guide
  • 99. How to Code Defensively • Community movements - Security ‣ New OWASP Top 10 ‣ Security at all parts of SDLC ‣ libsodium with PHP 7.2 ‣ Sophisticated attacks ‣ MD5 sunset ‣ IoT
  • 100. How to Code Defensively • Community movements - Security ‣ Increasing importance ‣ Good skill to complement development ‣ Core software feature ‣ Investment that can save a project
  • 101. How to Code Defensively • Community movements - Conferences help set trends - Magazines focus on topics monthly - Blogs to dispense knowledge - Social media to share ideas - Instant messaging to get live help
  • 102. How to Code Defensively • Considerations
  • 103. How to Code Defensively • Considerations - How could your project be attacked? - What are weak points in your projects?
  • 104. How to Code Defensively • Considerations - What will you do differently?
  • 105. How to Code Defensively • Considerations - Make a plan - Make a change
  • 106. How to Code Defensively
  • 107. How to Code Defensively • Questions? - Rate on joind.in ‣ https://joind.in/talk/d4c29