SlideShare a Scribd company logo
Defensive Coding

Crash Course
Mark Niebergall
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
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
‣ Separation of services
‣ Loosely coupled
Why Defensive Coding
• Good code qualities
- Secure
‣ Strong cryptography
‣ Proven approaches to reduce vulnerabilities
‣ Secure architecture
Why Defensive Coding
• Good code qualities
- Maintain
‣ Good code organization
‣ Documentation
‣ 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
- 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_int
‣ is_float
‣ is_bool
‣ is_null
‣ is_array
‣ is_object
‣ is_resource
How to Code Defensively
• Input validation
- Type
‣ $thing instanceof SomeThing
‣ class
‣ abstract
‣ interface
‣ trait
How to Code Defensively
• Input validation
- Format
‣ Phone number
‣ Email address (complicated)
‣ Country code
‣ Character patterns
How to Code Defensively
• Input validation
- Length
‣ Minimum
‣ Maximum
‣ Is it required?
How to Code Defensively
• Input validation
- Range
‣ Between 1 and 10
‣ Date range
‣ AA to ZZ
‣ Start and end values
How to Code Defensively
• Input validation
- Values
‣ Whitelist
‣ Blacklist
‣ 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
‣ Sanitization
• Remove unwanted characters or patterns
• Clean up the data
How to Code Defensively
• Input validation
- Techniques
‣ Sanitization
• filter_input(INPUT_POST, ‘something’,
FILTER_SANITIZE_EMAIL)
• filter_input(INPUT_COOKIE, ‘somewhere’,
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
• Utilize database integrity checks and
normalization
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
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
- More on this later
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
‣ 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?

More Related Content

PDF
Building Software That Lasts
PDF
SunshinePHP 2017: Tales From The Crypt - A Cryptography Primer
PDF
Scala Bay Meetup - The state of Scala code style and quality
PDF
Defensive Coding Crash Course - ZendCon 2017
PDF
Defensive Coding Crash Course Tutorial
PPT
Writing Secure Code – Threat Defense
PPTX
App sec - code insecurity basics
PDF
Secure coding-guidelines
Building Software That Lasts
SunshinePHP 2017: Tales From The Crypt - A Cryptography Primer
Scala Bay Meetup - The state of Scala code style and quality
Defensive Coding Crash Course - ZendCon 2017
Defensive Coding Crash Course Tutorial
Writing Secure Code – Threat Defense
App sec - code insecurity basics
Secure coding-guidelines

Similar to Defensive Coding Crash Course (20)

PPT
10290057.ppt
PPTX
Ebu class edgescan-2017
PPTX
Code - Fu: Defensive Programming
PPT
Php security
PPTX
Code - Fu: Defensive Programming
PDF
OWASP Secure Coding Quick Reference Guide
PPT
Intro to-ssdl--lone-star-php-2013
PPTX
chap-1 : Vulnerabilities in Information Systems
PDF
[EMC] Source Code Protection
PPTX
Web security-–-everything-we-know-is-wrong-eoin-keary
PPTX
Real-World WebAppSec Flaws - Examples and Countermeasues
PDF
Secure Coding - Web Application Security Vulnerabilities and Best Practices
PPTX
501 ch 7 advanced attacks
PDF
Designing software with security in mind?
PDF
Secure PHP Coding
PDF
"CERT Secure Coding Standards" by Dr. Mark Sherman
DOCX
Defensive coding practices is one of the most critical proactive s
PDF
Coding Security: Code Mania 101
PPTX
20101017 program analysis_for_security_livshits_lecture03_security
PPT
4.Security Assessment And Testing
10290057.ppt
Ebu class edgescan-2017
Code - Fu: Defensive Programming
Php security
Code - Fu: Defensive Programming
OWASP Secure Coding Quick Reference Guide
Intro to-ssdl--lone-star-php-2013
chap-1 : Vulnerabilities in Information Systems
[EMC] Source Code Protection
Web security-–-everything-we-know-is-wrong-eoin-keary
Real-World WebAppSec Flaws - Examples and Countermeasues
Secure Coding - Web Application Security Vulnerabilities and Best Practices
501 ch 7 advanced attacks
Designing software with security in mind?
Secure PHP Coding
"CERT Secure Coding Standards" by Dr. Mark Sherman
Defensive coding practices is one of the most critical proactive s
Coding Security: Code Mania 101
20101017 program analysis_for_security_livshits_lecture03_security
4.Security Assessment And Testing
Ad

More from Mark Niebergall (20)

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

Recently uploaded (20)

PPTX
L1 - Introduction to python Backend.pptx
PDF
Digital Systems & Binary Numbers (comprehensive )
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
Digital Strategies for Manufacturing Companies
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PPTX
history of c programming in notes for students .pptx
PDF
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
PDF
top salesforce developer skills in 2025.pdf
PPTX
Computer Software and OS of computer science of grade 11.pptx
PDF
System and Network Administration Chapter 2
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
System and Network Administraation Chapter 3
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
L1 - Introduction to python Backend.pptx
Digital Systems & Binary Numbers (comprehensive )
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Odoo Companies in India – Driving Business Transformation.pdf
wealthsignaloriginal-com-DS-text-... (1).pdf
Wondershare Filmora 15 Crack With Activation Key [2025
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Which alternative to Crystal Reports is best for small or large businesses.pdf
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Digital Strategies for Manufacturing Companies
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
history of c programming in notes for students .pptx
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
top salesforce developer skills in 2025.pdf
Computer Software and OS of computer science of grade 11.pptx
System and Network Administration Chapter 2
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Odoo POS Development Services by CandidRoot Solutions
System and Network Administraation Chapter 3
Internet Downloader Manager (IDM) Crack 6.42 Build 41

Defensive Coding Crash Course

  • 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
  • 5. Defensive Coding
 Crash Course • Why defensive coding • How to code defensively • Community trends with best practices
  • 7. Why Defensive Coding • Denver Broncos - 2 recent Super Bowl appearances: 2013 and 2015 - What was the difference?
  • 8. Why Defensive Coding • Rogue One - The Empire - Single point of failure - No encryption of sensitive data - Missing authentication - Bad error handling
  • 9. Why Defensive Coding • The Three R’s: - Reliability - Resiliency - Recoverability
  • 10. Why Defensive Coding • Reliability - Predictable behavior - Likelihood of failure is low - Achieved by writing resilient code
  • 11. Why Defensive Coding • Resiliency - Ability to recover from problems - How errors are handled
  • 12. Why Defensive Coding • Resiliency - Avoid assumptions
  • 13. Why Defensive Coding • Resiliency - Use correct data types - Use type hinting - Use return types - Use visibility modifiers
  • 14. Why Defensive Coding • Resiliency - function do_something($thing) {
 $thing->do_ThatThing();
 } - public function doSomething(Thing $thing) : bool
 {
 return $thing->doThatThing();
 }
  • 15. Why Defensive Coding • Recoverability - Application can come back from crashes and failures
  • 16. Why Defensive Coding • Recoverability - Good exception handling - try { … } catch (SomeException $exception) { … } - Hope for the best, code for the worst
  • 17. Why Defensive Coding • Good code qualities
  • 18. Why Defensive Coding • Good code qualities - Efficient ‣ High performance ‣ Separation of services ‣ Loosely coupled
  • 19. Why Defensive Coding • Good code qualities - Secure ‣ Strong cryptography ‣ Proven approaches to reduce vulnerabilities ‣ Secure architecture
  • 20. Why Defensive Coding • Good code qualities - Maintain ‣ Good code organization ‣ Documentation ‣ Adaptability
  • 21. Why Defensive Coding • Achieved by practicing effective defensive coding
  • 23. How to Code Defensively
  • 24. How to Code Defensively • Cover a variety of techniques
  • 25. 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
  • 26. 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
  • 27. How to Code Defensively • Attack surfaces - Measurement of exposure of being exploited by threats - Part of threat modeling - Ability of software to be attacked
  • 28. How to Code Defensively • Attack surfaces - Each accessible entry and exit point - Every feature is an attack vector
  • 29. 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
  • 30. How to Code Defensively • Attack surfaces - Relative Attack Surface Quotient (RASQ) ‣ 3 Dimensions • Targets and Enablers (resources) • Channels and Protocols (communication) • Access Rights (privileges)
  • 31. How to Code Defensively • Attack surfaces - High value resources ‣ Data ‣ Functionality
  • 32. 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
  • 33. How to Code Defensively • Input validation - Source - Type - Format - Length - Range - Values - Canonical
  • 34. 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
  • 35. How to Code Defensively • Input validation - Type ‣ is_int ‣ is_float ‣ is_bool ‣ is_null ‣ is_array ‣ is_object ‣ is_resource
  • 36. How to Code Defensively • Input validation - Type ‣ $thing instanceof SomeThing ‣ class ‣ abstract ‣ interface ‣ trait
  • 37. How to Code Defensively • Input validation - Format ‣ Phone number ‣ Email address (complicated) ‣ Country code ‣ Character patterns
  • 38. How to Code Defensively • Input validation - Length ‣ Minimum ‣ Maximum ‣ Is it required?
  • 39. How to Code Defensively • Input validation - Range ‣ Between 1 and 10 ‣ Date range ‣ AA to ZZ ‣ Start and end values
  • 40. How to Code Defensively • Input validation - Values ‣ Whitelist ‣ Blacklist ‣ Regular expressions ‣ Alphanumeric ‣ Free text ‣ Allowed values
  • 41. How to Code Defensively • Input validation - Injection prevention - Malicious
  • 42. How to Code Defensively • Input validation - Techniques ‣ Filtration ‣ Sanitization
  • 43. 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)
  • 44. 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
  • 45. 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}$/‘]])
  • 46. How to Code Defensively • Input validation - Techniques ‣ Sanitization • Remove unwanted characters or patterns • Clean up the data
  • 47. How to Code Defensively • Input validation - Techniques ‣ Sanitization • filter_input(INPUT_POST, ‘something’, FILTER_SANITIZE_EMAIL) • filter_input(INPUT_COOKIE, ‘somewhere’, FILTER_SANITIZE_URL)
  • 48. How to Code Defensively • Input validation - When to validate data ‣ Frontend (client) ‣ Backend (server) ‣ Filter input, escape output
  • 49. 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
  • 50. How to Code Defensively • Canonicalization - Translating input to a standardized value ‣ Encoding ‣ Character set ‣ Aliases ‣ Alternative spellings, formats
  • 51. How to Code Defensively • Canonicalization - Translating input to a standardized value ‣ 2017-08-17 ‣ 8/17/17 ‣ 17/8/17 ‣ Thursday, August 17, 2017
  • 52. How to Code Defensively • Canonicalization - Translating input to a standardized value ‣ Yes ‣ On ‣ 1 ‣ true ‣ T
  • 53. How to Code Defensively • Canonicalization - Translating input to a standardized value ‣ Free text vs pre-defined choices • Proper foreign keys • Utilize database integrity checks and normalization
  • 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 • Secure type checking - Part of Code Access Security (CAS) ‣ Only trusted sources can run application ‣ Prevent trusted sources from compromising security
  • 56. How to Code Defensively • Secure type checking - PHP is a type-safe language - C is not a type-safe language
  • 57. How to Code Defensively • Secure type checking - PHP manages memory use for you - C is unmanaged ‣ Susceptible to attacks like buffer overflow
  • 58. How to Code Defensively • Secure type checking - Apply PHP security patches - Vet third-party libraries
  • 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 • External library vetting - Security - Quality
  • 61. How to Code Defensively • External library vetting - Security ‣ Secure implementation ‣ Security audit ‣ Handling security issues ‣ Use trusted projects
  • 62. How to Code Defensively • External library vetting - Quality ‣ Unit tests ‣ Actively maintained ‣ Popularity ‣ Ease of use ‣ Coding standards
  • 63. 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
  • 64. How to Code Defensively • Cryptographic agility - Ability to stay current
  • 65. 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
  • 66. How to Code Defensively • Cryptographic agility - PHP password_hash and password_verify
  • 67. 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
  • 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 • Exception management - Handle errors with try/catch blocks ‣ try {...} catch (Exception $e) {…}
  • 70. How to Code Defensively • Exception management - Do not display PHP errors except in development environment ‣ dev: display_errors = On ‣ others: display_errors = Off
  • 71. 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
  • 72. 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
  • 73. How to Code Defensively • Code reviews - Static - Dynamic
  • 74. 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
  • 75. How to Code Defensively • Code reviews - Constructive feedback
  • 76. How to Code Defensively • Code reviews - Architecture direction
  • 77. How to Code Defensively • Code reviews - Coding standards
  • 78. How to Code Defensively • Code reviews - Security issues ‣ Cryptographic agility ‣ Injection flaws - Business rules - Related functionality - Exception handling
  • 79. How to Code Defensively • Code reviews - Automatic code reviews ‣ Coding standard enforcement ‣ Run unit and behavioral tests ‣ Continuous integration tools
  • 80. How to Code Defensively • Code reviews - Automatic code reviews ‣ Statistics ‣ Security ‣ Design patterns
  • 81. 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
  • 82. How to Code Defensively • Unit and behavioral testing - More on this later
  • 83. 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
  • 84. How to Code Defensively • Tips and Tricks
  • 85. How to Code Defensively • Tips and Tricks - Hope for the best, plan for the worst
  • 86. How to Code Defensively • Tips and Tricks - Abuse cases ‣ Harmful interactions ‣ Help identify threats - Misuse cases ‣ Inverse of use case ‣ Highlights malicious acts
  • 87. How to Code Defensively • Tips and Tricks - Limit class functionality - Limit function lines of code
  • 88. How to Code Defensively • Tips and Tricks - Leverage framework functionality - Leverage built-in PHP functionality
  • 89. 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
  • 90. 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
  • 91. How to Code Defensively • Community movements
  • 92. How to Code Defensively • Community movements - PHP Standards Recommendations ‣ Coding standard and style guide ‣ Autoloading ‣ Caching ‣ HTTP Message Interface
  • 93. How to Code Defensively • Community movements - PHP Standards Recommendations ‣ Security issue reporting and handling ‣ Documentation ‣ Extended coding style guide
  • 94. 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
  • 95. How to Code Defensively • Community movements - Security ‣ Increasing importance ‣ Good skill to complement development ‣ Core software feature ‣ Investment that can save a project
  • 96. 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
  • 97. How to Code Defensively • Considerations
  • 98. How to Code Defensively • Considerations - How could your project be attacked? - What are weak points in your projects?
  • 99. How to Code Defensively • Considerations - What will you do differently?
  • 100. How to Code Defensively • Considerations - Make a plan - Make a change
  • 101. How to Code Defensively
  • 102. How to Code Defensively • Questions?