Create a new window on launch.
[chromium-blink-merge.git] / extensions / common / csp_validator.cc
blob371d7f8d10a5ac764c7685e405517dfa4ef70c16
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "extensions/common/csp_validator.h"
7 #include <vector>
9 #include "base/strings/string_split.h"
10 #include "base/strings/string_tokenizer.h"
11 #include "base/strings/string_util.h"
12 #include "content/public/common/url_constants.h"
13 #include "extensions/common/constants.h"
14 #include "extensions/common/error_utils.h"
15 #include "extensions/common/install_warning.h"
16 #include "extensions/common/manifest_constants.h"
17 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
19 namespace extensions {
21 namespace csp_validator {
23 namespace {
25 const char kDefaultSrc[] = "default-src";
26 const char kScriptSrc[] = "script-src";
27 const char kObjectSrc[] = "object-src";
28 const char kPluginTypes[] = "plugin-types";
30 const char kObjectSrcDefaultDirective[] = "object-src 'self';";
31 const char kScriptSrcDefaultDirective[] =
32 "script-src 'self' chrome-extension-resource:;";
34 const char kSandboxDirectiveName[] = "sandbox";
35 const char kAllowSameOriginToken[] = "allow-same-origin";
36 const char kAllowTopNavigation[] = "allow-top-navigation";
38 // This is the list of plugin types which are fully sandboxed and are safe to
39 // load up in an extension, regardless of the URL they are navigated to.
40 const char* const kSandboxedPluginTypes[] = {
41 "application/pdf",
42 "application/x-google-chrome-pdf",
43 "application/x-pnacl"
46 struct DirectiveStatus {
47 explicit DirectiveStatus(const char* name)
48 : directive_name(name), seen_in_policy(false) {}
50 const char* directive_name;
51 bool seen_in_policy;
54 // Returns whether |url| starts with |scheme_and_separator| and does not have a
55 // too permissive wildcard host name. If |should_check_rcd| is true, then the
56 // Public suffix list is used to exclude wildcard TLDs such as "https://*.org".
57 bool isNonWildcardTLD(const std::string& url,
58 const std::string& scheme_and_separator,
59 bool should_check_rcd) {
60 if (!StartsWithASCII(url, scheme_and_separator, true))
61 return false;
63 size_t start_of_host = scheme_and_separator.length();
65 size_t end_of_host = url.find("/", start_of_host);
66 if (end_of_host == std::string::npos)
67 end_of_host = url.size();
69 // Note: It is sufficient to only compare the first character against '*'
70 // because the CSP only allows wildcards at the start of a directive, see
71 // host-source and host-part at http://www.w3.org/TR/CSP2/#source-list-syntax
72 bool is_wildcard_subdomain = end_of_host > start_of_host + 2 &&
73 url[start_of_host] == '*' && url[start_of_host + 1] == '.';
74 if (is_wildcard_subdomain)
75 start_of_host += 2;
77 size_t start_of_port = url.rfind(":", end_of_host);
78 // The ":" check at the end of the following condition is used to avoid
79 // treating the last part of an IPv6 address as a port.
80 if (start_of_port > start_of_host && url[start_of_port - 1] != ':') {
81 bool is_valid_port = false;
82 // Do a quick sanity check. The following check could mistakenly flag
83 // ":123456" or ":****" as valid, but that does not matter because the
84 // relaxing CSP directive will just be ignored by Blink.
85 for (size_t i = start_of_port + 1; i < end_of_host; ++i) {
86 is_valid_port = IsAsciiDigit(url[i]) || url[i] == '*';
87 if (!is_valid_port)
88 break;
90 if (is_valid_port)
91 end_of_host = start_of_port;
94 std::string host(url, start_of_host, end_of_host - start_of_host);
95 // Global wildcards are not allowed.
96 if (host.empty() || host.find("*") != std::string::npos)
97 return false;
99 if (!is_wildcard_subdomain || !should_check_rcd)
100 return true;
102 // Allow *.googleapis.com to be whitelisted for backwards-compatibility.
103 // (crbug.com/409952)
104 if (host == "googleapis.com")
105 return true;
107 // Wildcards on subdomains of a TLD are not allowed.
108 size_t registry_length = net::registry_controlled_domains::GetRegistryLength(
109 host,
110 net::registry_controlled_domains::INCLUDE_UNKNOWN_REGISTRIES,
111 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
112 return registry_length != 0;
115 InstallWarning CSPInstallWarning(const std::string& csp_warning) {
116 return InstallWarning(csp_warning, manifest_keys::kContentSecurityPolicy);
119 void GetSecureDirectiveValues(const std::string& directive_name,
120 base::StringTokenizer* tokenizer,
121 int options,
122 std::vector<std::string>* sane_csp_parts,
123 std::vector<InstallWarning>* warnings) {
124 sane_csp_parts->push_back(directive_name);
125 while (tokenizer->GetNext()) {
126 std::string source = tokenizer->token();
127 base::StringToLowerASCII(&source);
128 bool is_secure_csp_token = false;
130 // We might need to relax this whitelist over time.
131 if (source == "'self'" ||
132 source == "'none'" ||
133 source == "http://127.0.0.1" ||
134 LowerCaseEqualsASCII(source, "blob:") ||
135 LowerCaseEqualsASCII(source, "filesystem:") ||
136 LowerCaseEqualsASCII(source, "http://localhost") ||
137 StartsWithASCII(source, "http://127.0.0.1:", true) ||
138 StartsWithASCII(source, "http://localhost:", true) ||
139 isNonWildcardTLD(source, "https://", true) ||
140 isNonWildcardTLD(source, "chrome://", false) ||
141 isNonWildcardTLD(source,
142 std::string(extensions::kExtensionScheme) +
143 url::kStandardSchemeSeparator,
144 false) ||
145 StartsWithASCII(source, "chrome-extension-resource:", true)) {
146 is_secure_csp_token = true;
147 } else if ((options & OPTIONS_ALLOW_UNSAFE_EVAL) &&
148 source == "'unsafe-eval'") {
149 is_secure_csp_token = true;
152 if (is_secure_csp_token) {
153 sane_csp_parts->push_back(source);
154 } else if (warnings) {
155 warnings->push_back(CSPInstallWarning(ErrorUtils::FormatErrorMessage(
156 manifest_errors::kInvalidCSPInsecureValue, source, directive_name)));
159 // End of CSP directive that was started at the beginning of this method. If
160 // none of the values are secure, the policy will be empty and default to
161 // 'none', which is secure.
162 sane_csp_parts->back().push_back(';');
165 // Returns true if |directive_name| matches |status.directive_name|.
166 bool UpdateStatus(const std::string& directive_name,
167 base::StringTokenizer* tokenizer,
168 DirectiveStatus* status,
169 int options,
170 std::vector<std::string>* sane_csp_parts,
171 std::vector<InstallWarning>* warnings) {
172 if (directive_name != status->directive_name)
173 return false;
175 if (!status->seen_in_policy) {
176 status->seen_in_policy = true;
177 GetSecureDirectiveValues(directive_name, tokenizer, options, sane_csp_parts,
178 warnings);
179 } else {
180 // Don't show any errors for duplicate CSP directives, because it will be
181 // ignored by the CSP parser (http://www.w3.org/TR/CSP2/#policy-parsing).
182 GetSecureDirectiveValues(directive_name, tokenizer, options, sane_csp_parts,
183 NULL);
185 return true;
188 // Returns true if the |plugin_type| is one of the fully sandboxed plugin types.
189 bool PluginTypeAllowed(const std::string& plugin_type) {
190 for (size_t i = 0; i < arraysize(kSandboxedPluginTypes); ++i) {
191 if (plugin_type == kSandboxedPluginTypes[i])
192 return true;
194 return false;
197 // Returns true if the policy is allowed to contain an insecure object-src
198 // directive. This requires OPTIONS_ALLOW_INSECURE_OBJECT_SRC to be specified
199 // as an option and the plugin-types that can be loaded must be restricted to
200 // the set specified in kSandboxedPluginTypes.
201 bool AllowedToHaveInsecureObjectSrc(
202 int options,
203 const std::vector<std::string>& directives) {
204 if (!(options & OPTIONS_ALLOW_INSECURE_OBJECT_SRC))
205 return false;
207 for (size_t i = 0; i < directives.size(); ++i) {
208 const std::string& input = directives[i];
209 base::StringTokenizer tokenizer(input, " \t\r\n");
210 if (!tokenizer.GetNext())
211 continue;
212 if (!LowerCaseEqualsASCII(tokenizer.token(), kPluginTypes))
213 continue;
214 while (tokenizer.GetNext()) {
215 if (!PluginTypeAllowed(tokenizer.token()))
216 return false;
218 // All listed plugin types are whitelisted.
219 return true;
221 // plugin-types not specified.
222 return false;
225 } // namespace
227 bool ContentSecurityPolicyIsLegal(const std::string& policy) {
228 // We block these characters to prevent HTTP header injection when
229 // representing the content security policy as an HTTP header.
230 const char kBadChars[] = {',', '\r', '\n', '\0'};
232 return policy.find_first_of(kBadChars, 0, arraysize(kBadChars)) ==
233 std::string::npos;
236 std::string SanitizeContentSecurityPolicy(
237 const std::string& policy,
238 int options,
239 std::vector<InstallWarning>* warnings) {
240 // See http://www.w3.org/TR/CSP/#parse-a-csp-policy for parsing algorithm.
241 std::vector<std::string> directives;
242 base::SplitString(policy, ';', &directives);
244 DirectiveStatus default_src_status(kDefaultSrc);
245 DirectiveStatus script_src_status(kScriptSrc);
246 DirectiveStatus object_src_status(kObjectSrc);
248 bool allow_insecure_object_src =
249 AllowedToHaveInsecureObjectSrc(options, directives);
251 std::vector<std::string> sane_csp_parts;
252 std::vector<InstallWarning> default_src_csp_warnings;
253 for (size_t i = 0; i < directives.size(); ++i) {
254 std::string& input = directives[i];
255 base::StringTokenizer tokenizer(input, " \t\r\n");
256 if (!tokenizer.GetNext())
257 continue;
259 std::string directive_name = tokenizer.token();
260 base::StringToLowerASCII(&directive_name);
262 if (UpdateStatus(directive_name, &tokenizer, &default_src_status, options,
263 &sane_csp_parts, &default_src_csp_warnings))
264 continue;
265 if (UpdateStatus(directive_name, &tokenizer, &script_src_status, options,
266 &sane_csp_parts, warnings))
267 continue;
268 if (!allow_insecure_object_src &&
269 UpdateStatus(directive_name, &tokenizer, &object_src_status, options,
270 &sane_csp_parts, warnings))
271 continue;
273 // Pass the other CSP directives as-is without further validation.
274 sane_csp_parts.push_back(input + ";");
277 if (default_src_status.seen_in_policy) {
278 if (!script_src_status.seen_in_policy ||
279 !object_src_status.seen_in_policy) {
280 // Insecure values in default-src are only relevant if either script-src
281 // or object-src is omitted.
282 if (warnings)
283 warnings->insert(warnings->end(),
284 default_src_csp_warnings.begin(),
285 default_src_csp_warnings.end());
287 } else {
288 if (!script_src_status.seen_in_policy) {
289 sane_csp_parts.push_back(kScriptSrcDefaultDirective);
290 if (warnings)
291 warnings->push_back(CSPInstallWarning(ErrorUtils::FormatErrorMessage(
292 manifest_errors::kInvalidCSPMissingSecureSrc, kScriptSrc)));
294 if (!object_src_status.seen_in_policy && !allow_insecure_object_src) {
295 sane_csp_parts.push_back(kObjectSrcDefaultDirective);
296 if (warnings)
297 warnings->push_back(CSPInstallWarning(ErrorUtils::FormatErrorMessage(
298 manifest_errors::kInvalidCSPMissingSecureSrc, kObjectSrc)));
302 return JoinString(sane_csp_parts, ' ');
305 bool ContentSecurityPolicyIsSandboxed(
306 const std::string& policy, Manifest::Type type) {
307 // See http://www.w3.org/TR/CSP/#parse-a-csp-policy for parsing algorithm.
308 std::vector<std::string> directives;
309 base::SplitString(policy, ';', &directives);
311 bool seen_sandbox = false;
313 for (size_t i = 0; i < directives.size(); ++i) {
314 std::string& input = directives[i];
315 base::StringTokenizer tokenizer(input, " \t\r\n");
316 if (!tokenizer.GetNext())
317 continue;
319 std::string directive_name = tokenizer.token();
320 base::StringToLowerASCII(&directive_name);
322 if (directive_name != kSandboxDirectiveName)
323 continue;
325 seen_sandbox = true;
327 while (tokenizer.GetNext()) {
328 std::string token = tokenizer.token();
329 base::StringToLowerASCII(&token);
331 // The same origin token negates the sandboxing.
332 if (token == kAllowSameOriginToken)
333 return false;
335 // Platform apps don't allow navigation.
336 if (type == Manifest::TYPE_PLATFORM_APP) {
337 if (token == kAllowTopNavigation)
338 return false;
343 return seen_sandbox;
346 } // namespace csp_validator
348 } // namespace extensions