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

PHP Application Security - March 12, 2019

PHP Application Security - March 12, 2019

Anna Filina

March 12, 2019
Tweet

More Decks by Anna Filina

Other Decks in Programming

Transcript

  1. Anna Filina ‣ @ZenikaMontreal ‣ I refactor legacy code. ‣

    I automate tests. ‣ I fix security and performance. ‣ I give talks and workshops.
  2. Course Outline ‣ Application hardening basics. ‣ Injection. ‣ Broken

    authentication. ‣ Sensitive data exposure. ‣ XML external entities (XXE). ‣ Broken access control. ‣ Security misconfiguration. ‣ Cross-site scripting (XSS).
 ‣ Insecure deserialization. ‣ Using components with known vulnerabilities. ‣ Insufficient logging & monitoring. ‣ Buffer overflows. ‣ Cross-site request forgery. ‣ Vulnerability identification and classification. ‣ Threat modelling.
  3. Attack Surface ‣ The sum of all paths into and

    out of the application. ‣ The code that protects these paths. ‣ All valuable data used in the application. ‣ The code that protects these data. ‣ Reduce the attack surface.
  4. Reduce Amount of Code Running ‣ Review and simplify code.

    ‣ Refactor legacy. ‣ Delete dead code. ‣ Fewer/simpler forms. ‣ Bloat = big attack surface.
  5. Reduce Entry Points Available to Untrusted Users ‣ Debug mode.

    ‣ API endpoints. ‣ Don't allow DB access or admin login forms from outside the network. ‣ Files accessible via web server.
  6. Bad /var/www/myproject << vhost target - config - index.php -

    src Good /var/www/myproject - config - public << vhost target - src
  7. Eliminate Services Requested by Relatively Few Users ‣ <5% of

    users authenticate against your AD? ‣ <1% of users need to upload PDFs?
  8. Reduce Unnecessary Transit ‣ Send credentials only once, then use

    token. ‣ Don’t send data that is not needed.
  9. Reduce Amount of Data Stored ‣ Store less user data.

    ‣ Discard data as soon as it's not needed. ‣ Make stored data unusable.
  10. Vectors ‣ Stored injections. ‣ Queries: SQL, LDAP, XPath, NoSQL.

    ‣ OS commands. ‣ SMTP Headers. ‣ Expression languages. ‣ XML parsers.
  11. Solutions ‣ Examine code. ‣ Keep untrusted data separate from

    commands and queries. ‣ Whitelist validation. ‣ Use ORM or ODM. ‣ Bind params/prepared statements. ‣ Escape all user supplied input.
  12. Solutions ‣ Prepared statements: • Ensure that an attacker is

    not able to change the intent of a query. • You only need to forget once, so make it systematic.
  13. Solutions ‣ Validate boundaries (reject or truncate). ‣ Update software

    & libraries on time. ‣ Code written in PHP is fine, unless a problem in PHP or extension.
  14. Rainbow Tables ‣ Create string permutations. ‣ Compute hashes. ‣

    Steal password hashes. ‣ Look up in table.
  15. MD5 Tables Charset Length Table Size ascii-32-95 1-7 52 GB

    ascii-32-95 1-8 460 GB mixalpha-numeric 1-8 127 GB
  16. What About Collisions? ‣ They don’t exist for password-length strings.

    ‣ You won’t have any in your rainbow tables.
  17. Solutions ‣ Salt hashes: • Additional random key (salt) for

    hashing. • Store both salt and hash. • More permutations for attackers to try. ‣ Repeated hashing
  18. Bcrypt ‣ Does all the grunt work for you. ‣

    Pick cost, increase later. ‣ All metadata stored in the resulting hash.
  19. Password Policy ‣ Don't limit number and type of characters.

    ‣ Harder to generate rainbow tables. ‣ Also prevents brute force.
  20. Security Questions ‣ Known by a wide group of people.

    ‣ You're storing more private data. ‣ Security questions on other sites.
  21. Nobody Can See the Full Number ‣ Querying with token

    gives **** **** **** 0123 ‣ Print partial on receipts. ‣ Show partial to your account directors. ‣ Even devs can’t get full number.
  22. Beware of Sessions ‣ Sessions means storage. ‣ Storage means

    it can be stolen. ‣ Send directly to vault. ‣ You can store token.
  23. Vectors ‣ Transit. ‣ Storage on server: • Database. •

    Backups. • Etc. ‣ Storage on client: • Browser. • Cookies. • Etc.
  24. Secure Transit ‣ SSL everything. ‣ Mobile: require SSL chain

    verification. ‣ Mobile: refuse self-signed certificates. ‣ Avoid sensitive data on insecure channels (e-mail, SMS, etc.) ‣ Highly sensitive data: encrypt even if sent over SSL (Heartbleed).
  25. Leak Information With Detailed Error Messages ‣ Stack traces. ‣

    Account enumeration (password reset). ‣ Object enumeration (order numbers, admin pages, etc).
  26. Solutions ‣ Turn off debug mode. ‣ Tune security settings

    (framework, language and system). ‣ Return generic error messages where applicable.
  27. Impact ‣ Hijack session. ‣ Read cookies. ‣ Deface website.

    ‣ Redirect. ‣ Insert hostile content (phishing, keylogger). ‣ Download malware. ‣ Also beware of stored XSS.
  28. Solutions ‣ Use templating engine. • Avoid “raw” filters when

    data destined for output. ‣ Don't pass user data directly to JS (or sanitize). ‣ Escape depending on context (LDAP, XPATH, etc). ‣ Use Content Security Policy.
  29. Solutions ‣ Avoid exposing sequential IDs. ‣ Using tokens might

    not be enough (longer hashes or combination). ‣ Authenticate users & filter data / actions. ‣ Check roles & privileges. ‣ Review code. ‣ Think about your ACL. ‣ Add to your automated test suite.
  30. Given I am authenticating as "user1" with password "123" When

    I request "/purchases/5" Then the response code is 404
  31. General Structure ‣ Trick a user to perform an action

    on your site. ‣ Your site by default doesn't care where the request comes from. ‣ Not a problem with REST APIs, because they're stateless.
  32. Solutions ‣ Don't let GET have side-effects. ‣ CSRF token

    (nonce) - Symfony, Laravel and ZF have it. ‣ Re-authenticate for important operations.
  33. Solutions ‣ Don't use URL for session ID. ‣ Regenerate

    session ID on login. ‣ Timeout session ID. ‣ SSL all the things. ‣ Framework's built-in session management. ‣ Avoid storing data in cookies. ‣ Review password change/recovery.
  34. Vectors ‣ Default configurations. ‣ Default accounts. ‣ Outdated software

    (OS, server, libs, etc.) ‣ Publicly accessible code. ‣ Etc.
  35. Example: MongoDB ‣ Doesn't require credentials by default. ‣ "More

    than 27,000 MongoDB databases seized by ransomware"
 – The Register
  36. Example: Petya ‣ Infected corporations, power supplies & banks worldwide.

    ‣ Victims didn't patch their software. ‣ Victims didn't deactivate a 30-year old SMBv1 file-sharing protocol.
  37. Solutions ‣ Update software & libraries on time. ‣ Turn

    off debug mode. ‣ Change default passwords. ‣ Tune security settings. ‣ Automated config check. ‣ Secure architecture. ‣ Continuous hardening process.
  38. <?xml version="1.0"?> <!DOCTYPE lolz [ <!ENTITY lol "lol"> <!ELEMENT lolz

    (#PCDATA)> <!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;"> <!ENTITY lol2 "&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;"> <!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;"> <!ENTITY lol4 "&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;"> <!ENTITY lol5 "&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;"> <!ENTITY lol6 "&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;"> <!ENTITY lol7 "&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;"> <!ENTITY lol8 "&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;"> <!ENTITY lol9 "&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;"> ]> <lolz>&lol9;</lolz>
  39. Similar Attacks ‣ Fork bomb: recursively replicate a process (in

    any lang) ‣ Zip bomb / zip of death: • zip a 1.3 gigabyte file with only zeroes • make 10 copies, zip • repeat 10 times • end result is merely 45.1 kilobytes • uncompresses into 1.3 exabytes (gigabyte > terabyte > petabyte > exabyte) • break virus scanners when they recursively open it
  40. Attack Examples ‣ Inject malicious content. ‣ Read from the

    filesystem. ‣ Probe internal network (https:/ /192.168.1.1). ‣ DoS (file:/ / /dev/random)
  41. Solutions ‣ Use JSON if possible. ‣ Validate/sanitize input. ‣

    Update your XML libs. ‣ Disable XML external entity and DTD processing.
  42. Attack Examples ‣ Execute any __destruct/__wakeup method with any properties.

    • Upload root kits. • Silently send data or files to a 3rd party server. • Permanently inject key loggers into templates. • Etc. ‣ Alter serialized data to upgrade privileges (example: user cookie).
  43. Solutions ‣ Reject input from untrusted sources (forms, databases, headers,

    etc). ‣ Allow only primitive types. ‣ Use checksums. ‣ Run deserialization using low privileges. ‣ Restrict network requests (whitelist domains). ‣ Log deserialization errors. ‣ Monitor for repeated deserialization by a user.
  44. Why Log & Monitor? ‣ Attacks start with probing, often

    failing. ‣ Monitor to detect probing: • Guess what the attacked was trying to achieve • Discover your vulnerabilities before they do. ‣ Log: • Understand attack to find the vulnerabilities they exploited. • Maybe even find the attacker.
  45. Examples in the Wild ‣ No alerts when database backups

    fail. ‣ No brute-force attack detection. ‣ No DDoS detection. ‣ No URL scan detection. ‣ No alerts in case of CPU spikes. ‣ No alerts in case of application errors. ‣ No centralized log management.
  46. Log Examples ‣ Failed attempts in login: rotating brute-force. ‣

    ACL errors: user A tried to access user B’s transaction. ‣ 404 and 500 errors: URL scans or probing for app vulnerabilities. ‣ Input validation errors: upload a malicious file or input SQL injection. ‣ Log with context and keep for a long time, for later forensics. ‣ Do a pentest to see if your logs provide sufficient data about the attack.
  47. Log Management ‣ Send all your logs to an aggregator

    (example: Datadog). ‣ Add rules to detect suspicious activity and alert. ‣ Can be used for spotting other threats, such as CPU spikes and slow queries.
  48. Avoid Discovering Them in Prod ‣ Code reviews. ‣ Penetration

    testing. ‣ Follow security news, mailing lists, Twitter, etc. ‣ Threat modeling.
  49. Extra ‣ Adopt an incident response and recovery plan. ‣

    Example: NIST Computer Security Incident Handling Guide
 https:/ /nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP. 800-61r2.pdf
  50. Response Plan Example ‣ 1-click process in case of leaked

    passwords: • Log out all users. • Mark as compromised (is_dirty=1). • Force 2nd factor authentication (ex.: Google Authenticator). • Force password change. • Mark as not compromised.
  51. Threat Modelling Process ‣ Two general types of threats: •

    Malicious (DDoS attack) • Incidental (failure of a Storage Device) ‣ Each tech decision introduces potential threat. ‣ Don't waste time on things that are unlikely or have minimal impact.
  52. 1 – Assessment Scope: Identify Assets ‣ DB ‣ Sensitive

    files ‣ Reputation ‣ Customer base ‣ Employee relations ‣ Etc.
  53. 2 – Identify Threat Agents and Possible Attacks ‣ Insiders:

    staff, contractors, vendors, etc. ‣ Outsiders: competitors, criminals, activists, etc. ‣ Performing malicious attacks or inadvertent mistakes. ‣ Other agents: fires, earthquakes, malware, etc.
  54. Countermeasure Examples ‣ Action: security training, OS update. ‣ Device:

    firewall appliances, intrusion detection systems. ‣ Procedure: code reviews, remove unused SSH keys. ‣ Technique: input validation, data encryption.
  55. 4 – Identify Exploitable Vulnerabilities ‣ Search for vulnerabilities that

    connect the possible attacks to the negative consequences. Loss of confidentiality Plaintext CC numbers
  56. 5 – Prioritized Identified Risks ‣ Risk = likelihood &

    impact. ‣ Likelihood: medium. ‣ Impact: high. ‣ Risk: high.
  57. 6 – Identify Countermeasures To Reduce Threat ‣ Reduce the

    risk to acceptable levels. ‣ Example: bind SQL parameters.
  58. 1 – Identifying a Risk ‣ Assets. ‣ Threat agents

    & attacks. ‣ Existing countermeasures. ‣ Exploitable vulnerabilities. ‣ Rate & prioritize. ‣ Countermeasures to reduce threat.
  59. 2 – Likelihood ‣ Vulnerability factors • Ease of discovery

    • Ease of exploit • Awareness • Intrusion detection
  60. 3 - Impact ‣ Technical impact factors • Loss of

    confidentiality • Loss of integrity • Loss of availability • Loss of accountability
  61. 3 - Impact ‣ Business impact factors • Financial damage

    • Reputation damage • Non-compliance • Privacy violation
  62. 4 – Overall Risk Severity Likelihood Low Medium High Impact

    Low Note Low Medium Medium Low Medium High High Medium High Crijcal
  63. 5 – Decide What To Fix ‣ Critical first, but

    check cost of fix. ‣ Don't spend too much time on easy-to-fix but unimportant things.
  64. 6 – Customize Your Risk Rating Model ‣ Add factors.

    ‣ Customize options. ‣ Weigh factors.