Slide 1

Slide 1 text

PHP Application Security ROVINJ, CROATIA | AUGUST 31, 2018 @afilina

Slide 2

Slide 2 text

Anna Filina ‣ Project rescue expert. ‣ Dev, trainer, public speaker. ‣ Consultant at Zenika.

Slide 3

Slide 3 text

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.

Slide 4

Slide 4 text

Application Hardening

Slide 5

Slide 5 text

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.

Slide 6

Slide 6 text

Reduce Amount of Code Running ‣ Review and simplify code. ‣ Refactor legacy. ‣ Delete dead code. ‣ Fewer/simpler forms. ‣ Bloat = big attack surface.

Slide 7

Slide 7 text

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.

Slide 8

Slide 8 text

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

Slide 9

Slide 9 text

Eliminate Services Requested by Relatively Few Users ‣ <5% of users authenticate against your AD? ‣ <1% of users need to upload PDFs?

Slide 10

Slide 10 text

Turn Off Unnecessary Functionality ‣ Close ports. ‣ Uninstall unused software. ‣ Remove unused code features.

Slide 11

Slide 11 text

Reduce Unnecessary Transit ‣ Send credentials only once, then use token. ‣ Don’t send data that is not needed.

Slide 12

Slide 12 text

THEY CAN’T STEAL IT IF YOU DON’T STORE IT

Slide 13

Slide 13 text

Reduce Amount of Data Stored ‣ Store less user data. ‣ Discard data as soon as it's not needed. ‣ Make stored data unusable.

Slide 14

Slide 14 text

Security Layers

Slide 15

Slide 15 text

Common Coding Vulnerabilities

Slide 16

Slide 16 text

Project Setup

Slide 17

Slide 17 text

1: Injection Flaws

Slide 18

Slide 18 text

SQL Injection Demo

Slide 19

Slide 19 text

SQL Injection Exercise

Slide 20

Slide 20 text

No content

Slide 21

Slide 21 text

Vectors ‣ Stored injections. ‣ Queries: SQL, LDAP, XPath, NoSQL. ‣ OS commands. ‣ SMTP Headers. ‣ Expression languages. ‣ XML parsers.

Slide 22

Slide 22 text

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.

Slide 23

Slide 23 text

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.

Slide 24

Slide 24 text

2: Buffer Overflows

Slide 25

Slide 25 text

No content

Slide 26

Slide 26 text

No content

Slide 27

Slide 27 text

No content

Slide 28

Slide 28 text

Vectors ‣ TAR archive. ‣ GD image. ‣ EXIF data. ‣ String.

Slide 29

Slide 29 text

Impact ‣ Execute arbitrary code. ‣ Corrupt memory adresses, causing a crash. ‣ Expose sensitive data.

Slide 30

Slide 30 text

Solutions ‣ Validate boundaries (reject or truncate). ‣ Update software & libraries on time. ‣ Code written in PHP is fine, unless a problem in PHP or extension.

Slide 31

Slide 31 text

3: Insecure Cryptographic Storage

Slide 32

Slide 32 text

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

Slide 33

Slide 33 text

Rainbow Tables ‣ Create string permutations. ‣ Compute hashes. ‣ Steal password hashes. ‣ Look up in table.

Slide 34

Slide 34 text

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

Slide 35

Slide 35 text

Rainbow Table Demo

Slide 36

Slide 36 text

What About Collisions? ‣ They don’t exist for password-length strings. ‣ You won’t have any in your rainbow tables.

Slide 37

Slide 37 text

Solutions ‣ Salt hashes: • Additional random key (salt) for hashing. • Store both salt and hash. • More permutations for attackers to try. ‣ Repeated hashing

Slide 38

Slide 38 text

Re-Hashing +salt + hashing Hash Password Hash +salt + hashing x20,000

Slide 39

Slide 39 text

Hashing Demo

Slide 40

Slide 40 text

Hashing Exercise

Slide 41

Slide 41 text

Bcrypt ‣ Does all the grunt work for you. ‣ Pick cost, increase later. ‣ All metadata stored in the resulting hash.

Slide 42

Slide 42 text

Password Policy ‣ Don't limit number and type of characters. ‣ Harder to generate rainbow tables. ‣ Also prevents brute force.

Slide 43

Slide 43 text

Security Questions ‣ Known by a wide group of people. ‣ You're storing more private data. ‣ Security questions on other sites.

Slide 44

Slide 44 text

