Files.app: Dispatch 'drive-connection-changed' event on initialization of VolumeManag...
[chromium-blink-merge.git] / extensions / common / csp_validator.cc
blob06ea4ef6f3e71f898af4e350d5963cf0ea82c8bb
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 (!base::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 = base::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'" || source == "'none'" ||
132 source == "http://127.0.0.1" ||
133 base::LowerCaseEqualsASCII(source, "blob:") ||
134 base::LowerCaseEqualsASCII(source, "filesystem:") ||
135 base::LowerCaseEqualsASCII(source, "http://localhost") ||
136 base::StartsWithASCII(source, "http://127.0.0.1:", true) ||
137 base::StartsWithASCII(source, "http://localhost:", true) ||
138 isNonWildcardTLD(source, "https://", true) ||
139 isNonWildcardTLD(source, "chrome://", false) ||
140 isNonWildcardTLD(source, std::string(extensions::kExtensionScheme) +
141 url::kStandardSchemeSeparator,
142 false) ||
143 base::StartsWithASCII(source, "chrome-extension-resource:", true)) {
144 is_secure_csp_token = true;
145 } else if ((options & OPTIONS_ALLOW_UNSAFE_EVAL) &&
146 source == "'unsafe-eval'") {
147 is_secure_csp_token = true;
150 if (is_secure_csp_token) {
151 sane_csp_parts->push_back(source);
152 } else if (warnings) {
153 warnings->push_back(CSPInstallWarning(ErrorUtils::FormatErrorMessage(
154 manifest_errors::kInvalidCSPInsecureValue, source, directive_name)));
157 // End of CSP directive that was started at the beginning of this method. If
158 // none of the values are secure, the policy will be empty and default to
159 // 'none', which is secure.
160 sane_csp_parts->back().push_back(';');
163 // Returns true if |directive_name| matches |status.directive_name|.
164 bool UpdateStatus(const std::string& directive_name,
165 base::StringTokenizer* tokenizer,
166 DirectiveStatus* status,
167 int options,
168 std::vector<std::string>* sane_csp_parts,
169 std::vector<InstallWarning>* warnings) {
170 if (directive_name != status->directive_name)
171 return false;
173 if (!status->seen_in_policy) {
174 status->seen_in_policy = true;
175 GetSecureDirectiveValues(directive_name, tokenizer, options, sane_csp_parts,
176 warnings);
177 } else {
178 // Don't show any errors for duplicate CSP directives, because it will be
179 // ignored by the CSP parser (http://www.w3.org/TR/CSP2/#policy-parsing).
180 GetSecureDirectiveValues(directive_name, tokenizer, options, sane_csp_parts,
181 NULL);
183 return true;
186 // Returns true if the |plugin_type| is one of the fully sandboxed plugin types.
187 bool PluginTypeAllowed(const std::string& plugin_type) {
188 for (size_t i = 0; i < arraysize(kSandboxedPluginTypes); ++i) {
189 if (plugin_type == kSandboxedPluginTypes[i])
190 return true;
192 return false;
195 // Returns true if the policy is allowed to contain an insecure object-src
196 // directive. This requires OPTIONS_ALLOW_INSECURE_OBJECT_SRC to be specified
197 // as an option and the plugin-types that can be loaded must be restricted to
198 // the set specified in kSandboxedPluginTypes.
199 bool AllowedToHaveInsecureObjectSrc(
200 int options,
201 const std::vector<std::string>& directives) {
202 if (!(options & OPTIONS_ALLOW_INSECURE_OBJECT_SRC))
203 return false;
205 for (size_t i = 0; i < directives.size(); ++i) {
206 const std::string& input = directives[i];
207 base::StringTokenizer tokenizer(input, " \t\r\n");
208 if (!tokenizer.GetNext())
209 continue;
210 if (!base::LowerCaseEqualsASCII(tokenizer.token(), kPluginTypes))
211 continue;
212 while (tokenizer.GetNext()) {
213 if (!PluginTypeAllowed(tokenizer.token()))
214 return false;
216 // All listed plugin types are whitelisted.
217 return true;
219 // plugin-types not specified.
220 return false;
223 } // namespace
225 bool ContentSecurityPolicyIsLegal(const std::string& policy) {
226 // We block these characters to prevent HTTP header injection when
227 // representing the content security policy as an HTTP header.
228 const char kBadChars[] = {',', '\r', '\n', '\0'};
230 return policy.find_first_of(kBadChars, 0, arraysize(kBadChars)) ==
231 std::string::npos;
234 std::string SanitizeContentSecurityPolicy(
235 const std::string& policy,
236 int options,
237 std::vector<InstallWarning>* warnings) {
238 // See http://www.w3.org/TR/CSP/#parse-a-csp-policy for parsing algorithm.
239 std::vector<std::string> directives;
240 base::SplitString(policy, ';', &directives);
242 DirectiveStatus default_src_status(kDefaultSrc);
243 DirectiveStatus script_src_status(kScriptSrc);
244 DirectiveStatus object_src_status(kObjectSrc);
246 bool allow_insecure_object_src =
247 AllowedToHaveInsecureObjectSrc(options, directives);
249 std::vector<std::string> sane_csp_parts;
250 std::vector<InstallWarning> default_src_csp_warnings;
251 for (size_t i = 0; i < directives.size(); ++i) {
252 std::string& input = directives[i];
253 base::StringTokenizer tokenizer(input, " \t\r\n");
254 if (!tokenizer.GetNext())
255 continue;
257 std::string directive_name = tokenizer.token();
258 base::StringToLowerASCII(&directive_name);
260 if (UpdateStatus(directive_name, &tokenizer, &default_src_status, options,
261 &sane_csp_parts, &default_src_csp_warnings))
262 continue;
263 if (UpdateStatus(directive_name, &tokenizer, &script_src_status, options,
264 &sane_csp_parts, warnings))
265 continue;
266 if (!allow_insecure_object_src &&
267 UpdateStatus(directive_name, &tokenizer, &object_src_status, options,
268 &sane_csp_parts, warnings))
269 continue;
271 // Pass the other CSP directives as-is without further validation.
272 sane_csp_parts.push_back(input + ";");
275 if (default_src_status.seen_in_policy) {
276 if (!script_src_status.seen_in_policy ||
277 !object_src_status.seen_in_policy) {
278 // Insecure values in default-src are only relevant if either script-src
279 // or object-src is omitted.
280 if (warnings)
281 warnings->insert(warnings->end(),
282 default_src_csp_warnings.begin(),
283 default_src_csp_warnings.end());
285 } else {
286 if (!script_src_status.seen_in_policy) {
287 sane_csp_parts.push_back(kScriptSrcDefaultDirective);
288 if (warnings)
289 warnings->push_back(CSPInstallWarning(ErrorUtils::FormatErrorMessage(
290 manifest_errors::kInvalidCSPMissingSecureSrc, kScriptSrc)));
292 if (!object_src_status.seen_in_policy && !allow_insecure_object_src) {
293 sane_csp_parts.push_back(kObjectSrcDefaultDirective);
294 if (warnings)
295 warnings->push_back(CSPInstallWarning(ErrorUtils::FormatErrorMessage(
296 manifest_errors::kInvalidCSPMissingSecureSrc, kObjectSrc)));
300 return JoinString(sane_csp_parts, ' ');
303 bool ContentSecurityPolicyIsSandboxed(
304 const std::string& policy, Manifest::Type type) {
305 // See http://www.w3.org/TR/CSP/#parse-a-csp-policy for parsing algorithm.
306 std::vector<std::string> directives;
307 base::SplitString(policy, ';', &directives);
309 bool seen_sandbox = false;
311 for (size_t i = 0; i < directives.size(); ++i) {
312 std::string& input = directives[i];
313 base::StringTokenizer tokenizer(input, " \t\r\n");
314 if (!tokenizer.GetNext())
315 continue;
317 std::string directive_name = tokenizer.token();
318 base::StringToLowerASCII(&directive_name);
320 if (directive_name != kSandboxDirectiveName)
321 continue;
323 seen_sandbox = true;
325 while (tokenizer.GetNext()) {
326 std::string token = tokenizer.token();
327 base::StringToLowerASCII(&token);
329 // The same origin token negates the sandboxing.
330 if (token == kAllowSameOriginToken)
331 return false;
333 // Platform apps don't allow navigation.
334 if (type == Manifest::TYPE_PLATFORM_APP) {
335 if (token == kAllowTopNavigation)
336 return false;
341 return seen_sandbox;
344 } // namespace csp_validator
346 } // namespace extensions