PHP Application Security - March 12, 2019

PHP Application Security - March 12, 2019

B3b2139e4f2c0eca4efe2379fcebc1c5?s=128

Anna Filina

March 12, 2019
Tweet

Transcript

  1. 2.

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

    I automate tests. ‣ I fix security and performance. ‣ I give talks and workshops.
  2. 3.

    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. 5.

    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. 6.

    Reduce Amount of Code Running ‣ Review and simplify code.

    ‣ Refactor legacy. ‣ Delete dead code. ‣ Fewer/simpler forms. ‣ Bloat = big attack surface.
  5. 7.

    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. 8.

    Bad /var/www/myproject << vhost target - config - index.php -

    src Good /var/www/myproject - config - public << vhost target - src
  7. 9.

    Eliminate Services Requested by Relatively Few Users ‣ <5% of

    users authenticate against your AD? ‣ <1% of users need to upload PDFs?
  8. 10.
  9. 11.

    Reduce Unnecessary Transit ‣ Send credentials only once, then use

    token. ‣ Don’t send data that is not needed.
  10. 13.

    Reduce Amount of Data Stored ‣ Store less user data.

    ‣ Discard data as soon as it's not needed. ‣ Make stored data unusable.
  11. 20.
  12. 21.

    Vectors ‣ Stored injections. ‣ Queries: SQL, LDAP, XPath, NoSQL.

    ‣ OS commands. ‣ SMTP Headers. ‣ Expression languages. ‣ XML parsers.
  13. 22.

    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.
  14. 23.

    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.
  15. 25.
  16. 26.
  17. 27.
  18. 30.

    Solutions ‣ Validate boundaries (reject or truncate). ‣ Update software

    & libraries on time. ‣ Code written in PHP is fine, unless a problem in PHP or extension.
  19. 33.

    Rainbow Tables ‣ Create string permutations. ‣ Compute hashes. ‣

    Steal password hashes. ‣ Look up in table.
  20. 34.

    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
  21. 36.

    What About Collisions? ‣ They don’t exist for password-length strings.

    ‣ You won’t have any in your rainbow tables.
  22. 37.

    Solutions ‣ Salt hashes: • Additional random key (salt) for

    hashing. • Store both salt and hash. • More permutations for attackers to try. ‣ Repeated hashing
  23. 41.

    Bcrypt ‣ Does all the grunt work for you. ‣

    Pick cost, increase later. ‣ All metadata stored in the resulting hash.
  24. 42.

    Password Policy ‣ Don't limit number and type of characters.

    ‣ Harder to generate rainbow tables. ‣ Also prevents brute force.
  25. 43.

    Security Questions ‣ Known by a wide group of people.

    ‣ You're storing more private data. ‣ Security questions on other sites.
  26. 45.

    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.
  27. 46.

    Beware of Sessions ‣ Sessions means storage. ‣ Storage means

    it can be stolen. ‣ Send directly to vault. ‣ You can store token.
  28. 50.

    Vectors ‣ Transit. ‣ Storage on server: • Database. •

    Backups. • Etc. ‣ Storage on client: • Browser. • Cookies. • Etc.
  29. 51.
  30. 52.

    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).
  31. 54.

    Leak Information With Detailed Error Messages ‣ Stack traces. ‣

    Account enumeration (password reset). ‣ Object enumeration (order numbers, admin pages, etc).
  32. 55.

    Solutions ‣ Turn off debug mode. ‣ Tune security settings

    (framework, language and system). ‣ Return generic error messages where applicable.
  33. 59.

    Impact ‣ Hijack session. ‣ Read cookies. ‣ Deface website.

    ‣ Redirect. ‣ Insert hostile content (phishing, keylogger). ‣ Download malware. ‣ Also beware of stored XSS.
  34. 60.

    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.
  35. 65.

    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.
  36. 66.

    Given I am authenticating as "user1" with password "123" When

    I request "/purchases/5" Then the response code is 404
  37. 70.
  38. 72.

    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.
  39. 73.

    Solutions ‣ Don't let GET have side-effects. ‣ CSRF token

    (nonce) - Symfony, Laravel and ZF have it. ‣ Re-authenticate for important operations.
  40. 78.

    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.
  41. 80.

    Vectors ‣ Default configurations. ‣ Default accounts. ‣ Outdated software

    (OS, server, libs, etc.) ‣ Publicly accessible code. ‣ Etc.
  42. 81.

    Example: MongoDB ‣ Doesn't require credentials by default. ‣ "More

    than 27,000 MongoDB databases seized by ransomware"
 – The Register
  43. 82.

    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.
  44. 84.

    Solutions ‣ Update software & libraries on time. ‣ Turn

    off debug mode. ‣ Change default passwords. ‣ Tune security settings. ‣ Automated config check. ‣ Secure architecture. ‣ Continuous hardening process.
  45. 87.

    <?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>
  46. 88.

    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
  47. 91.

    Attack Examples ‣ Inject malicious content. ‣ Read from the

    filesystem. ‣ Probe internal network (https:/ /192.168.1.1). ‣ DoS (file:/ / /dev/random)
  48. 92.

    Solutions ‣ Use JSON if possible. ‣ Validate/sanitize input. ‣

    Update your XML libs. ‣ Disable XML external entity and DTD processing.
  49. 97.

    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).
  50. 98.

    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.
  51. 101.

    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.
  52. 102.

    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.
  53. 103.

    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.
  54. 104.

    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.
  55. 106.

    Avoid Discovering Them in Prod ‣ Code reviews. ‣ Penetration

    testing. ‣ Follow security news, mailing lists, Twitter, etc. ‣ Threat modeling.
  56. 107.

    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
  57. 108.

    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.
  58. 110.

    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.
  59. 111.

    1 – Assessment Scope: Identify Assets ‣ DB ‣ Sensitive

    files ‣ Reputation ‣ Customer base ‣ Employee relations ‣ Etc.
  60. 112.

    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.
  61. 114.

    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.
  62. 115.

    4 – Identify Exploitable Vulnerabilities ‣ Search for vulnerabilities that

    connect the possible attacks to the negative consequences. Loss of confidentiality Plaintext CC numbers
  63. 116.

    5 – Prioritized Identified Risks ‣ Risk = likelihood &

    impact. ‣ Likelihood: medium. ‣ Impact: high. ‣ Risk: high.
  64. 117.

    6 – Identify Countermeasures To Reduce Threat ‣ Reduce the

    risk to acceptable levels. ‣ Example: bind SQL parameters.
  65. 119.

    1 – Identifying a Risk ‣ Assets. ‣ Threat agents

    & attacks. ‣ Existing countermeasures. ‣ Exploitable vulnerabilities. ‣ Rate & prioritize. ‣ Countermeasures to reduce threat.
  66. 120.
  67. 121.

    2 – Likelihood ‣ Vulnerability factors • Ease of discovery

    • Ease of exploit • Awareness • Intrusion detection
  68. 122.

    3 - Impact ‣ Technical impact factors • Loss of

    confidentiality • Loss of integrity • Loss of availability • Loss of accountability
  69. 123.

    3 - Impact ‣ Business impact factors • Financial damage

    • Reputation damage • Non-compliance • Privacy violation
  70. 124.

    4 – Overall Risk Severity Likelihood Low Medium High Impact

    Low Note Low Medium Medium Low Medium High High Medium High Crijcal
  71. 125.

    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.
  72. 126.

    6 – Customize Your Risk Rating Model ‣ Add factors.

    ‣ Customize options. ‣ Weigh factors.