Credit Card Vault Credit card Token Amount + token App Payment gateway Browser

Slide 45

Slide 45 text

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.

Slide 46

Slide 46 text

Beware of Sessions ‣ Sessions means storage. ‣ Storage means it can be stolen. ‣ Send directly to vault. ‣ You can store token.

Slide 47

Slide 47 text

Multi-Step Checkout **** **** **** 0123 Edit

Slide 48

Slide 48 text

Unforeseen Storage ‣ User instructions. ‣ Admin comments. ‣ Detect patterns and strip the plaintext data.

Slide 49

Slide 49 text

4: Insecure Communications

Slide 50

Slide 50 text

Vectors ‣ Transit. ‣ Storage on server: • Database. • Backups. • Etc. ‣ Storage on client: • Browser. • Cookies. • Etc.

Slide 51

Slide 51 text

No content

Slide 52

Slide 52 text

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

Slide 53

Slide 53 text

5: Improper Error Handling

Slide 54

Slide 54 text

Leak Information With Detailed Error Messages ‣ Stack traces. ‣ Account enumeration (password reset). ‣ Object enumeration (order numbers, admin pages, etc).

Slide 55

Slide 55 text

Solutions ‣ Turn off debug mode. ‣ Tune security settings (framework, language and system). ‣ Return generic error messages where applicable.

Slide 56

Slide 56 text

6: Cross-site scripting (XSS)

Slide 57

Slide 57 text

XSS Demo
 (Doesn’t work in Chrome)

Slide 58

Slide 58 text

XSS Exercise

Slide 59

Slide 59 text

Impact ‣ Hijack session. ‣ Read cookies. ‣ Deface website. ‣ Redirect. ‣ Insert hostile content (phishing, keylogger). ‣ Download malware. ‣ Also beware of stored XSS.

Slide 60

Slide 60 text

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.

Slide 61

Slide 61 text

add_header Content-Security-Policy "default-src 'none'; script-src 'self'; connect-src 'self';
 img-src 'self';
 style-src 'self';";

Slide 62

Slide 62 text

7: Improper Access Control

Slide 63

Slide 63 text

Improper Access Control Demo

Slide 64

Slide 64 text

Improper Access Control Exercise

Slide 65

Slide 65 text

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.

Slide 66

Slide 66 text

Given I am authenticating as "user1" with password "123" When I request "/purchases/5" Then the response code is 404

Slide 67

Slide 67 text

8: Cross-Site Request Forgery (CSRF)

Slide 68

Slide 68 text

Request Forgery Discount link via e-mail Credentials /cancel-ticket/123 App User Attacker ??? Profit

Slide 69

Slide 69 text

Examples ‣ Fake form that leads to destructive action. ‣ Clickjacking.

Slide 70

Slide 70 text

CSRF Demo

Slide 71

Slide 71 text

CSRF Exercise

Slide 72

Slide 72 text

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.

Slide 73

Slide 73 text

Solutions ‣ Don't let GET have side-effects. ‣ CSRF token (nonce) - Symfony, Laravel and ZF have it. ‣ Re-authenticate for important operations.

Slide 74

Slide 74 text

9: Broken Authentication and Session Management

Slide 75

Slide 75 text

Data Interception Demo

Slide 76

Slide 76 text

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

Slide 77

Slide 77 text

Vectors ‣ URL argument. ‣ Hidden form field. ‣ Cookie.

Slide 78

Slide 78 text

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.

Slide 79

Slide 79 text

10: Security Misconfiguration

Slide 80

Slide 80 text

Vectors ‣ Default configurations. ‣ Default accounts. ‣ Outdated software (OS, server, libs, etc.) ‣ Publicly accessible code. ‣ Etc.

Slide 81

Slide 81 text

Example: MongoDB ‣ Doesn't require credentials by default. ‣ "More than 27,000 MongoDB databases seized by ransomware"
 – The Register

Slide 82

Slide 82 text

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.

Slide 83

Slide 83 text

Example: WordPress Syntax Highlighter ‣ When using outdated version:
 display any file from server, such as DB config.

Slide 84

Slide 84 text

Solutions ‣ Update software & libraries on time. ‣ Turn off debug mode. ‣ Change default passwords. ‣ Tune security settings. ‣ Automated config check. ‣ Secure architecture. ‣ Continuous hardening process.

Slide 85

Slide 85 text

curl
 -H "Accept: text/plain"
 https://security.sensiolabs.org/check_lock
 -F lock=@./composer.lock

