Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Notes on security - Bulgaria PHP Virtual Meetup

Sponsored · SiteGround - Reliable hosting with speed, security, and support you can count on.

Notes on security - Bulgaria PHP Virtual Meetup

Notes on security

Avatar for Goce Bonev

Goce Bonev

January 10, 2023
Tweet

More Decks by Goce Bonev

Other Decks in Programming

Transcript

  1. ▪ SQL Injection; ▪ XSS; ▪ Directory traversal; ▪ Remote

    code execution; ▪ Denial of service attacks; ▪ Securing sessions; ▪ Securing file uploads; ▪ File system security; ▪ Security headers; ▪ CSRF; ▪ …. Not going to talk about…. Image: iconpacks.net
  2. ▪ Security is rarely high on the priorities list /

    marginal topic; ▪ Security is not part of the development process; ▪ Developers are expected to write secure code; ▪ Developers get little to no security training; ▪ Stack Overflow copy-paste development; ▪ Security can not catch up with development; ▪ Security / penetration tests are performed just before application goes to production or when it is already in production; ▪ Becomes short term high priority after an incident; ▪ Overconfidence is a problem; ▪ Most developers state their code is secure; Reality Image: iconpacks.net
  3. ▪ Use The Framework; ▪ Use this ORM; ▪ Use

    this package; ▪ Use these security headers; ▪ Use this / use that …; ▪ Learn the OWASP Top 10; ▪ Use md5 / sha1 / bcrypt; ▪ Outdated / incorrect Stack Overflow answers; ▪ Mostly outdated best practices and checklists; ▪ Cyber security frameworks (ISO 27001 / ISO 27002, PCI DSS…); ▪ Builders not breakers; ▪ …. Typical security training Image: iconpacks.net
  4. ▪ Define incorrect / incomplete trust boundaries –usually focused around

    user input; ▪ Canonize / standardize / normalize – convert data to a standard, normal, canonical form; /var/www/../../etc/passwd => /etc/passwd ▪ Sanitize – clean up dangerous data; ▪ Validate – making sure data is valid in the context of the domain; More on validation later…. ▪ The Framework – supposed to deal with everything else; The result
  5. ▪ Confidentiality – protecting private and sensitive information from unauthorized

    access; ▪ Integrity – data trustworthiness, accuracy and consistency, prevent modification / deletion by unauthorized parties; ▪ Availability – authorized individuals can access their data most of the time; ▪ Authentication – the ability of systems to confirm an identity; ▪ Non-repudiation – assurance about data origins and integrity, proof of delivery + proof of senders identity; CIA Triad
  6. Something or someone that can intentionally or accidentally, obtain, damage

    or destroy something that has worth, like data or systems. ▪ You; ▪ System administrators; ▪ Developers; ▪ Employees, contractors, staff members; ▪ Cybercriminals, activists, people and organizations with malicious intent; ▪ Script kiddies; ▪ Natural events / force majeure; Threats
  7. ✓ 60+ government employee; ✓ No technical skills; ✓ Unintentionally

    destroyed a government website with 60K documents and over 100K pages; ✓ Twice in 3 years! ✓ No one knows how she did it; Real story Image: Asier Relampagoe Studio / Freepik.com
  8. Threat ▪ Cybercriminals; ▪ Activists; ▪ Employees / insiders; ▪

    Contractors; ▪ Competition; ▪ Nature, weather, geological; Risk Risk ▪ Privacy /data breach; ▪ Business disruption; ▪ Financial loss; ▪ Reputation damage; ▪ Legal implications; ▪ Loss of life; Vulnerability ▪ Human error; ▪ Broken process; ▪ Software bug; ▪ Legacy code; ▪ Broken access control; ▪ Hardware; ▪ Physical access; + =
  9. Technical ✓ OWASP Top 10; ✓ Focus on getting access

    to data or infrastructure; ✓ Availability; Types of attacks Business ✓ Sophisticated attacks; ✓ Focused on circumventing business rules or abusing the business;
  10. 1. Injection flaws; 2. Broken authentication; 3. Sensitive data exposure;

    4. XML External Entities (XXE); 5. Broken access control; 6. Security misconfiguration; 7. Cross-Site Scripting XSS; 8. Insecure deserialization; 9. Using components with known vulnerabilities; 10.Insufficient logging and monitoring; https://owasp.org/www-project-top-ten/ OWASP
  11. ▪ Defense in depth – Layered security on a macro

    and micro level; ▪ Principle of least privilege - Limit privileges to the minimum required for normal functioning of the application. Access on a need-to-know basis; Minimize attack surface area; ▪ Compartmentalize – Limit the attacker’s ability for damage. Design modular systems, if one module is compromised, it does not mean that the whole system is; ▪ Trust no one and nothing – Assume everything is untrusted; ▪ Keep security simple – Design for simplicity, KISS. The more complex the system, the more risk it caries; ▪ Audit trail – When something goes wrong you need to know how it happened. Record all significant events in a secure store. Do not use your main database for storing your audit logs, use an append only storage; ▪ Secure defaults and fail securely – Default behavior, default logins, values configuration params. Always start with no permissions / zero access; ▪ Never rely on obscurity – Assume the attacker has perfect knowledge of your system; If you think that something is secure because it is hidden, it is not secure at all; ▪ Never invent your own security technology – Always use a battle tested one; ▪ Secure the weakest link – Identify who or what is the weakest link in your system; Principles
  12. ▪ Don’t rely on single layer of security. ▪ Containing

    and slowing down the attacker by using multiple layers of security; ▪ With multiple it becomes harder for an attacker to be successful even if one fails, there is another one that stands in the way. ▪ The opposite of Defense in depth is very strong perimeter security and no defenses inside. As soon as the first defense is breached there is nothing to stop the attacker from compromising the whole system; Defense in depth
  13. ✓ Implement plaintext passwords as read-once objects; ✓ Secure hashing

    with bcrypt / Argon2i; ✓ AES-256 Encryption; ✓ Configurable protection level, hash upgrade; ✓ Brute force protection / ';--have i been pwned? ✓ Never send passwords in emails or store them in logs; ✓ Password construction policies / strength checker; https://dropbox.tech/security/how-dropbox-securely-stores-your-passwords Example on microlevel: Passwords
  14. ▪ The bare minimum access and resources the app needs

    to perform its function; ▪ Applies to apps, credentials, processes, infrastructure… simply everything; ▪ Start with zero access rights and resources and only add what you really need; ▪ When adding a “privilege” ask why, is it a necessity or a convenience; ▪ Don’t take shortcuts, ex: “s3:*”, running as root; ▪ Read only file systems; ▪ Avoid creating superusers; ▪ Avoid unnecessary accumulation of access and permissions; ▪ Helps with compliance; Principle of least privilege
  15. ▪ Complexity is an enemy; ▪ Introduces unpredictable behavior; ▪

    Hard to reason about code; ▪ Hard to maintain; ▪ Slow / hard developer onboarding; Complexity
  16. ▪ Approach for building software focusing on the domain; ▪

    Set of patterns and good practices of software development; ▪ Big ball of mud problem; ▪ Strategic design (why, what) - Bounded contexts, subdomains, ubiquitous language and context maps; ▪ Tactical design (how) - Entities, services, repositories, value objects, aggregates, events, factories, etc.; ▪ Architecture - Hexagonal, Layered, CQRS; ▪ Refactoring toward deeper insight / Iterative by nature; ▪ Eases communication / Encourages talking to domain experts; ▪ Good for complex domains; ▪ DDD-Lite; ▪ Not a silver bullet; Domain-Driven Design
  17. “Domain Driven Security is about taking ideas from DDD and

    using them as tools to address security concerns, even though the tools were not originally designed specifically for security issues.” Dan Bergh Johnsson, Dr. John Wilander [2009] http://dearjunior.blogspot.be/2009/09/introducing-domain-driven-security.html Domain-Driven security
  18. ▪ Implicit concepts, rules, domain knowledge, are modeled as explicit

    code concepts; ▪ Domain primitives have built in validation, they can not be created invalid; ▪ The PHP type system ensures correct domain objects are used; ▪ Primitive types (strings, double, ints, null..) are not trusted by default, you forgot to validate or model something; ▪ Model NULL explicitly; Don’t poison your code with null checks; ▪ Context specific domain primitives library; RFC defined email != email in your context; ▪ Business rules still need to be validated but ALL building blocks are ALWAYS valid; ▪ Validation outside the domain model becomes a code smell; ▪ Application architecture*; Domain-Driven security building blocks
  19. ▪ Modeling using language primitives (strings, double, ints..); ▪ Ex.

    Username, email, personal ID number, credit card numbers, quantity; ▪ Accidental parameter swapping; ▪ Validation has to be performed over and over and thus easily forgotten. Scattered / inconsistent validation, excessive defensive coding; ▪ When rules change, validation has to be updated everywhere; ▪ Leaking sensitive data into logs; ▪ Security flaws arising from broken business rules can exist for long time without being detected; ▪ Lead to buggy and insecure code; ▪ Multiple entry points: public forms, admin panel, console, message queues, databases, APIs etc; ▪ I want to order 2147483647 / - 1 bottles of wine; ▪ Username is ' OR 1 = 1 LIMIT 1 -- ‘; ▪ My personal ID number is 11111111111; ▪ Ex. Agency client flag; Implicit concepts
  20. ▪ Mutability allows state to change; immutability prevents it; Big

    difference for security; ▪ Mutable objects carry risk; ▪ Reduce the risk by making immutable everything that can be; ▪ Solves integrity issues, what is validated stays valid; ▪ Reduces time of check to time of use (TOCTTOU) problems, no data is mutated in between; ▪ Simply, no setters or methods that change the value; ▪ Once an object is created, it can only be replaced by another instance; ▪ Plays well with DDD, DDS, event sourcing… ▪ Strive to make objects immutable; Immutability
  21. ▪ Explicitly modeled concept in the domain; ▪ Immutable; ▪

    No concept of identity; ▪ Comparable by value of its properties; ▪ Can not be created invalid, always contain a valid value; ▪ Reduce primitive obsession; ▪ Add context to a value; ▪ Ex: Money, PhoneNumber, EmailAddress, IBSN; ▪ Can encapsulate business operations on the value, ex: adding and subtracting money, calculating percentages…; Value objects final class ProductName { private string $value; public function __construct(string $value) { if (!self::isValid($value)) { throw new InvalidProductArgumentException::invalidProductName(); } $this->value = $value; } public function value() : string { return $this->value; } public static function isValid(string $value) : bool { return (bool) preg_match('/^[a-zA-Z0-9]{2,32}$/D', $value); } }
  22. Value objects final class ProductService { ..... public function renameProduct(int

    $id, string $newName) : void { ..... } public function renameProduct(ProductId $id, ProductName $newName) : void { ..... } } final class Product { ..... public function rename(string $newName) : void { ..... } public function rename(ProductName $newName) : void { ..... } }
  23. ▪ Object, inconsistent with the business rules is not only

    a bug, it’s a security issue; ▪ Uphold invariants in constructors; All domain objects (entities, value objects…) are valid at creation; ▪ Protect the integrity of objects. Don’t allow clients to change data in violation of business rules; ▪ No public fields; Getter methods should return only immutable data / objects; ▪ Remove all setter methods and define explicit methods performing operations on your objects; ▪ Make sure that collections are immutable and don’t leak mutable data; Domain-Driven security
  24. Read-once object is a design pattern that can mitigate the

    possibility of intentional or unintentional leakage of sensitive data. ▪ Do not prevent data from leaking, but facilitate detection of unintentional use / leaking early in the development process; ▪ Represent sensitive values or concepts (password, credit card number, Personal ID number…); ▪ Most commonly implemented as a domain primitive (not a DDD value object since it is not immutable); ▪ Its value can be read once and once only; ▪ Must not allow extension (declared as final); ▪ Prevents serialization / var_dump() __debugInfo() ; ▪ To string method does not leak sensitive data; Read-once objects final class Password implements Serializable { private string $value; private bool $consumed; public function __construct(string $value) { $this->value = $value; $this->consumed = false; } public function value() : string { if ($this->consumed) { throw new LogicException('Already consumed!'); } $returnValue = $this->value; $this->value = ''; $this->consumed = true; return $returnValue; } public function __toString() { return '************'; } public function __clone() { $this->deny(); } public function serialize() { $this->deny(); } public function unserialize($serialized) : void { $this->deny(); } private function deny() : void { throw new LogicException('Serialization is not supported!'); } }
  25. ✓ Be a pessimist, always assume failure; ✓ Use whitelisting,

    not blacklisting. Deny all, allow from; ✓ Fail fast! Catch bad data or invalid situations fast, use precondition validations at the beginning of the method / function; ✓ Don’t do type juggling, use strict types declare(strict_types=1); ✓ Use domain primitives ; ✓ Use strict comparisons ===; ✓ Avoid nested if statements, readable code reduces bugs and security issues; Tips: Be a pessimist, fail fast… private bool $success = true; ...... CODE ...... return $success; private bool $success = false; ...... CODE ...... return $success; public function doSomething(User $user) : void { if (!$this->isAllowedFor($user) { throw new Exception(Forbidden!'); } ...... CODE ...... $this->completeTheAction(); }
  26. ✓ Keep an eye on PHP security advisories; ✓ Check

    if you have installed dependencies with known security vulnerabilities; ✓ Roave security advisories package; ✓ SensioLabs security checker; ✓ Whoops, die and dump dd() etc. move to dev dependencies; Composer "require-dev": { "roave/security-advisories": "dev-master", "filp/whoops": "^2.7", "wanfeiyy/dd": "^1.0" }
  27. ✓ Improper exception handling is a frequent source of vulnerabilities;

    ✓ When the system fails, always fail securely; ✓ Don’t leak code, configuration, system information and secrets; ✓ Use a global exception handler; ✓ Log errors and exceptions; ✓ Show a simple “Service not available, try again later” message and log the error; ✓ Treat warnings as errors; Handle errors securely
  28. ▪ PHP config files; ▪ .env files; ▪ Environment variables;

    ▪ Encrypted configuration files, decryption key requested externally; ▪ Secrets retrieval on request (ex. Starting a container, starting a VM, application start); ▪ Leasing secrets and secrets rotation (Vault, AWS Secrets Manager….); Secrets management
  29. Acceptable for ✓ Configuration variables that are not secret; ✓

    API endpoints / hostnames; ✓ Public keys; Not good for ▪ Sensitive / private variables; ▪ Passwords; ▪ API Keys; ▪ Private keys; Secrets in environment variables Recommendations ✓ No plaintext secrets in environment variables; ✓ Encrypt before putting them in ENV and decrypt before using them – expensive in some cases; ✓ Centralized configuration service; ✓ OTP or short lived passwords;
  30. Options ▪ GCP Secret Manager; ▪ GCP Cloud Key Management;

    ▪ AWS Key Management Service (KMS); ▪ AWS Secrets Manager; ▪ AWS Systems Manager Parameter Store; ▪ Azure Key Vault; ▪ HashiCorp Vault; Comparison: https://scalesec.com/blog/a-comparison-of-secrets-managers-for-aws/ Secure key/secrets storage
  31. ✓ Encryption at rest; ✓ Encryption in transit; ✓ At

    least 256-bit Advanced Encryption Standard (AES) in Galois Counter Mode (GCM); ✓ Libsodium; ✓ Envelope encryption (DEK + KEK); ✓ Do not store the keys and data on the same system; ✓ Key rotation; ✓ Encryption as a service; ✓ Literal search of encrypted data using blind keys; ✓ Crypto-shredding; Battle-tested libraries: https://github.com/paragonie/halite https://github.com/paragonie/ciphersweet Encryption Example Key storage + encrypted DB + vulnerabilities ▪ Key on application server; ▪ Key not on the app server; ▪ Both cases with envelope encryption; ▪ SQL Injection + file upload vulnerability; ▪ How do we protect an app that deals with sensitive data…
  32. “One unrepaired broken window is a signal that no one

    cares, and so breaking more windows costs nothing.” ✓ Unconsciously, we are all subject to the Broken Windows psychology; ✓ Start a project clean and try to keep it clean; ✓ Make as few shortcuts and as little technical debt as possible; ✓ As soon as a shortcut creeps in, it acts as a broken window and attracts more shortcuts; References: “Get Your Hands Dirty on Clean Architecture” - Tom Hombergs https://www.psychologytoday.com/intl/basics/broken-windows-theory Broken windows theory Image: Freepik.com
  33. ▪ Educate yourself, train your team; ▪ Defense in depth;

    ▪ Implement secure coding practices; ▪ Avoid primitive types; ▪ Immutability; ▪ Use Domain Driven Security or at least value objects with built-in validation; ▪ Secure by design / make security part of the development process; ▪ Adopt security guidelines in your team / organization; ▪ Code reviews; ▪ Use tools to find the most obvious vulnerabilities; ▪ Test, test, test; Takeaways