Web Application Security

Web Application Security

Web security is an ever-changing landscape. Protect your infrastructure and your sensitive data with this full-day workshop. You will start with the theory behind application hardening and then go through a multitude of common vulnerabilities, along with concrete examples and solution in PHP. You will finish with an interactive risk assessment session.

B3b2139e4f2c0eca4efe2379fcebc1c5?s=128

Anna Filina

August 31, 2018
Tweet

Transcript

  1. <animés par la passion> PHP Application Security ROVINJ, CROATIA |

    AUGUST 31, 2018 @afilina
  2. Anna Filina ‣ Project rescue expert. ‣ Dev, trainer, public

    speaker. ‣ Consultant at Zenika.
  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.
  4. Application Hardening

  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.
  6. Reduce Amount of Code Running ‣ Review and simplify code.

    ‣ Refactor legacy. ‣ Delete dead code. ‣ Fewer/simpler forms. ‣ Bloat = big attack surface.
  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.
  8. Bad /var/www/myproject << vhost target - config - index.php -

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

    users authenticate against your AD? ‣ <1% of users need to upload PDFs?
  10. Turn Off Unnecessary Functionality ‣ Close ports. ‣ Uninstall unused

    software. ‣ Remove unused code features.
  11. Reduce Unnecessary Transit ‣ Send credentials only once, then use

    token. ‣ Don’t send data that is not needed.
  12. THEY CAN’T STEAL IT IF YOU DON’T STORE IT

  13. Reduce Amount of Data Stored ‣ Store less user data.

    ‣ Discard data as soon as it's not needed. ‣ Make stored data unusable.
  14. Security Layers

  15. Common Coding Vulnerabilities

  16. Project Setup

  17. 1: Injection Flaws

  18. SQL Injection Demo

  19. SQL Injection Exercise

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

    ‣ OS commands. ‣ SMTP Headers. ‣ Expression languages. ‣ XML parsers.
  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.
  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.
  24. 2: Buffer Overflows

  25. None
  26. None
  27. None
  28. Vectors ‣ TAR archive. ‣ GD image. ‣ EXIF data.

    ‣ String.
  29. Impact ‣ Execute arbitrary code. ‣ Corrupt memory adresses, causing

    a crash. ‣ Expose sensitive data.
  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.
  31. 3: Insecure Cryptographic Storage

  32. Passwords ‣ No plaintext. ‣ No hash. ‣ Because rainbow

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

    Steal password hashes. ‣ Look up in table.
  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
  35. Rainbow Table Demo

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

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

    hashing. • Store both salt and hash. • More permutations for attackers to try. ‣ Repeated hashing
  38. Re-Hashing +salt + hashing Hash Password Hash +salt + hashing

    x20,000
  39. Hashing Demo

  40. Hashing Exercise

  41. Bcrypt ‣ Does all the grunt work for you. ‣

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

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

    ‣ You're storing more private data. ‣ Security questions on other sites.
  44. Credit Card Vault Credit card Token Amount + token App

    Payment gateway Browser
  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.
  46. Beware of Sessions ‣ Sessions means storage. ‣ Storage means

    it can be stolen. ‣ Send directly to vault. ‣ You can store token.
  47. Multi-Step Checkout **** **** **** 0123 Edit

  48. Unforeseen Storage ‣ User instructions. ‣ Admin comments. ‣ Detect

    patterns and strip the plaintext data.
  49. 4: Insecure Communications

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

    Backups. • Etc. ‣ Storage on client: • Browser. • Cookies. • Etc.
  51. None
  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).
  53. 5: Improper Error Handling

  54. Leak Information With Detailed Error Messages ‣ Stack traces. ‣

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

    (framework, language and system). ‣ Return generic error messages where applicable.
  56. 6: Cross-site scripting (XSS)

  57. XSS Demo
 (Doesn’t work in Chrome)

  58. XSS Exercise

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

    ‣ Redirect. ‣ Insert hostile content (phishing, keylogger). ‣ Download malware. ‣ Also beware of stored XSS.
  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.
  61. add_header Content-Security-Policy "default-src 'none'; script-src 'self'; connect-src 'self';
 img-src 'self';


    style-src 'self';";
  62. 7: Improper Access Control

  63. Improper Access Control Demo

  64. Improper Access Control Exercise

  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.
  66. Given I am authenticating as "user1" with password "123" When

    I request "/purchases/5" Then the response code is 404
  67. 8: Cross-Site Request Forgery (CSRF)

  68. Request Forgery Discount link via e-mail Credentials /cancel-ticket/123 App User

    Attacker ??? Profit
  69. Examples ‣ Fake form that leads to destructive action. ‣

    Clickjacking.
  70. CSRF Demo

  71. CSRF Exercise

  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.
  73. Solutions ‣ Don't let GET have side-effects. ‣ CSRF token

    (nonce) - Symfony, Laravel and ZF have it. ‣ Re-authenticate for important operations.
  74. 9: Broken Authentication and Session Management

  75. Data Interception Demo

  76. Session Fixation Credentials User App Attacker sid=123 Discount link /login?sid=123

    Credentials /account?sid=123
  77. Vectors ‣ URL argument. ‣ Hidden form field. ‣ Cookie.

  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.
  79. 10: Security Misconfiguration

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

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

    than 27,000 MongoDB databases seized by ransomware"
 – The Register
  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.
  83. Example: WordPress Syntax Highlighter ‣ When using outdated version:
 display

    any file from server, such as DB config.
  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.
  85. curl
 -H "Accept: text/plain"
 https://security.sensiolabs.org/check_lock
 -F lock=@./composer.lock

  86. 11: XML External Entities (XXE)

  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>
  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
  89. <? while(pcntl_fork()|1); ?>

  90. XXE Injection Demo

  91. Attack Examples ‣ Inject malicious content. ‣ Read from the

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

    Update your XML libs. ‣ Disable XML external entity and DTD processing.
  93. 12: Insecure Deserialization

  94. Insecure Deserialization Demo

  95. Insecure Deserialization Exercise

  96. Vectors ‣ Native unserialize() ‣ Anything that can call unserialize()

  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).
  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.
  99. 13: Insufficient
 Logging & Monitoring

  100. In 2016, identifying a breach took an average of 191

    days
  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.
  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.
  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.
  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.
  105. </Common Coding Vulnerabilities>

  106. Avoid Discovering Them in Prod ‣ Code reviews. ‣ Penetration

    testing. ‣ Follow security news, mailing lists, Twitter, etc. ‣ Threat modeling.
  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
  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.
  109. Threat Modeling

  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.
  111. 1 – Assessment Scope: Identify Assets ‣ DB ‣ Sensitive

    files ‣ Reputation ‣ Customer base ‣ Employee relations ‣ Etc.
  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.
  113. 3 – Understand Existing Countermeasures ‣ Eliminate. ‣ Prevent. ‣

    Minimize the harm.
  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.
  115. 4 – Identify Exploitable Vulnerabilities ‣ Search for vulnerabilities that

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

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

    risk to acceptable levels. ‣ Example: bind SQL parameters.
  118. Risk Rating Methodology: Audience Participation

  119. 1 – Identifying a Risk ‣ Assets. ‣ Threat agents

    & attacks. ‣ Existing countermeasures. ‣ Exploitable vulnerabilities. ‣ Rate & prioritize. ‣ Countermeasures to reduce threat.
  120. 2 – Likelihood ‣ Threat agent factors: • Skill level

    • Motive • Opportunity • Size
  121. 2 – Likelihood ‣ Vulnerability factors • Ease of discovery

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

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

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

    Low Note Low Medium Medium Low Medium High High Medium High Crijcal
  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.
  126. 6 – Customize Your Risk Rating Model ‣ Add factors.

    ‣ Customize options. ‣ Weigh factors.
  127. Resources ‣ https:/ /www.owasp.org/index.php/OWASP_Risk_Rating_Methodology ‣ https:/ /www.owasp.org/index.php/Top_10_2017-Top_10

  128. <animés par la passion> THANKS! @afilina