Slide 86

Slide 86 text

11: XML External Entities (XXE)

Slide 87

Slide 87 text

]> &lol9;

Slide 88

Slide 88 text

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

Slide 89

Slide 89 text

Slide 90

Slide 90 text

XXE Injection Demo

Slide 91

Slide 91 text

Attack Examples ‣ Inject malicious content. ‣ Read from the filesystem. ‣ Probe internal network (https:/ /192.168.1.1). ‣ DoS (file:/ / /dev/random)

Slide 92

Slide 92 text

Solutions ‣ Use JSON if possible. ‣ Validate/sanitize input. ‣ Update your XML libs. ‣ Disable XML external entity and DTD processing.

Slide 93

Slide 93 text

12: Insecure Deserialization

Slide 94

Slide 94 text

Insecure Deserialization Demo

Slide 95

Slide 95 text

Insecure Deserialization Exercise

Slide 96

Slide 96 text

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

Slide 97

Slide 97 text

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

Slide 98

Slide 98 text

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.

Slide 99

Slide 99 text

13: Insufficient
 Logging & Monitoring

Slide 100

Slide 100 text

In 2016, identifying a breach took an average of 191 days

Slide 101

Slide 101 text

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.

Slide 102

Slide 102 text

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.

Slide 103

Slide 103 text

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.

Slide 104

Slide 104 text

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.

Slide 105

Slide 105 text

Slide 106

Slide 106 text

Avoid Discovering Them in Prod ‣ Code reviews. ‣ Penetration testing. ‣ Follow security news, mailing lists, Twitter, etc. ‣ Threat modeling.

Slide 107

Slide 107 text

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

Slide 108

Slide 108 text

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.

Slide 109

Slide 109 text

Threat Modeling

Slide 110

Slide 110 text

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.

Slide 111

Slide 111 text

1 – Assessment Scope: Identify Assets ‣ DB ‣ Sensitive files ‣ Reputation ‣ Customer base ‣ Employee relations ‣ Etc.

Slide 112

Slide 112 text

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.

Slide 113

Slide 113 text

3 – Understand Existing Countermeasures ‣ Eliminate. ‣ Prevent. ‣ Minimize the harm.

Slide 114

Slide 114 text

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.

Slide 115

Slide 115 text

4 – Identify Exploitable Vulnerabilities ‣ Search for vulnerabilities that connect the possible attacks to the negative consequences. Loss of confidentiality Plaintext CC numbers

Slide 116

Slide 116 text

5 – Prioritized Identified Risks ‣ Risk = likelihood & impact. ‣ Likelihood: medium. ‣ Impact: high. ‣ Risk: high.

Slide 117

Slide 117 text

6 – Identify Countermeasures To Reduce Threat ‣ Reduce the risk to acceptable levels. ‣ Example: bind SQL parameters.

Slide 118

Slide 118 text

Risk Rating Methodology: Audience Participation

Slide 119

Slide 119 text

1 – Identifying a Risk ‣ Assets. ‣ Threat agents & attacks. ‣ Existing countermeasures. ‣ Exploitable vulnerabilities. ‣ Rate & prioritize. ‣ Countermeasures to reduce threat.

Slide 120

Slide 120 text

2 – Likelihood ‣ Threat agent factors: • Skill level • Motive • Opportunity • Size

Slide 121

Slide 121 text

2 – Likelihood ‣ Vulnerability factors • Ease of discovery • Ease of exploit • Awareness • Intrusion detection

Slide 122

Slide 122 text

3 - Impact ‣ Technical impact factors • Loss of confidentiality • Loss of integrity • Loss of availability • Loss of accountability

Slide 123

Slide 123 text

3 - Impact ‣ Business impact factors • Financial damage • Reputation damage • Non-compliance • Privacy violation

Slide 124

Slide 124 text

4 – Overall Risk Severity Likelihood Low Medium High Impact Low Note Low Medium Medium Low Medium High High Medium High Crijcal

Slide 125

Slide 125 text

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.

Slide 126

Slide 126 text

6 – Customize Your Risk Rating Model ‣ Add factors. ‣ Customize options. ‣ Weigh factors.

Slide 127

Slide 127 text

Resources ‣ https:/ /www.owasp.org/index.php/OWASP_Risk_Rating_Methodology ‣ https:/ /www.owasp.org/index.php/Top_10_2017-Top_10

Slide 128

Slide 128 text

THANKS! @afilina