Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / chrome / common / extensions / docs / templates / articles / contentSecurityPolicy.html
blobdaf3f7170f4d323a8cb6258c46dda1ca05f5d48d
1 <h1>Content Security Policy (CSP)</h1>
4 <p>
5 In order to mitigate a large class of potential cross-site scripting issues,
6 Chrome's extension system has incorporated the general concept of
7 <a href="http://dvcs.w3.org/hg/content-security-policy/raw-file/tip/csp-specification.dev.html">
8 <strong>Content Security Policy (CSP)</strong>
9 </a>. This introduces some fairly strict policies that will make extensions
10 more secure by default, and provides you with the ability to create and
11 enforce rules governing the types of content that can be loaded and executed
12 by your extensions and applications.
13 </p>
15 <p>
16 In general, CSP works as a black/whitelisting mechanism for resources loaded
17 or executed by your extensions. Defining a reasonable policy for your
18 extension enables you to carefully consider the resources that your extension
19 requires, and to ask the browser to ensure that those are the only resources
20 your extension has access to. These policies provide security over and above
21 the <a href="declare_permissions">host permissions</a> your extension
22 requests; they're an additional layer of protection, not a replacement.
23 </p>
25 <p>
26 On the web, such a policy is defined via an HTTP header or <code>meta</code>
27 element. Inside Chrome's extension system, neither is an appropriate
28 mechanism. Instead, an extension's policy is defined via the extension's
29 <a href="manifest"><code>manifest.json</code></a> file as follows:
30 </p>
32 <pre data-filename="manifest.json">
34 ...,
35 "content_security_policy": "[POLICY STRING GOES HERE]"
36 ...
38 </pre>
40 <p class="note">
41 For full details regarding CSP's syntax, please take a look at
42 <a href="http://dvcs.w3.org/hg/content-security-policy/raw-file/tip/csp-specification.dev.html#syntax">
43 the Content Security Policy specification
44 </a>, and the <a href="http://www.html5rocks.com/en/tutorials/security/content-security-policy/">
45 "An Introduction to Content Security Policy"
46 </a> article on HTML5Rocks.
47 </p>
49 <h2 id="restrictions">Default Policy Restrictions</h2>
51 <p>
52 Packages that do not define a <a href="manifestVersion">
53 <code>manifest_version</code>
54 </a> have no default content security policy. Those that select
55 <code>manifest_version</code> 2, have a default content security policy
56 of:
57 </p>
59 <pre>script-src 'self'; object-src 'self'</pre>
61 <p>
62 This policy adds security by limiting extensions and applications in three
63 ways:
64 </p>
66 <h3 id="JSEval">Eval and related functions are disabled</h3>
68 <p>Code like the following does not work:</p>
70 <pre>
71 alert(eval("foo.bar.baz"));
72 window.setTimeout("alert('hi')", 10);
73 window.setInterval("alert('hi')", 10);
74 new Function("return foo.bar.baz");
75 </pre>
77 <p>Evaluating strings of JavaScript like this is a common XSS attack vector.
78 Instead, you should write code like:
80 <pre>
81 alert(foo && foo.bar && foo.bar.baz);
82 window.setTimeout(function() { alert('hi'); }, 10);
83 window.setInterval(function() { alert('hi'); }, 10);
84 function() { return foo && foo.bar && foo.bar.baz };
85 </pre>
87 <h3 id="JSExecution">Inline JavaScript will not be executed</h3>
89 <p>
90 Inline JavaScript will not be executed. This restriction bans both inline
91 <code>&lt;script&gt;</code> blocks <strong>and</strong> inline event handlers
92 (e.g. <code>&lt;button onclick="..."&gt;</code>).
93 </p>
95 <p>
96 The first restriction wipes out a huge class of cross-site scripting attacks
97 by making it impossible for you to accidentally execute script provided by a
98 malicious third-party. It does, however, require you to write your code with a
99 clean separation between content and behavior (which you should of course do
100 anyway, right?). An example might make this clearer. You might try to write a
101 <a href="browserAction#popups">Browser Action's popup</a> as a single
102 <code>popup.html</code> containing:
103 </p>
105 <pre data-filename="popup.html">
106 &lt;!doctype html&gt;
107 &lt;html&gt;
108 &lt;head&gt;
109 &lt;title&gt;My Awesome Popup!&lt;/title&gt;
110 &lt;script&gt;
111 function awesome() {
112 // do something awesome!
115 function totallyAwesome() {
116 // do something TOTALLY awesome!
119 function clickHandler(element) {
120 setTimeout(<strong>"awesome(); totallyAwesome()"</strong>, 1000);
123 function main() {
124 // Initialization work goes here.
126 &lt;/script&gt;
127 &lt;/head&gt;
128 &lt;body onload="main();"&gt;
129 &lt;button <strong>onclick="clickHandler(this)"</strong>&gt;
130 Click for awesomeness!
131 &lt;/button&gt;
132 &lt;/body&gt;
133 &lt;/html&gt;</pre>
136 Three things will need to change in order to make this work the way you expect
137 it to:
138 </p>
140 <ul>
141 <li>
142 The <code>clickHandler</code> definition needs to move into an external
143 JavaScript file (<code>popup.js</code> would be a good target).
144 </li>
145 <li>
146 <p>The inline event handler definitions must be rewritten in terms of
147 <code>addEventListener</code> and extracted into <code>popup.js</code>.</p>
148 <p>If you're currently kicking off your program's execution via code like
149 <code>&lt;body onload="main();"&gt;</code>, consider replacing it by hooking
150 into the document's <code>DOMContentLoaded</code> event, or the window's
151 <code>load</code> event, depending on your needs. Below we'll use the
152 former, as it generally triggers more quickly.</p>
153 </li>
154 <li>
155 The <code>setTimeout</code> call will need to be rewritten to avoid
156 converting the string <code>"awesome(); totallyAwesome()"</code> into
157 JavaScript for execution.
158 </li>
159 </ul>
162 Those changes might look something like the following:
163 </p>
165 <pre data-filename="popup.js">
166 function awesome() {
167 // Do something awesome!
170 function totallyAwesome() {
171 // do something TOTALLY awesome!
174 <strong>function awesomeTask() {
175 awesome();
176 totallyAwesome();
177 }</strong>
179 function clickHandler(e) {
180 setTimeout(<strong>awesomeTask</strong>, 1000);
183 function main() {
184 // Initialization work goes here.
187 // Add event listeners once the DOM has fully loaded by listening for the
188 // `DOMContentLoaded` event on the document, and adding your listeners to
189 // specific elements when it triggers.
190 <strong>document.addEventListener('DOMContentLoaded', function () {</strong>
191 document.querySelector('button').addEventListener('click', clickHandler);
192 main();
194 </pre>
195 <pre data-filename="popup.html">
196 &lt;!doctype html&gt;
197 &lt;html&gt;
198 &lt;head&gt;
199 &lt;title&gt;My Awesome Popup!&lt;/title&gt;
200 &lt;script <strong>src="popup.js"</strong>&gt;&lt;/script&gt;
201 &lt;/head&gt;
202 &lt;body&gt;
203 &lt;button&gt;Click for awesomeness!&lt;/button&gt;
204 &lt;/body&gt;
205 &lt;/html&gt;
206 </pre>
211 <h3 id="resourceLoading">Only local script and and object resources are loaded</h3>
214 Script and object resources can only be loaded from the extension's
215 package, not from the web at large. This ensures that your extension only
216 executes the code you've specifically approved, preventing an active network
217 attacker from maliciously redirecting your request for a resource.
218 </p>
221 Instead of writing code that depends on jQuery (or any other library) loading
222 from an external CDN, consider including the specific version of jQuery in
223 your extension package. That is, instead of:
224 </p>
226 <pre data-filename="popup.html">
227 &lt;!doctype html&gt;
228 &lt;html&gt;
229 &lt;head&gt;
230 &lt;title&gt;My Awesome Popup!&lt;/title&gt;
231 &lt;script src="<strong>http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js</strong>"&gt;&lt;/script&gt;
232 &lt;/head&gt;
233 &lt;body&gt;
234 &lt;button&gt;Click for awesomeness!&lt;/button&gt;
235 &lt;/body&gt;
236 &lt;/html&gt;
237 </pre>
240 Download the file, include it in your package, and write:
243 <pre data-filename="popup.html">
244 &lt;!doctype html&gt;
245 &lt;html&gt;
246 &lt;head&gt;
247 &lt;title&gt;My Awesome Popup!&lt;/title&gt;
248 &lt;script src="<strong>jquery.min.js</strong>"&gt;&lt;/script&gt;
249 &lt;/head&gt;
250 &lt;body&gt;
251 &lt;button&gt;Click for awesomeness!&lt;/button&gt;
252 &lt;/body&gt;
253 &lt;/html&gt;</pre>
255 <h2 id="relaxing">Relaxing the default policy</h2>
257 <h3 id="relaxing-inline-script">Inline Script</h3>
260 Up until Chrome 45, there was no mechanism for relaxing the restriction
261 against executing inline JavaScript. In particular, setting a script policy
262 that includes <code>'unsafe-inline'</code> will have no effect.
263 </p>
266 As of Chrome 46, inline scripts can be whitelisted by specifying the
267 base64-encoded hash of the source code in the policy. This hash must be
268 prefixed by the used hash algorithm (sha256, sha384 or sha512).
270 <a href="http://www.w3.org/TR/2015/CR-CSP2-20150721/#script-src-hash-usage">
271 Hash usage for &lt;script&gt; elements</a> for an example.
272 </p>
274 <h3 id="relaxing-remote-script">Remote Script</h3>
277 If you have a need for some external JavaScript or object
278 resources, you can relax the policy to a limited extent by whitelisting
279 secure origins from which scripts should be accepted. We want to ensure that
280 executable resources loaded with an extension's elevated permissions are
281 exactly the resources you expect, and haven't been replaced by an active
282 network attacker. As <a
283 href="http://en.wikipedia.org/wiki/Man-in-the-middle_attack">man-in-the-middle
284 attacks</a> are both trivial and undetectable over HTTP, those origins will
285 not be accepted.
286 </p>
289 Currently, we allow whitelisting origins with the following schemes:
290 <code>blob</code>, <code>filesystem</code>, <code>https</code>,
291 <code>chrome-extension</code>, and <code>chrome-extension-resource</code>.
292 The host part of the origin must explicitly be specified for the
293 <code>https</code> and <code>chrome-extension</code> schemes.
294 Generic wildcards such as <code>https:</code>, <code>https://*</code> and
295 <code>https://*.com</code> are not allowed; subdomain wildcards such as
296 <code>https://*.example.com</code> are allowed.
297 Domains in the <a href="https://publicsuffix.org/list/">Public Suffix list</a>
298 are also viewed as generic top-level domains. To load a resource from these
299 domains, the subdomain must explicitly be listed. For example,
300 <code>https://*.cloudfront.net</code> is invalid, but
301 <code>https://XXXX.cloudfront.net</code> and
302 <code>https://*.XXXX.cloudfront.net</code> can be whitelisted.
303 </p>
306 To ease development, we're also allowing the whitelisting of resources loaded
307 over HTTP from servers on your local machine. You may whitelist script and
308 object sources on any port of either <code>http://127.0.0.1</code> or
309 <code>http://localhost</code>.
310 </p>
312 <p class="note">
313 The restriction against resources loaded over HTTP applies only to those
314 resources which are directly executed. You're still free, for example, to
315 make XMLHTTPRequest connections to any origin you like; the default policy
316 doesn't restrict <code>connect-src</code> or any of the other CSP directives
317 in any way.
318 </p>
321 A relaxed policy definition which allows script resources to be loaded from
322 <code>example.com</code> over HTTPS might look like:
323 </p>
325 <pre data-filename="manifest.json">
326 "content_security_policy": "script-src 'self' https://example.com; object-src 'self'"
327 </pre>
329 <p class="note">
330 Note that both <code>script-src</code> and <code>object-src</code> are defined
331 by the policy. Chrome will not accept a policy that doesn't limit each of
332 these values to (at least) <code>'self'</code>.
333 </p>
336 Making use of Google Analytics is the canonical example for this sort of
337 policy definition. It's common enough that we've provided an Analytics
338 boilerplate of sorts in the <a href="samples#event-tracking-with-google-analytics">Event Tracking
339 with Google Analytics</a> sample extension, and a
340 <a href="tut_analytics">brief tutorial</a> that goes into more detail.
341 </p>
343 <h3 id="relaxing-eval">Evaluated JavaScript</h3>
346 The policy against <code>eval()</code> and its relatives like
347 <code>setTimeout(String)</code>, <code>setInterval(String)</code>, and
348 <code>new Function(String)</code> can be relaxed by adding
349 <code>'unsafe-eval'</code> to your policy:
350 </p>
352 <pre data-filename="manifest.json">
353 "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"
354 </pre>
357 However, we strongly recommend against doing this. These functions are
358 notorious XSS attack vectors.
359 </p>
361 <h2 id="tightening">Tightening the default policy</h2>
364 You may, of course, tighten this policy to whatever extent your extension
365 allows in order to increase security at the expense of convenience. To specify
366 that your extension can only load resources of <em>any</em> type (images, etc)
367 from its own package, for example, a policy of <code>default-src 'self'</code>
368 would be appropriate. The <a href="samples#mappy">Mappy</a> sample
369 extension is a good example of an extension that's been locked down above and
370 beyond the defaults.
371 </p>
374 <h2 id="interactions">Content Scripts</h2>
377 The policy that we have been discussing applies to the <a
378 href="background_pages">background pages</a> and <a href="event_pages">event
379 pages</a> of the extension. How they apply to the <a href="content_scripts">
380 content scripts</a> of the extension is more complicated.
381 </p>
384 Content scripts are generally not subject to the CSP of the extension. Since
385 content scripts are not HTML, the main impact of this is that they may use
386 <code>eval</code> even if the extension's CSP does not specify
387 <code>unsafe-eval</code>, although this is not recommended. Additionally, the
388 CSP of the <em>page</em> does not apply to content scripts. More complicated
389 are <code>&lt;script&gt;</code> tags that content scripts create and put into
390 the DOM of the page they are running on. We will refer to these as DOM
391 injected scripts going forward.
392 </p>
395 DOM injected scripts that would be executed immediately upon injection into
396 the page will execute as you might expect. Imagine a content script with the
397 following code as a simple example:
398 <pre data-filename="content_script.js">
399 document.write("&lt;script&gt;alert(1);&lt;/script&gt;");
400 </pre>
401 This content script will cause an <code>alert</code> immediately upon the
402 <code>document.write()</code>. Note that this will execute regardless of the
403 policy a page may specify.
404 </p>
407 However, the behavior becomes more complicated both inside that DOM injected
408 script and for any script that does not immediately execute upon injection.
409 Imagine that our extension is running on a page that provides its own CSP
410 that specifies <code>script-src 'self'</code>. Now imagine the content script
411 executes the following code:
412 <pre data-filename="content_script.js">
413 document.write("&lt;button onclick='alert(1);'&gt;click me&lt;/button&gt;'");
414 </pre>
415 If a user clicks on that button, the <code>onclick</code> script will
416 <em>not</em> execute. This is because the script did not immediately execute
417 and code not interpreted until the click event occurs is not considered part
418 of the content script, so the CSP <em>of the page</em> (not of the extension)
419 restricts its behavior. And since that CSP does not specify
420 <code>unsafe-inline</code>, the inline event handler is blocked.
421 </p>
424 The correct way to implement the desired behavior in this case would be to add
425 the <code>onclick</code> handler as a function from the content script as
426 follows:
427 <pre data-filename="content_script.js">
428 document.write("&lt;button id='mybutton'&gt;click me&lt;/button&gt;'");
429 var button = document.getElementById('mybutton');
430 button.onclick = function() {
431 alert(1);
433 </pre>
434 </p>
437 Another similar issue arises if the content script executes the following:
438 <pre data-filename="content_script.js">
439 var script = document.createElement('script');
440 script.innerHTML = 'alert(1);'
441 document.getElementById('body').appendChild(script);
442 </pre>
443 In this case, the script <em>will</em> execute and the alert will pop up.
444 However, take this case:
445 <pre data-filename="content_script.js">
446 var script = document.createElement('script');
447 script.innerHTML = 'eval("alert(1);")';
448 document.getElementById('body').appendChild(script);
449 </pre>
450 While the initial script will execute, the call to <code>eval</code> will be
451 blocked. That is, while the initial script execution is allowed, the behavior
452 within the script will be regulated by the page's CSP.
453 </p>
456 Thus, depending on how you write DOM injected scripts in your extension,
457 changes to the page's CSP may affect the behavior of your extension. Since
458 content scripts are <em>not</em> affected by the page's CSP, this a great
459 reason to put as much behavior as possible of your extension into the content
460 script rather than DOM injected scripts.
461 </p>