Más contenido relacionado La actualidad más candente (20) Similar a Edge 2016 service workers and other front end techniques (20) Edge 2016 service workers and other front end techniques1. © AKAMAI - EDGE 2016
Creating a Secure and Optimal Site
with Service Workers and Other Front-end Techniques
2. © AKAMAI - EDGE 2016
Source: Cisco VNI, 2015
Scale
Performance
3. © AKAMAI - EDGE 2016
DDoS
Financial Fraud
Data Harvest
SEO Poisoning
Spamming
Security
Scale
4. © AKAMAI - EDGE 2016
3rd Party Popularity
Average number of embedded page
objects from Alexa’s Top 100
1st party resources: 48
3rd party resources: 62
5. © AKAMAI - EDGE 2016
<iframe> & Content-Security-Policy
6. © AKAMAI - EDGE 2016
What Are Sites Using Now?
From Alexa’s Top 100 domains
65% of sites use <iframe>
2% of sites use Content-Security-Policy header
7. © AKAMAI - EDGE 2016
Why? ….. 3rd Party Vulnerabilities
• Single-Point-of-Failure
• Compromised content
8. © AKAMAI - EDGE 2016
Headlines 2015-2016
Vendor Related Breaches:
• Walmart Canada looks into possible credit card data breach
• CVS probes card breach at online photo unit
• Expedia, Travelocity, Hotels.com warn customers of phishing scam
Ad Network Related Breaches:
• Hackers hit Google AdWords and Adsense networks
• DoubleClick ad fraud campaign lures victims with promise of adult videos
• 1 million machines hacked for AdSense revenue in Click Fraud attacks
9. © AKAMAI - EDGE 2016
<script src="http://3rdparty.com/object.js"></script>
10. © AKAMAI - EDGE 2016
How can <iframe> or Content-Security-Policy
help?
11. © AKAMAI - EDGE 2016
<script> vs <iframe>
<script type="text/javascript">
var myIframe=document.createElement("IFRAME");
myIframe.src="about:blank";
myIframe.addEventListener('load',
function (e) {
var myElement=document.createElement("SCRIPT");
myElement.type="text/javascript";
myElement.src=" http://3rdparty.com/object.js";
myIframe.contentDocument.body.appendChild(myElement);
}, false);
document.body.appendChild(myIframe);
</script>
Security: Limited access to site content Performance: No Single-Point-of-Failure
12. © AKAMAI - EDGE 2016
<script> with Content-Security-Policy
<script src="http://3rdparty.example.com/object.js"></script>
Content-Security-Policy: default-src 'self' ; img-src 'self'
https://*.google.com ; script-src 'self' http://www.google-
analytics.com 'unsafe-inline’ http://*gstatic.com ; style-src 'self'
https://fonts.googleapis.com ; font-src 'self'
https://themes.googleusercontent.com ; frame-src 'self'
http://3rdparty.com
Prevent Single-Point-Of-Failure with unknown 3rd parties
13. © AKAMAI - EDGE 2016
Performance Comparison: Single-Point-of-Failure
14. © AKAMAI - EDGE 2016
How Can We Enhance
Security?
15. © AKAMAI - EDGE 2016
<iframe>: sandbox
Original HTML
<script src="http://3rdparty.com/object.js"></script>
Modified HTML
<iframe src="http://3rdparty.com/object.html" sandbox></iframe>
<iframe src="http://3rdparty.com/object.html" sandbox="allow-
scripts"></iframe>
allow-forms allow-modals allow-orientation-lock allow-pointer-lock allow-popups
allow-popups-to-escape-sandbox allow-same-origin allow-scripts allow-top-
navigation
16. © AKAMAI - EDGE 2016
Content-Security-Policy: sandbox
Content-Security-Policy:
default-src 'self' ;
img-src 'self' https://*.google.com ;
script-src 'self' http://www.google-analytics.com 'unsafe-
inline’ http://*gstatic.com ;
style-src 'self' https://fonts.googleapis.com ;
font-src 'self' https://themes.googleusercontent.com ;
frame-src 'self' http://3rdparty.com
sandbox ‘allow-scripts’;
allow-forms allow-modals allow-orientation-lock allow-
pointer-lock allow-popups allow-popups-to-escape-sandbox
allow-same-origin allow-scripts allow-top-navigation
17. © AKAMAI - EDGE 2016
Inline Code Considerations
Original HTML: Sample Analytics Code
<script type="text/javascript">
var _comscore = _comscore || [];
_comscore.push({ c1: "2", c2: "3005660" });
(function () {
var s = document.createElement("script"), el =
document.getElementsByTagName("script")[0]; s.async = true;
s.src = (document.location.protocol ==
"https://sb.scorecardresearch.com/beacon.js";
el.push.parentNode.insertBefore(s, el );
})();
</script>
18. © AKAMAI - EDGE 2016
<iframe>: srcdoc
Modified HTML: Sample Analytics Code
<iframe srcdoc=
'<script> var _comscore = _comscore || [];
_comscore.push({ c1: "2", c2: "3005660" });
(function () {
var s = document.createElement("script"), el =
document.getElementsByTagName("script")[0]; s.async = true;
s.src = (document.location.protocol == "https:" ? "https://sb" :
"http://b" ) + ".scorecardresearch.com/beacon.js";
el.push.parentNode.insertBefore(s, el );
})();</script>'
sandbox= "allow-scripts"
</iframe>
19. © AKAMAI - EDGE 2016
User Session Considerations
Result
• Referer:
https://firstparty.com/sabrina.burney.3?ut=3856&pt=1209&name=sabrinaburney
• Information Leakage
Navigate
Login
Load 3rd party resource
20. © AKAMAI - EDGE 2016
<iframe>: referrerpolicy
Original HTML
<script src="http://3rdparty.com/object.js"></script>
Modified HTML
<iframe src="http://3rdparty.com/object.js" referrerpolicy="no-
referrer"></iframe>
no-referrer no-referrer-when-downgrade origin origin-when-
cross-origin unsafe-url
21. © AKAMAI - EDGE 2016
Content-Security-Policy: referrer
Content-Security-Policy:
default-src 'self' ;
img-src 'self' https://*.google.com ;
script-src 'self' http://www.google-analytics.com 'unsafe-
inline’ http://*gstatic.com ;
style-src 'self' https://fonts.googleapis.com ;
font-src 'self' https://themes.googleusercontent.com ;
frame-src 'self' http://3rdparty.com ;
referrer origin ;
no-referrer no-referrer-when-downgrade origin origin-when-
cross-origin unsafe-url
22. © AKAMAI - EDGE 2016
<iframe> & CSP: Secure and Optimal for
3rd Party Content
23. © AKAMAI - EDGE 2016
How Can Akamai Help?
• Add Content-Security-Policy headers through Property Manager
• Front End Optimization techniques that leverage iframes
25. © AKAMAI - EDGE 2016
What is a Service Worker?
Browser Network
Service Worker
• Event Driven Architecture
• Installation Events (install, activate) vs. Functional Events (fetch, push,
sync)
• It’s just JavaScript!
• Shared Worker that sits at the Browser
26. © AKAMAI - EDGE 2016
Service Worker Gotchas!
HTTPs
Not supported on all browsers
Browser can terminate Service Worker at
any time
No DOM Access
No sync xhr/local storage supported
No Global State
No Credentials/Non CORS fails By Default
Fetch events limited to scope and no fetch
events for iframes, service workers,
requests triggered within service workers
27. © AKAMAI - EDGE 2016
Service Workers: 3rd Party Content Control
28. © AKAMAI - EDGE 2016
Client Reputation
• Typically, Client Reputation Strategies are Backend
• Leverage Service Workers to control third party content based on specified
criteria to improve performance and security
Browser Network
Page Service Worker
Intercept Incoming Resource Requests
Block Network Requests based on list/thresholds for metrics
Expand to an Adaptive Reputation Strategy…
29. © AKAMAI - EDGE 2016
Service Worker Reputation Implementation: Register
Register Event
<head>
<script>
if ('serviceworker' in navigator) {
navigator.serviceWorker.register('./sb-service-worker.js').then(
function(registration) {
console.log('ServiceWorker registration successful:', registration.scope);
}).catch(function(err) {
console.log('ServiceWorker registration failed: ' , err);
});
}
</script>
</head>
30. © AKAMAI - EDGE 2016
Service Worker Reputation Implementation: Initialize
Install Event
self.addEventListener('install', function(event) {
self.skipWaiting();
});
Activate Event
self.addEventListener('activate', function(event) {
if (self.clients && clients.claim) {
clients.claim();
}
var policyRequest = new Request('thirdparty_urls.txt');
fetch(policyRequest).then(function(response) {
return response.text().then(function(text) {
thirdparty_urls_result=text.toString();
});
});
});
31. © AKAMAI - EDGE 2016
Service Worker Reputation Implementation: The Fetch
Pseudocode
self.onfetch = function(event) {
event.respondWith(
// Retrieve list of acceptable third party domains from remote txt database
if request URL has domain that matches ones in list
Retrieve current counter value
if (counter > threshold)
-Serve object from cache
-Serve alternate response
else if (counter <= threshold)
-Time resource delivery
-Update counter if object is delayed
-Add object to cache
else request URL not under scope, serve request as is
);
};
32. © AKAMAI - EDGE 2016
Service Worker Reputation Implementation: Fetch Details (cont)
Fetch Event
self.addEventListener('fetch', function(event) {
if (hostname.test(thirdparty_urls_result)) {
getCounter(…, rspFcn);
var rspFcn = function (event){
//If counter exceeded, retrieve from cache or serve 408
if (counter_flag > 0) {
caches.open('sabrina_cache').then(function(cache) {
var cachedResponse = cache.match(event.request.url).then(function(response) {
if (response) {
console.log("Found response in cache");
return response;
}
else {
console.log("Response not found in cache");
return (new Response('', {status: 408,statusText: 'Request timed out.'}));
}
}).catch(function() {
return (new Response('', {status: 408,statusText: 'Request timed out due to error.'}));
});
event.respondWith(cachedResponse);
});
}
33. © AKAMAI - EDGE 2016
Service Worker Reputation Implementation: Fetch Details (cont)
else {
Promise.race([timeout(delay), fetch(event.request.url, {mode: 'no-cors'})]).then(function(value){
if (value=="timeout"){
console.log("Timeout threshold reached, update counter");
updateCounter(…); //Use promise to update counter after asset download
}
else {
//If counter not exceeded (normal request), then add to cache
console.log("Timeout threshold not reached, retrieve request without updating counter");
caches.open('sabrina_cache').then(function(cache) {
console.log("Adding to cache");
cache.add(event.request.url);
}).catch(function(error) {
console.error("Error" + error);
throw error;
});
}
});}
};}
else {
//If current asset is not under scope for solution, serve resource as is
event.respondWith(fetch(event.request));
}});
34. © AKAMAI - EDGE 2016
Real Work Application: Sample Scenario
• Resource in Scope
<script src="https://resources.projectwikiwiki.com/serviceworkers/js/jquery.js"></script>
• Counter Threshold
Allow resource to be slow 3 times in a 5 minute period before taking alternate action
• Timeout Threshold
Update counter if resource takes longer than 5 seconds to download in browser
• Rolling Penalty Window
Configure solution to maintain counter value for a 5 minute period. Continuous resource delays will reset the
penalty window.
• Alternate action for slow response
Serve locally cached version of object -or- serve 408 error response
35. © AKAMAI - EDGE 2016
On First Load
thirdparty_urls.txt
ajax.googleapis.com
resources.projectwikiwiki.com
convertmyimage.com
static.tumblr.com
hitleap.com
Conditions:
• Service Worker registered
• Service Worker activate event triggered
36. © AKAMAI - EDGE 2016
On Next Load: Add to Cache
<script
src="https://resources.projectwikiwiki.com
/serviceworkers/js/jquery.js"></script>
Time < 5 seconds
Counter < 3
Conditions:
• Timeout threshold not exceeded
• Counter threshold not exceeded
37. © AKAMAI - EDGE 2016
On Next Load: Timeout Exceeded
Time > 5 seconds
Counter < 3
Conditions:
• Timeout threshold exceeded
• Counter threshold not exceeded
38. © AKAMAI - EDGE 2016
On Next Load: Counter Exceeded
Load locally cached version of resource
…Page loads much faster
39. © AKAMAI - EDGE 2016
On Next Load: Counter Exceeded
…Serve alternate error response defined in Service Worker
Resource not available in cache
40. © AKAMAI - EDGE 2016
Immediate Results: 5 minute period
• Improved DOMContentLoaded
time
• Improved end user
experience
• Avoid continuous Single-
Point-of-Failure
Counter exceeded
41. © AKAMAI - EDGE 2016
How Can Akamai Help?
Register Service Worker
• Edge Akamaizer on base page
• Host SW.js on Netstorage
Install/Activate Service Worker
• Host thirdparty_urls.txt on
Netstorage
Datastore Capabilities
• Maintain counter value per
scoped resource
Configuration Capabilities
• Define penalty window time
• Define counter threshold
Service Worker Alternate Action
• Block network requests based on
predefined list of domains
• Serve alternate static content
• Serve content from local browser
cache if available
• Simply monitor third party
performance
42. © AKAMAI - EDGE 2016
Service Workers: Analytics Monitoring
43. © AKAMAI - EDGE 2016
Third Party Analytics Monitoring
44. © AKAMAI - EDGE 2016
What do third party analytics tools have to do with
Service Workers?
46. © AKAMAI - EDGE 2016
Tracking Metrics with Service Workers
navigator.connect to track metrics both online and offline
self.addEventListener('activate', function(event) {
event.waitUntil(
navigator.services.connect('https://thirdparty.com/services/analytics',
{name: 'analytics'}));
});
self.addEventListener('fetch', function(event) {
navigator.services.match({name: 'analytics'}).then(
port.postMessage('log fetch'));
});
…Where does performance and security come in?
• Less client side JavaScript logic
• After Service Worker is installed, no need for browser to re-parse analytics reporting code
• Reduce risk of script injection (no DOM access)
• Asynchronous metric reporting (non blocking)
• Avoid SPOF
• User Agent can terminate the Service Worker at ANY time
47. © AKAMAI - EDGE 2016
Why don’t popular analytics tools leverage
Service Workers?
48. © AKAMAI - EDGE 2016
Other Service Worker Applications
• Input Validation
• Geo Content Control with the Geofencing API
• Load Balancing
• Switching off between multiple server URLs
• Dependency Injector
• Distinguishing production versus staging or production versus a fallback
49. © AKAMAI - EDGE 2016
A Performance Solution Can Be A Security Solution!
• Bridge the gap
• First Party Attackers & Third Party Attackers
• Explore Service Worker Applications
Questions?
@soniaburney @sabrina_burney