Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Defensive Coding Crash Course - ZendCon 2017

493 views

Published on

Ensuring software reliability, resiliency, and recoverability is best achieved by practicing effective defensive coding. Take a crash course in defensive coding with PHP and learn about attack surfaces, input validation, canonicalization, secure type checking, external library vetting, cryptographic agility, exception management, code reviews, and unit and behavioral testing. Learn some helpful tips and tricks from experienced professionals within the PHP community as we review the latest blogs and discussions on best practices to defend your project.

Published in: Software
  • Writing good research paper is quite easy and very difficult simultaneously. It depends on the individual skill set also. You can get help from research paper writing. Check out, please ⇒ www.HelpWriting.net ⇐
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Be the first to like this

Defensive Coding Crash Course - ZendCon 2017

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

×