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"
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
{
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
[] = {
42 "application/x-google-chrome-pdf",
46 struct DirectiveStatus
{
47 explicit DirectiveStatus(const char* name
)
48 : directive_name(name
), seen_in_policy(false) {}
50 const char* directive_name
;
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))
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
)
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
] == '*';
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
)
99 if (!is_wildcard_subdomain
|| !should_check_rcd
)
102 // Allow *.googleapis.com to be whitelisted for backwards-compatibility.
103 // (crbug.com/409952)
104 if (host
== "googleapis.com")
107 // Wildcards on subdomains of a TLD are not allowed.
108 size_t registry_length
= net::registry_controlled_domains::GetRegistryLength(
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
,
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
,
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
,
168 std::vector
<std::string
>* sane_csp_parts
,
169 std::vector
<InstallWarning
>* warnings
) {
170 if (directive_name
!= status
->directive_name
)
173 if (!status
->seen_in_policy
) {
174 status
->seen_in_policy
= true;
175 GetSecureDirectiveValues(directive_name
, tokenizer
, options
, sane_csp_parts
,
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
,
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
])
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(
201 const std::vector
<std::string
>& directives
) {
202 if (!(options
& OPTIONS_ALLOW_INSECURE_OBJECT_SRC
))
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())
210 if (!base::LowerCaseEqualsASCII(tokenizer
.token(), kPluginTypes
))
212 while (tokenizer
.GetNext()) {
213 if (!PluginTypeAllowed(tokenizer
.token()))
216 // All listed plugin types are whitelisted.
219 // plugin-types not specified.
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
)) ==
234 std::string
SanitizeContentSecurityPolicy(
235 const std::string
& policy
,
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())
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
))
263 if (UpdateStatus(directive_name
, &tokenizer
, &script_src_status
, options
,
264 &sane_csp_parts
, warnings
))
266 if (!allow_insecure_object_src
&&
267 UpdateStatus(directive_name
, &tokenizer
, &object_src_status
, options
,
268 &sane_csp_parts
, warnings
))
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.
281 warnings
->insert(warnings
->end(),
282 default_src_csp_warnings
.begin(),
283 default_src_csp_warnings
.end());
286 if (!script_src_status
.seen_in_policy
) {
287 sane_csp_parts
.push_back(kScriptSrcDefaultDirective
);
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
);
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())
317 std::string directive_name
= tokenizer
.token();
318 base::StringToLowerASCII(&directive_name
);
320 if (directive_name
!= kSandboxDirectiveName
)
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
)
333 // Platform apps don't allow navigation.
334 if (type
== Manifest::TYPE_PLATFORM_APP
) {
335 if (token
== kAllowTopNavigation
)
344 } // namespace csp_validator
346 } // namespace extensions