Upstreaming browser/ui/uikit_ui_util from iOS.
[chromium-blink-merge.git] / extensions / common / csp_validator.cc
blob1fe22178854f13df8826df4c0e1eea293a353dea
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::StartsWith(url, scheme_and_separator,
61 base::CompareCase::SENSITIVE))
62 return false;
64 size_t start_of_host = scheme_and_separator.length();
66 size_t end_of_host = url.find("/", start_of_host);
67 if (end_of_host == std::string::npos)
68 end_of_host = url.size();
70 // Note: It is sufficient to only compare the first character against '*'
71 // because the CSP only allows wildcards at the start of a directive, see
72 // host-source and host-part at http://www.w3.org/TR/CSP2/#source-list-syntax
73 bool is_wildcard_subdomain = end_of_host > start_of_host + 2 &&
74 url[start_of_host] == '*' && url[start_of_host + 1] == '.';
75 if (is_wildcard_subdomain)
76 start_of_host += 2;
78 size_t start_of_port = url.rfind(":", end_of_host);
79 // The ":" check at the end of the following condition is used to avoid
80 // treating the last part of an IPv6 address as a port.
81 if (start_of_port > start_of_host && url[start_of_port - 1] != ':') {
82 bool is_valid_port = false;
83 // Do a quick sanity check. The following check could mistakenly flag
84 // ":123456" or ":****" as valid, but that does not matter because the
85 // relaxing CSP directive will just be ignored by Blink.
86 for (size_t i = start_of_port + 1; i < end_of_host; ++i) {
87 is_valid_port = base::IsAsciiDigit(url[i]) || url[i] == '*';
88 if (!is_valid_port)
89 break;
91 if (is_valid_port)
92 end_of_host = start_of_port;
95 std::string host(url, start_of_host, end_of_host - start_of_host);
96 // Global wildcards are not allowed.
97 if (host.empty() || host.find("*") != std::string::npos)
98 return false;
100 if (!is_wildcard_subdomain || !should_check_rcd)
101 return true;
103 // Allow *.googleapis.com to be whitelisted for backwards-compatibility.
104 // (crbug.com/409952)
105 if (host == "googleapis.com")
106 return true;
108 // Wildcards on subdomains of a TLD are not allowed.
109 size_t registry_length = net::registry_controlled_domains::GetRegistryLength(
110 host,
111 net::registry_controlled_domains::INCLUDE_UNKNOWN_REGISTRIES,
112 net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
113 return registry_length != 0;
116 InstallWarning CSPInstallWarning(const std::string& csp_warning) {
117 return InstallWarning(csp_warning, manifest_keys::kContentSecurityPolicy);
120 void GetSecureDirectiveValues(const std::string& directive_name,
121 base::StringTokenizer* tokenizer,
122 int options,
123 std::vector<std::string>* sane_csp_parts,
124 std::vector<InstallWarning>* warnings) {
125 sane_csp_parts->push_back(directive_name);
126 while (tokenizer->GetNext()) {
127 std::string source = tokenizer->token();
128 base::StringToLowerASCII(&source);
129 bool is_secure_csp_token = false;
131 // We might need to relax this whitelist over time.
132 if (source == "'self'" || source == "'none'" ||
133 source == "http://127.0.0.1" ||
134 base::LowerCaseEqualsASCII(source, "blob:") ||
135 base::LowerCaseEqualsASCII(source, "filesystem:") ||
136 base::LowerCaseEqualsASCII(source, "http://localhost") ||
137 base::StartsWith(source, "http://127.0.0.1:",
138 base::CompareCase::SENSITIVE) ||
139 base::StartsWith(source, "http://localhost:",
140 base::CompareCase::SENSITIVE) ||
141 isNonWildcardTLD(source, "https://", true) ||
142 isNonWildcardTLD(source, "chrome://", false) ||
143 isNonWildcardTLD(source, std::string(extensions::kExtensionScheme) +
144 url::kStandardSchemeSeparator,
145 false) ||
146 base::StartsWith(source, "chrome-extension-resource:",
147 base::CompareCase::SENSITIVE)) {
148 is_secure_csp_token = true;
149 } else if ((options & OPTIONS_ALLOW_UNSAFE_EVAL) &&
150 source == "'unsafe-eval'") {
151 is_secure_csp_token = true;
154 if (is_secure_csp_token) {
155 sane_csp_parts->push_back(source);
156 } else if (warnings) {
157 warnings->push_back(CSPInstallWarning(ErrorUtils::FormatErrorMessage(
158 manifest_errors::kInvalidCSPInsecureValue, source, directive_name)));
161 // End of CSP directive that was started at the beginning of this method. If
162 // none of the values are secure, the policy will be empty and default to
163 // 'none', which is secure.
164 sane_csp_parts->back().push_back(';');
167 // Returns true if |directive_name| matches |status.directive_name|.
168 bool UpdateStatus(const std::string& directive_name,
169 base::StringTokenizer* tokenizer,
170 DirectiveStatus* status,
171 int options,
172 std::vector<std::string>* sane_csp_parts,
173 std::vector<InstallWarning>* warnings) {
174 if (directive_name != status->directive_name)
175 return false;
177 if (!status->seen_in_policy) {
178 status->seen_in_policy = true;
179 GetSecureDirectiveValues(directive_name, tokenizer, options, sane_csp_parts,
180 warnings);
181 } else {
182 // Don't show any errors for duplicate CSP directives, because it will be
183 // ignored by the CSP parser (http://www.w3.org/TR/CSP2/#policy-parsing).
184 GetSecureDirectiveValues(directive_name, tokenizer, options, sane_csp_parts,
185 NULL);
187 return true;
190 // Returns true if the |plugin_type| is one of the fully sandboxed plugin types.
191 bool PluginTypeAllowed(const std::string& plugin_type) {
192 for (size_t i = 0; i < arraysize(kSandboxedPluginTypes); ++i) {
193 if (plugin_type == kSandboxedPluginTypes[i])
194 return true;
196 return false;
199 // Returns true if the policy is allowed to contain an insecure object-src
200 // directive. This requires OPTIONS_ALLOW_INSECURE_OBJECT_SRC to be specified
201 // as an option and the plugin-types that can be loaded must be restricted to
202 // the set specified in kSandboxedPluginTypes.
203 bool AllowedToHaveInsecureObjectSrc(
204 int options,
205 const std::vector<std::string>& directives) {
206 if (!(options & OPTIONS_ALLOW_INSECURE_OBJECT_SRC))
207 return false;
209 for (size_t i = 0; i < directives.size(); ++i) {
210 const std::string& input = directives[i];
211 base::StringTokenizer tokenizer(input, " \t\r\n");
212 if (!tokenizer.GetNext())
213 continue;
214 if (!base::LowerCaseEqualsASCII(tokenizer.token(), kPluginTypes))
215 continue;
216 while (tokenizer.GetNext()) {
217 if (!PluginTypeAllowed(tokenizer.token()))
218 return false;
220 // All listed plugin types are whitelisted.
221 return true;
223 // plugin-types not specified.
224 return false;
227 } // namespace
229 bool ContentSecurityPolicyIsLegal(const std::string& policy) {
230 // We block these characters to prevent HTTP header injection when
231 // representing the content security policy as an HTTP header.
232 const char kBadChars[] = {',', '\r', '\n', '\0'};
234 return policy.find_first_of(kBadChars, 0, arraysize(kBadChars)) ==
235 std::string::npos;
238 std::string SanitizeContentSecurityPolicy(
239 const std::string& policy,
240 int options,
241 std::vector<InstallWarning>* warnings) {
242 // See http://www.w3.org/TR/CSP/#parse-a-csp-policy for parsing algorithm.
243 std::vector<std::string> directives;
244 base::SplitString(policy, ';', &directives);
246 DirectiveStatus default_src_status(kDefaultSrc);
247 DirectiveStatus script_src_status(kScriptSrc);
248 DirectiveStatus object_src_status(kObjectSrc);
250 bool allow_insecure_object_src =
251 AllowedToHaveInsecureObjectSrc(options, directives);
253 std::vector<std::string> sane_csp_parts;
254 std::vector<InstallWarning> default_src_csp_warnings;
255 for (size_t i = 0; i < directives.size(); ++i) {
256 std::string& input = directives[i];
257 base::StringTokenizer tokenizer(input, " \t\r\n");
258 if (!tokenizer.GetNext())
259 continue;
261 std::string directive_name = tokenizer.token();
262 base::StringToLowerASCII(&directive_name);
264 if (UpdateStatus(directive_name, &tokenizer, &default_src_status, options,
265 &sane_csp_parts, &default_src_csp_warnings))
266 continue;
267 if (UpdateStatus(directive_name, &tokenizer, &script_src_status, options,
268 &sane_csp_parts, warnings))
269 continue;
270 if (!allow_insecure_object_src &&
271 UpdateStatus(directive_name, &tokenizer, &object_src_status, options,
272 &sane_csp_parts, warnings))
273 continue;
275 // Pass the other CSP directives as-is without further validation.
276 sane_csp_parts.push_back(input + ";");
279 if (default_src_status.seen_in_policy) {
280 if (!script_src_status.seen_in_policy ||
281 !object_src_status.seen_in_policy) {
282 // Insecure values in default-src are only relevant if either script-src
283 // or object-src is omitted.
284 if (warnings)
285 warnings->insert(warnings->end(),
286 default_src_csp_warnings.begin(),
287 default_src_csp_warnings.end());
289 } else {
290 if (!script_src_status.seen_in_policy) {
291 sane_csp_parts.push_back(kScriptSrcDefaultDirective);
292 if (warnings)
293 warnings->push_back(CSPInstallWarning(ErrorUtils::FormatErrorMessage(
294 manifest_errors::kInvalidCSPMissingSecureSrc, kScriptSrc)));
296 if (!object_src_status.seen_in_policy && !allow_insecure_object_src) {
297 sane_csp_parts.push_back(kObjectSrcDefaultDirective);
298 if (warnings)
299 warnings->push_back(CSPInstallWarning(ErrorUtils::FormatErrorMessage(
300 manifest_errors::kInvalidCSPMissingSecureSrc, kObjectSrc)));
304 return base::JoinString(sane_csp_parts, " ");
307 bool ContentSecurityPolicyIsSandboxed(
308 const std::string& policy, Manifest::Type type) {
309 // See http://www.w3.org/TR/CSP/#parse-a-csp-policy for parsing algorithm.
310 std::vector<std::string> directives;
311 base::SplitString(policy, ';', &directives);
313 bool seen_sandbox = false;
315 for (size_t i = 0; i < directives.size(); ++i) {
316 std::string& input = directives[i];
317 base::StringTokenizer tokenizer(input, " \t\r\n");
318 if (!tokenizer.GetNext())
319 continue;
321 std::string directive_name = tokenizer.token();
322 base::StringToLowerASCII(&directive_name);
324 if (directive_name != kSandboxDirectiveName)
325 continue;
327 seen_sandbox = true;
329 while (tokenizer.GetNext()) {
330 std::string token = tokenizer.token();
331 base::StringToLowerASCII(&token);
333 // The same origin token negates the sandboxing.
334 if (token == kAllowSameOriginToken)
335 return false;
337 // Platform apps don't allow navigation.
338 if (type == Manifest::TYPE_PLATFORM_APP) {
339 if (token == kAllowTopNavigation)
340 return false;
345 return seen_sandbox;
348 } // namespace csp_validator
350 } // namespace extensions