HTML 5 Security
HTML 5 Security
HTML 5 Security
Philippe De Ryck
philippe.deryck@cs.kuleuven.be
DistriNet
Fast Evolution of the Web
Extension of client-side platform
HTML5 brings a lot of new features
• Media elements, extended forms, custom
handlers, offline applications …
Communication between browsing contexts
Cross-origin communication
DistriNet
Several APIs offer client-side storage
Access to system / device properties
Fast (In)Security of the Web?
Exciting new extensions
Potentially very security-sensitive operations
• (Location) Tracking, stealing local data, …
• Example: Accelerometer keyloggers
Covered by numerous separate specs
• Potential cross-spec issues/inconsistencies
DistriNet
Specs aim to be secure-by-design
But are they?
Security Analysis of Web Standards
DistriNet 4
Analysis of the specifications
A Security Analysis of Next
Generation Web Standards
Commissioned by European Network and
Information Security Agency (ENISA)
Performed by DistriNet Research Group
DistriNet
http://www.enisa.europa.eu/html5
5
W3C specifications in scope
HTML 5 specification Media
Cross-domain Media Capture API
communication Client-side storage
XML Http Request levels 1 Web Storage
and 2 Device access
Uniform Messaging Policy
Geolocation API
Cross-Origin Resource Specification
Sharing
System Information API
Inter-window Permissions for Device API
DistriNet
communication Access
HTML5 Web Messaging Device API Privacy
Requirements
6
Methodology
Iterative and repeatable process
Applied to 13 specifications in scope
1000+ pages of specification!
Analysis driven by four security questions
Results were captured in three steps
Specification summary
DistriNet
Analysis result of specification in isolation
Cross-specification analysis results
7
Scope
Focus on newly introduced features
No specific focus for classic issues
• E.g. XSS vectors, session management
• Included when relevant for new features
Already extensive work
on XSS attack vectors
• See html5sec.org
DistriNet 8
Four security questions
SQ1: Are the security-relevant aspects of the newly introduced
capabilities well-defined and secure?
privacy problems, unprotected features, …
DistriNet
SQ4: How do the security measures of the specification rely on
the user making correct security decisions?
which decisions does the user have to make
9
3-step analysis
Step 1: Security-focused study of the specification in
isolation:
Capabilities: enlisting functional capabilities offered by the spec
User Involvement: how and when is the user involved in
granting access
Security/privacy considerations: both explicit and implicit
considerations
DistriNet
Step 3: identification of cross-specification issues:
Inconsistencies between the specifications
Interaction of features across specifications
10
Analysis results
Well-defined / Isolation User
Consistency
Secure Properties Involvement
HTML5 8 3 2 2
Web Messaging 1 2
XMLHttpRequest 1 + 2 1
CORS 2 1
UMP
Web Storage 3 1 1
Geolocation API 5 1 1 1
Media Capture API 3
System Information API 3 1 1 2
DistriNet
Widgets - Digital Signatures 2
Widgets - Access Req Policy 3 1
Total 25 8 10 8
11
Key Observations
Overall, specs are secure-by-design
Security of legacy applications
Generally well maintained
Corner cases violate legacy security
Underspecified behavior
Spec is too open, too vague
DistriNet
Allows diverging and insecure
implementations
12
Key Observations
Restricted contexts
Sandboxed document / Private Browsing
Specifications do not account for this
Permission systems
Several specifications use permissions
Multiple different permission systems
DistriNet
Heavily dependent on user for security
13
Conclusion
Tons of new features will become available
to third-party JavaScript
Analysis results
Overal quality of the specification is quite OK
Limited number of threats identified
Lack consistency in permission management,
user consent
Underspecification in restricted contexts
DistriNet
Only coarse-grained control over available
APIs
14
Next steps
Follow up on issues and new spec
developments at W3C and on mailinglists
Translate knowledge in security
guidelines for developers and website
owners
Evaluating the browser compliance
DistriNet
towards the specifications
15
More info…
A Security Analysis of Next
Generation Web Standards
DistriNet
http://www.enisa.europa.eu/html5
16
HTML5 Security Up Close
DistriNet 17
Goals of this session
Glimpse of upcoming HTML5 technology
Newly available client-side functionality
Learn how they work
Understand the security consequences
Best practices / Security guidelines
Both for new and existing applications
DistriNet
Newly proposed security features
Learn how to protect your site
18
Overview of Technologies
Security Policies
(CSP, Do-Not-Track, X-Frame-Options)
Sandbox
(HTML5) Client-side Storage
Client-side Communication
Window (Web Storage, IndexedDB,
(Web Messaging)
Web SQL database, File API)
Forms
(HTML5)
Media Content Sensor APIs
(Media Capture API) Media Content
(HTML5, HTML Media (Sysinfo API, Geolocation, …)
Capture)
DistriNet
Client/Server Communication
(CORS, UMP, XHR 1+2)
19
On the menu …
Basic Web Security Concepts
HTML5 Forms
Cross-origin Communication
Messaging between Contexts
Storage APIs
Content Security Policy
HTML5 Sandboxing
DistriNet
X-Frame Options
20
Basic Web Security Concepts
Recommended read: “The Tangled Web”
Same Origin Policy
Isolates content from different origins within
the browser
Cornerstone for script security
Can differ based on type of access/content
DistriNet
• E.g. Scripts are included within context of
document that includes it
21
Basic Web Security Concepts
Origin A Origin C
DistriNet 22
Basic Web Security Concepts
Script inclusion
Scripts become part of including document
Script tags are directly executed
• Access to parsed data (e.g. vars or functions)
• No access to source
Example to circumvent: JSONP
DistriNet
• Request JSON data with function call
• Server responds with data
23
Notation Style
Best Practices / Security Guidelines
…
Level of support in Browsers
Well to Fully supported
Marginally supported
Not supported
Not supported and no intention to do so
DistriNet
Browser versions: Firefox 10, Chrome 16, Opera 11.61, Safari
5.1, Internet Explorer 9, Internet Explorer 8 (max version for Windows XP)
29/02/2012 24
Forms
DistriNet
25
New Form Functionality
New Form Controls
Mainly input / visualization elements
Security-relevant: keygen
Client-side Form Validation
Out-of-band Form Controls
Place form elements anywhere
DistriNet
Modify form’s properties with attributes
26
Form Controls - keygen
Generates public/private key pair
Public key is submitted, private key is stored
Use case: create client-side certs
<keygen name=“key” keytype=“rsa” />
DistriNet
Install cert Multipart page (key and HTML)
in browser
27
Form Controls - keygen
Advantages
Useful as additional authentication
Better protection against stealing/phishing
Disadvantages
Stored in browser (not directly accessible)
Does not prevent browser-based attacks
DistriNet
Management issues
Limited support (mainly Firefox)
28
Form Validation
Client-side validation of form elements
Predefined patterns
Custom checks and messages
Triggered by submission or checkValidity()
Overridden by novalidate
Useful to avoid roundtrip to server
DistriNet
Especially on slower networks (e.g. mobile)
29
Form Validation – Predefined patterns
Traditional input types
hidden, text, password, checkbox, radio, file, submit
New input types
search, tel, url, email, datetime, date, month, week,
time, datetime-local, number, range, color
<input type=“month” name=“month” />
DistriNet
<input type=“color” name=“background” />
30
Form Validation – Required/Patterns
Default validation attributes
Required: element must contain a value
Pattern: element must match a regex pattern
Example: Belgian zip codes
<input type=“text” name=“zip”
pattern=“B-[0-9]{4}” required />
DistriNet 31
Form Validation - Custom
Custom validation
Trigger custom validation method
Set custom validation message
<input type=“text” name=“myCustom”
oninput=“validate(this)” required />
function validate(input) {
if(…) {
input.setCustomValidity(“ … custom message … ”);
DistriNet
}
}
32
Form Validation
Client-side Validation
Useful to improve user experience
More efficient than round-trip to server
Easily circumvented by malicious user
DistriNet 33
Out-of-band Form Controls
Form elements anywhere in the page
Associated with a form
• Nearest form or form attribute
Supports valid nesting of forms
<form id=“myform” action=“basic.php” >
…
</form>
DistriNet
<input type=“submit” form=“myform” name=“stray”
value=“Guess What I do?” />
34
Behavior Modifying Attributes
Attributes can modify form behavior
Only applies to submission controls
Change action, enctype, method,
novalidate and target
<form action=“basic.php” >
…
<input type=“submit” name=“…” value=“Basic Version” />
DistriNet
<input type=“submit” name=“…”
value=“Advanced Version” formaction=“advanced.php”/>
</form>
35
Injected Form Controls
Attacker can confuse the user
Inject submission control
Change form destination
<form id=“login” action=“basic.php” >
…
<input type=“submit” name=“…” value=“Home Bank” />
</form>
DistriNet
<input type=“submit” form=“login” name=“steal”
value=“Try out the new version!”
formaction=“http://…/steal.php” />
36
Out-of-band Form Controls
Can be used to change form destination
User still needs to click the button
No scripts needed
Solution: appropriate filtering
DistriNet
Prevent injection of form attributes
37
Browser Support
Form Out-of-band
Keygen
Validation Form Controls
Firefox
Chrome
Opera
Safari
IE
DistriNet
IE (XP)
38
Cross-Origin Communication
DistriNet 39
Cross-Origin Communication
Only possible by means of hacks
Proxy in same origin as host page
Script inclusion (e.g. JSONP)
XMLHttpRequest Level 2
By-design solution for cross-origin comm.
DistriNet
Cross-Origin Resource Sharing
Uniform Messaging Policy
40
XMLHttpRequest Level 1
JavaScript HTTP API
Synchronous and asynchronous
Restricted to same origin as host page
xhr.onreadystatechange = function() { … }
DistriNet
xhr.open(“GET”, “updates.php” );
xhr.send();
41
XMLHttpRequest Level 2
JavaScript HTTP API
Synchronous and asynchronous
Offers cross-origin and anonymous requests
var xhr = new XMLHttpRequest();
var anon = new AnonXMLHttpRequest();
DistriNet
Carefully designed API
42
Cross-Origin Resource Sharing
Cross-origin requests
Client provides (trustworthy) origin
• Request header: Origin
Server provides authorization information
• Additional response headers
Client (browser) enforces rules
DistriNet
• Grant/deny access to response
43
Cross-Origin Resource Sharing
Simple request
Send to server with Origin header
Process response headers
• Access-Control-Allow-Origin
• Access-Control-Allow-Credentials
• Access-Control-Allow-Expose-Headers
Wildcard allowed for ACAO
DistriNet
• Not if credentials are used
44
Cross-Origin Resource Sharing
Cross-origin XHR request
GET two.com
Origin: http://one.com
DistriNet
Response
45
Cross-Origin Resource Sharing
Security Goal
Do not give an attacker more capabilities than he
has with traditional HTML and JS APIs
DistriNet
Client will not give script access to response
Same capabilities as with img element
46
Cross-Origin Resource Sharing
Security Goal
Do not give an attacker more capabilities than he
has with traditional HTML and JS APIs
DistriNet
API addresses this with preflight requests
47
Cross-Origin Resource Sharing
Complex request
Send preflight before making actual request
Server responds with CORS headers
Client processes headers
• If server allows request: send actual request
• Else: do not send actual request
DistriNet
Preflights maintain security goal
48
Cross-Origin Resource Sharing
Preflight request
Send OPTIONS request to server
• Origin
• Access-Control-Request-Method
• Access-Control-Request-Headers
Process response headers
• Access-Control-Allow-Origin
• Access-Control-Allow-Credentials
• Access-Control-Allow-Expose-Headers
DistriNet
• Access-Control-Allow-Max-Age
• Access-Control-Allow-Methods
• Access-Control-Allow-Headers
49
Cross-Origin Resource Sharing
Cross-origin preflight XHR request
OPTIONS two.com
Origin: http://one.com
Access-Control-Request-Method: PUT
Response
DistriNet
Access-Control-Allow-Origin: http://one.com
50
Cross-Origin Resource Sharing
Cross-origin preflight XHR request
OPTIONS two.com
Origin: http://one.com
Access-Control-Request-Method: PUT
DistriNet 51
Cross-Origin Resource Sharing
Denied simple requests
Server knows that access will be denied
Processing request is useless / dangerous
DistriNet
response without any CORS headers
52
Cross-Origin Resource Sharing
Spec proposes some server-side policies
Do not allow access to resources that are not
useful to other applications
• Example: login pages
Publicly accessible resources can always allow
access (using the wildcard *)
DistriNet
• Example: images, …
53
Cross-Origin Resource Sharing
Spec proposes some server-side policies
Responses that parse as JavaScript and do not
contain sensitive comments can always allow
access (using the wildcard *)
DistriNet
• Currently, a cross-origin redirect adds an origin to
the Origin header
54
Cross-Origin Resource Sharing
Origin header can have value null
Occurrence: sandboxed context and
proposed for cross-origin redirect
All the CORS algorithms still work with null!
• Use of credentials is allowed
• Server has no origin information
• Pages can always sandbox themselves
DistriNet
Do NOT allow a null value in the Origin header
55
CORS Usage
Other CORS use cases besides XHR
Canvas tainting (HTML5)
• Load cross-origin images without tainting
Media elements metadata (HTML5)
• Access metadata on cross-origin videos
Server-sent events
DistriNet
• Allow cross-origin access to event stream
56
Uniform Messaging Policy
Only uniform requests/responses
No credentials/cookies/referer/origin
If needed, use other authentication or
authorization system (e.g. oAuth)
Access to response is granted by Access-
Control-Allow-Origin: * header
DistriNet
Do not use for non-publicly available
resources
57
Browser Support
XMLHttpRequest
CORS UMP
Level 1 Level 2
Firefox
Chrome
Opera
Safari
IE
DistriNet
IE (XP)
58
Legacy Applications
XHR Level 1 was same origin
Legacy apps never made CORS requests
But now they can, so how about your app …
Ask Facebook
• Facebook Touch used fragment to specify page
• Uses XHR to load that page into the DOM
DistriNet
• Code accepted any URL
Do not depend on implicit same-origin rules for
security (but check your destination domain)
59
Facebook XHR Vulnerabiltiy
Loading content with AJAX
touch.facebook.com/#profile.php
DistriNet
Attacker now fully controls the user’s
Facebook session
60
Messaging between Contexts
DistriNet 61
Messaging Between Contexts
Isolation is a good security technique
Same Origin Policy applies
Components require interaction
Web Messaging
Supports sending single messages
Supports establishing a message channel
DistriNet
• Based on port objects
• Follows the object-capability security model
62
Web Messaging – Single Message
Send message to other browsing context
Sender: method of destination window
• Provides message + destination origin + objects
Receiver: event handler on window object
• Receives message + origin information
Origin A Origin B
DistriNet
windowB.postMessage(“some message”, “http://originB”)
63
Web Messaging – Single Message
function receiver(e) {
if (e.origin == 'http://example.com') {
…
}
}
window.addEventListener('message', receiver, false);
var f = document.getElementById("myframe");
f.contentWindow.postMessage('Hello world',
'http://b.example.org/');
DistriNet
Check sender origin before accepting message
64
Web Messaging – Message Channel
Construct channel between two contexts
Two tangled ports, one for each context
• Follows the object-capability model
p1
Origin A Origin B
p2
DistriNet
p1
Origin A Origin B
p2 p2
p1.postMessage(“some message”)
65
Web Messaging – Message Channel
Game wants to add contact to address book
capability
With permission of social site
passing around capability
DistriNet
p1
p2
66
Web Messaging – Message Channel
Game wants to add contact to address book
capability
With permission of social site
passing around capability
DistriNet
p1
p2
67
Web Messaging – Message Channel
Game wants to add contact to address book
capability
With permission of social site
passing around capability
DistriNet
p2 p1
p2
68
Web Messaging – Message Channel
var channel = new MessageChannel();
parent.frames[1].postMessage(“port”,
'http://b.example.org/„,
[channel.port2]);
function receiver(e) { … }
channel.port1.onmessage = receiver;
channel.port1.postMessage(“Hello!”);
DistriNet 69
Web Messaging
DistriNet
Messages contain no origin information
70
Web Messaging in a Sandbox
HTML5 Sandbox
Supports unique origins
Source origin of messages: null
• Any origin can send these messages
DistriNet
Check explicitly for a null source origin
71
Browser Support
Single Message
Message Channel
Firefox
Chrome
Opera
Safari
IE
DistriNet
IE (XP)
72
Storage APIs
DistriNet
73
Storage APIs
All techniques have similar properties
JavaScript API
Limited amount of storage
• If supported, user can enlarge the quota
Storage techniques
Simple key/value pairs (Web Storage)
Advanced key-based (Indexed DB)
DistriNet
Client-side SQL (Web SQL DB)
Local file (File API)
74
Storage APIs – Web Storage
Simple key-based storage
Window.localStorage.setItem(“key”, “value”);
Window.localStorage.getItem(“key”);
DistriNet
context/origin pair
75
Storage APIs – Web Storage
Local
Storage
Session
Storage
DistriNet 76
Storage APIs – Indexed DB
Advanced key-based storage
Databases based on keys
• Key-based storage and retrieval (no SQL)
• Support for indexing, looping, in-order retrieval …
One storage area per origin
• Can contain multiple databases
Extensive API
DistriNet
• Asynchronous operations for normal use
• Synchronous API available for use in workers
77
Storage APIs – Indexed DB
// Create new object stores
var osNotes = DB.db.createObjectStore(
DB.ObjectStores.notes, {
keyPath: "id", autoIncrement: true
});
DistriNet
var rq = index.get(name);
rq.onsuccess = function(e) {
callback(e.target.result);
}
78
Client-side Storage – Web SQL
Client-side SQL storage
Extensive SQL support
• Including transactions and rollback
One storage area per origin
• Can contain multiple databases
Extensive API:
DistriNet
• Asynchronous operations for normal use
• Synchronous API available for use in workers
79
Storage APIs – Web SQL
// Create new database
t.executeSql('CREATE TABLE IF NOT EXISTS notes
(…)', [], function(e) { /* success */ },
function(e) { /* error */ } );
// Insert a note
var args = [note.name, note.user.id];
t.executeSql('INSERT INTO notes (name, userId)
VALUES (?, ?)', args,
function(t, r) { /* success */ },
DistriNet
function(e) { /* error */ });
80
Storage APIs – File API
Local File Access
Read/write user selected files
Use a virtual file system
• Support for temporary or permanent FS
• One FS per origin (one of each type)
Extensive API
DistriNet
• Asynchronous operations for normal use
• Synchronous API available for use in workers
81
Storage APIs – File API
// Create new filesystem
requestFileSystem(0, 1024 * 1024,
function(fs) { /* success */ });
DistriNet 82
Storage APIs – Security Considerations
Access is bound to origin
Beware of included scripts
(e.g. advertisements, maps, …)
Do not use storage on shared hosting
(i.e. multiple sites within same origin)
DistriNet
Carefully think about sensitivity of stored data
83
Storage APIs – Browser Support
Firefox
Chrome
Opera
Safari
DistriNet
IE
IE (XP)
84
Content Security Policy
DistriNet 85
Content Security Policy
Prevent potential injection attacks
XSS, Content injection (images, …)
Not the primary line of defense
Policy defines sources of content
• Scripts, images, fonts, stylesheets, …
Currently being developed as a W3C spec
DistriNet 86
Content Security Policy
Policy Directives
script-src: allowed script sources
object-src: allowed object sources
img-src: allowed image sources (html, css)
media-src: allowed media sources
style-src: allowed CSS sources
frame-src: allowed sources for child frames
font-src: allowed font sources (CSS)
DistriNet
connect-src: allowed remote destinations
default-src: allowed sources for any
87
Content Security Policy
Behavioral constraints
Inline scripts are not allowed to execute
Code evaluation is disabled
Inline CSS is not applied
Constraints can be overridden if needed
Allow inline scripts or CSS: unsafe-inline
DistriNet
Allow code evaluation: unsafe-eval
88
Content Security Policy - Example
SecAppDev’s main page
Same-origin stylesheets / icons / images
Google Analytics
Inline scripts
default-src „self‟;
script-src www.google-analytics.com
DistriNet
„unsafe-inline‟;
89
Content Security Policy - Example
SecAppDev’s main page
Same-origin stylesheets / icons / images
Google Analytics
Same-origin scripts (external files)
default-src „self‟;
script-src „self‟ www.google-analytics.com ;
DistriNet
To protect against XSS, limit scripts and objects
and do not allow inline scripts
90
Content Security Policy
Policy Delivery
Value of HTTP header or meta-tag
• X-Content-Security-Policy
For large policies: refer to remote policy file
• Must be within same origin as page
• Use policy-uri directive
DistriNet 91
Content Security Policy
Policy Deployment
Backwards compatibility
• Older browsers will ignore the policy
• No risks of breaking stuff on older sites
Dry-run before enforcing
• CSP supports a report-only mode
• All violations are reported to URI
DistriNet
• Enables debugging of policy before enforcement
92
Content Security Policy - Report
"csp-report": {
"document-uri": "http://example.org/page.html",
"referrer": "http://evil.example.com/haxor.html",
"blocked-uri": "http://evil.example.com/image.png",
"violated-directive": "default-src 'self'",
"original-policy": "default-src 'self';
report-uri http://example.org/csp-report.cgi“
DistriNet
}
93
Content Security Policy
Testimonial
Rollout on Twitter Mobile [4]
JQuery tests eval function at loading time
• Needed small fix (fixed by default in >=1.5)
Unexpected issues
• JavaScript injection/ content alteration by ISPs
DistriNet
• Fixed by requiring SSL for all users
Now: fully operational
94
Browser Support
Firefox
Chrome
Opera
Safari
IE
DistriNet
IE (XP)
95
HTML Sandbox
DistriNet
96
HTML Sandbox
Restricts functionality of framed content
Possibility to increase security
Coarse-grained options available
• All enabled by default
• Some can be relaxed with specific keywords
DistriNet
<iframe src=“http://…” sandbox></iframe>
97
HTML Sandbox
Restrictions and relaxations:
• Content has unique origin (allow-same-origin)
• Navigation limited to sandbox and descendants
• Top navigation prevented (allow-top-navigation)
• Plugins are not loaded (e.g. embed, object, …).
User agent may allow user-initiated override
• Seamless can not be used
• Form submission is prevented(allow-forms)
DistriNet
• Scripts are disabled(allow-scripts)
• Automatic features are disabled (allow-scripts)
98
HTML Sandbox
Do not enable allow-scripts and allow-
same-origin (Allows breaking out)
Allows content to break out of sandbox
DistriNet
Otherwise, loading outside of sandbox
compromises main domain
99
HTML Sandbox
Do not rely on script-based security measures
(or ensure a secure non-script mode)
Attacker can sandbox your page
Example: common clickjacking defenses
if (top!=self)
top.location.href = self.location.href
Disabled by sandboxing page
DistriNet
Use X-Frame-Options instead
100
X-Frame-Options
DistriNet
101
Clickjacking Attack
DistriNet
Clickjacking Attack
DistriNet
But actually you are
clicking here
X-Frame-Options
Restricts framing of pages
Can be used to prevent framing attacks
Header-based policy: X-Frame-Options
Values:
• DENY: no framing allowed
• SAMEORIGIN: only framing within origin
DistriNet
• ALLOW-FROM x: specify sites that are allowed
to frame this page
Browser Support
X-Frame-Options
Firefox
Chrome
Opera
Safari
IE
DistriNet
IE (XP)
105
Conclusion
DistriNet
106
HTML5 Security
Exciting developments
Huge extension of client-side functionality
High potential for application creators
• But also attractive target
Follow simple security rules
Only allow the strictly necessary features
DistriNet
Don’t trust anything
107
Thank You
You can always contact me
For further questions
With example uses of new technology
…
DistriNet 108
HTML5 Security
Philippe De Ryck
philippe.deryck@cs.kuleuven.be
DistriNet