2 * Copyright (C) 2007 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
14 * its contributors may be used to endorse or promote products derived
15 * from this software without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
21 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 #include "SecurityOrigin.h"
34 #include "FileSystem.h"
36 #include "SchemeRegistry.h"
37 #include "SecurityPolicy.h"
38 #include "ThreadableBlobRegistry.h"
39 #include <wtf/MainThread.h>
40 #include <wtf/StdLibExtras.h>
41 #include <wtf/text/StringBuilder.h>
45 const int InvalidPort = 0;
46 const int MaxAllowedPort = 65535;
48 static bool schemeRequiresAuthority(const KURL& url)
50 // We expect URLs with these schemes to have authority components. If the
51 // URL lacks an authority component, we get concerned and mark the origin
53 return url.protocolIsInHTTPFamily() || url.protocolIs("ftp");
56 // Some URL schemes use nested URLs for their security context. For example,
57 // filesystem URLs look like the following:
59 // filesystem:http://example.com/temporary/path/to/file.png
61 // We're supposed to use "http://example.com" as the origin.
63 // Generally, we add URL schemes to this list when WebKit support them. For
64 // example, we don't include the "jar" scheme, even though Firefox understands
65 // that jar uses an inner URL for it's security origin.
67 static bool shouldUseInnerURL(const KURL& url)
70 if (url.protocolIs("blob"))
73 #if ENABLE(FILE_SYSTEM)
74 if (url.protocolIs("filesystem"))
81 // In general, extracting the inner URL varies by scheme. It just so happens
82 // that all the URL schemes we currently support that use inner URLs for their
83 // security origin can be parsed using this algorithm.
84 static KURL extractInnerURL(const KURL& url)
87 return *url.innerURL();
88 // FIXME: Update this callsite to use the innerURL member function when
89 // we finish implementing it.
90 return KURL(ParsedURLString, decodeURLEscapeSequences(url.path()));
93 static PassRefPtr<SecurityOrigin> getCachedOrigin(const KURL& url)
96 if (url.protocolIs("blob"))
97 return ThreadableBlobRegistry::getCachedOrigin(url);
102 static bool shouldTreatAsUniqueOrigin(const KURL& url)
107 // FIXME: Do we need to unwrap the URL further?
108 KURL innerURL = shouldUseInnerURL(url) ? extractInnerURL(url) : url;
110 // FIXME: Check whether innerURL is valid.
112 // For edge case URLs that were probably misparsed, make sure that the origin is unique.
113 // FIXME: Do we really need to do this? This looks to be a hack around a
114 // security bug in CFNetwork that might have been fixed.
115 if (schemeRequiresAuthority(innerURL) && innerURL.host().isEmpty())
118 // SchemeRegistry needs a lower case protocol because it uses HashMaps
119 // that assume the scheme has already been canonicalized.
120 String protocol = innerURL.protocol().lower();
122 if (SchemeRegistry::shouldTreatURLSchemeAsNoAccess(protocol))
125 // This is the common case.
129 SecurityOrigin::SecurityOrigin(const KURL& url)
130 : m_protocol(url.protocol().isNull() ? "" : url.protocol().lower())
131 , m_host(url.host().isNull() ? "" : url.host().lower())
134 , m_universalAccess(false)
135 , m_domainWasSetInDOM(false)
136 , m_enforceFilePathSeparation(false)
137 , m_needsDatabaseIdentifierQuirkForFiles(false)
139 // document.domain starts as m_host, but can be set by the DOM.
142 if (isDefaultPortForProtocol(m_port, m_protocol))
143 m_port = InvalidPort;
145 // By default, only local SecurityOrigins can load local resources.
146 m_canLoadLocalResources = isLocal();
148 if (m_canLoadLocalResources)
149 m_filePath = url.path(); // In case enforceFilePathSeparation() is called.
152 SecurityOrigin::SecurityOrigin()
156 , m_port(InvalidPort)
158 , m_universalAccess(false)
159 , m_domainWasSetInDOM(false)
160 , m_canLoadLocalResources(false)
161 , m_enforceFilePathSeparation(false)
162 , m_needsDatabaseIdentifierQuirkForFiles(false)
166 SecurityOrigin::SecurityOrigin(const SecurityOrigin* other)
167 : m_protocol(other->m_protocol.isolatedCopy())
168 , m_host(other->m_host.isolatedCopy())
169 , m_encodedHost(other->m_encodedHost.isolatedCopy())
170 , m_domain(other->m_domain.isolatedCopy())
171 , m_filePath(other->m_filePath.isolatedCopy())
172 , m_port(other->m_port)
173 , m_isUnique(other->m_isUnique)
174 , m_universalAccess(other->m_universalAccess)
175 , m_domainWasSetInDOM(other->m_domainWasSetInDOM)
176 , m_canLoadLocalResources(other->m_canLoadLocalResources)
177 , m_enforceFilePathSeparation(other->m_enforceFilePathSeparation)
178 , m_needsDatabaseIdentifierQuirkForFiles(other->m_needsDatabaseIdentifierQuirkForFiles)
182 PassRefPtr<SecurityOrigin> SecurityOrigin::create(const KURL& url)
184 RefPtr<SecurityOrigin> cachedOrigin = getCachedOrigin(url);
185 if (cachedOrigin.get())
188 if (shouldTreatAsUniqueOrigin(url)) {
189 RefPtr<SecurityOrigin> origin = adoptRef(new SecurityOrigin());
191 if (url.protocolIs("file")) {
192 // Unfortunately, we can't represent all unique origins exactly
193 // the same way because we need to produce a quirky database
194 // identifier for file URLs due to persistent storage in some
195 // embedders of WebKit.
196 origin->m_needsDatabaseIdentifierQuirkForFiles = true;
199 return origin.release();
202 if (shouldUseInnerURL(url))
203 return adoptRef(new SecurityOrigin(extractInnerURL(url)));
205 return adoptRef(new SecurityOrigin(url));
208 PassRefPtr<SecurityOrigin> SecurityOrigin::createUnique()
210 RefPtr<SecurityOrigin> origin = adoptRef(new SecurityOrigin());
211 ASSERT(origin->isUnique());
212 return origin.release();
215 PassRefPtr<SecurityOrigin> SecurityOrigin::isolatedCopy()
217 return adoptRef(new SecurityOrigin(this));
220 void SecurityOrigin::setDomainFromDOM(const String& newDomain)
222 m_domainWasSetInDOM = true;
223 m_domain = newDomain.lower();
226 bool SecurityOrigin::isSecure(const KURL& url)
228 // Invalid URLs are secure, as are URLs which have a secure protocol.
229 if (!url.isValid() || SchemeRegistry::shouldTreatURLSchemeAsSecure(url.protocol()))
232 // URLs that wrap inner URLs are secure if those inner URLs are secure.
233 if (shouldUseInnerURL(url) && SchemeRegistry::shouldTreatURLSchemeAsSecure(extractInnerURL(url).protocol()))
239 bool SecurityOrigin::canAccess(const SecurityOrigin* other) const
241 if (m_universalAccess)
247 if (isUnique() || other->isUnique())
250 // Here are two cases where we should permit access:
252 // 1) Neither document has set document.domain. In this case, we insist
253 // that the scheme, host, and port of the URLs match.
255 // 2) Both documents have set document.domain. In this case, we insist
256 // that the documents have set document.domain to the same value and
257 // that the scheme of the URLs match.
259 // This matches the behavior of Firefox 2 and Internet Explorer 6.
261 // Internet Explorer 7 and Opera 9 are more strict in that they require
262 // the port numbers to match when both pages have document.domain set.
264 // FIXME: Evaluate whether we can tighten this policy to require matched
267 // Opera 9 allows access when only one page has set document.domain, but
268 // this is a security vulnerability.
270 bool canAccess = false;
271 if (m_protocol == other->m_protocol) {
272 if (!m_domainWasSetInDOM && !other->m_domainWasSetInDOM) {
273 if (m_host == other->m_host && m_port == other->m_port)
275 } else if (m_domainWasSetInDOM && other->m_domainWasSetInDOM) {
276 if (m_domain == other->m_domain)
281 if (canAccess && isLocal())
282 canAccess = passesFileCheck(other);
287 bool SecurityOrigin::passesFileCheck(const SecurityOrigin* other) const
289 ASSERT(isLocal() && other->isLocal());
291 if (!m_enforceFilePathSeparation && !other->m_enforceFilePathSeparation)
294 return (m_filePath == other->m_filePath);
297 bool SecurityOrigin::canRequest(const KURL& url) const
299 if (m_universalAccess)
302 if (getCachedOrigin(url) == this)
308 RefPtr<SecurityOrigin> targetOrigin = SecurityOrigin::create(url);
310 if (targetOrigin->isUnique())
313 // We call isSameSchemeHostPort here instead of canAccess because we want
314 // to ignore document.domain effects.
315 if (isSameSchemeHostPort(targetOrigin.get()))
318 if (SecurityPolicy::isAccessWhiteListed(this, targetOrigin.get()))
324 bool SecurityOrigin::taintsCanvas(const KURL& url) const
329 // This function exists because we treat data URLs as having a unique origin,
330 // contrary to the current (9/19/2009) draft of the HTML5 specification.
331 // We still want to let folks paint data URLs onto untainted canvases, so
332 // we special case data URLs below. If we change to match HTML5 w.r.t.
333 // data URL security, then we can remove this function in favor of
335 if (url.protocolIsData())
341 bool SecurityOrigin::canReceiveDragData(const SecurityOrigin* dragInitiator) const
343 if (this == dragInitiator)
346 return canAccess(dragInitiator);
349 // This is a hack to allow keep navigation to http/https feeds working. To remove this
350 // we need to introduce new API akin to registerURLSchemeAsLocal, that registers a
351 // protocols navigation policy.
352 // feed(|s|search): is considered a 'nesting' scheme by embedders that support it, so it can be
353 // local or remote depending on what is nested. Currently we just check if we are nesting
354 // http or https, otherwise we ignore the nesting for the purpose of a security check. We need
355 // a facility for registering nesting schemes, and some generalized logic for them.
356 // This function should be removed as an outcome of https://bugs.webkit.org/show_bug.cgi?id=69196
357 static bool isFeedWithNestedProtocolInHTTPFamily(const KURL& url)
359 const String& urlString = url.string();
360 if (!urlString.startsWith("feed", false))
363 return urlString.startsWith("feed://", false)
364 || urlString.startsWith("feed:http:", false) || urlString.startsWith("feed:https:", false)
365 || urlString.startsWith("feeds:http:", false) || urlString.startsWith("feeds:https:", false)
366 || urlString.startsWith("feedsearch:http:", false) || urlString.startsWith("feedsearch:https:", false);
369 bool SecurityOrigin::canDisplay(const KURL& url) const
371 if (m_universalAccess)
374 String protocol = url.protocol().lower();
376 if (isFeedWithNestedProtocolInHTTPFamily(url))
379 if (SchemeRegistry::canDisplayOnlyIfCanRequest(protocol))
380 return canRequest(url);
382 if (SchemeRegistry::shouldTreatURLSchemeAsDisplayIsolated(protocol))
383 return m_protocol == protocol || SecurityPolicy::isAccessToURLWhiteListed(this, url);
385 if (SecurityPolicy::restrictAccessToLocal() && SchemeRegistry::shouldTreatURLSchemeAsLocal(protocol))
386 return canLoadLocalResources() || SecurityPolicy::isAccessToURLWhiteListed(this, url);
391 SecurityOrigin::Policy SecurityOrigin::canShowNotifications() const
393 if (m_universalAccess)
400 void SecurityOrigin::grantLoadLocalResources()
402 // Granting privileges to some, but not all, documents in a SecurityOrigin
403 // is a security hazard because the documents without the privilege can
404 // obtain the privilege by injecting script into the documents that have
405 // been granted the privilege.
407 // To be backwards compatible with older versions of WebKit, we also use
408 // this function to grant the ability to load local resources to documents
409 // loaded with SubstituteData.
410 ASSERT(isUnique() || SecurityPolicy::allowSubstituteDataAccessToLocal());
411 m_canLoadLocalResources = true;
414 void SecurityOrigin::grantUniversalAccess()
416 m_universalAccess = true;
419 void SecurityOrigin::enforceFilePathSeparation()
422 m_enforceFilePathSeparation = true;
425 bool SecurityOrigin::isLocal() const
427 return SchemeRegistry::shouldTreatURLSchemeAsLocal(m_protocol);
430 String SecurityOrigin::toString() const
434 if (m_protocol == "file" && m_enforceFilePathSeparation)
436 return toRawString();
439 String SecurityOrigin::toRawString() const
441 if (m_protocol == "file")
444 StringBuilder result;
445 result.reserveCapacity(m_protocol.length() + m_host.length() + 10);
446 result.append(m_protocol);
447 result.append("://");
448 result.append(m_host);
452 result.append(String::number(m_port));
455 return result.toString();
458 PassRefPtr<SecurityOrigin> SecurityOrigin::createFromString(const String& originString)
460 return SecurityOrigin::create(KURL(KURL(), originString));
463 static const char SeparatorCharacter = '_';
465 PassRefPtr<SecurityOrigin> SecurityOrigin::createFromDatabaseIdentifier(const String& databaseIdentifier)
467 // Make sure there's a first separator
468 size_t separator1 = databaseIdentifier.find(SeparatorCharacter);
469 if (separator1 == notFound)
470 return create(KURL());
472 // Make sure there's a second separator
473 size_t separator2 = databaseIdentifier.reverseFind(SeparatorCharacter);
474 if (separator2 == notFound)
475 return create(KURL());
477 // Ensure there were at least 2 separator characters. Some hostnames on intranets have
478 // underscores in them, so we'll assume that any additional underscores are part of the host.
479 if (separator1 == separator2)
480 return create(KURL());
482 // Make sure the port section is a valid port number or doesn't exist
484 int port = databaseIdentifier.right(databaseIdentifier.length() - separator2 - 1).toInt(&portOkay);
485 bool portAbsent = (separator2 == databaseIdentifier.length() - 1);
486 if (!(portOkay || portAbsent))
487 return create(KURL());
489 if (port < 0 || port > MaxAllowedPort)
490 return create(KURL());
492 // Split out the 3 sections of data
493 String protocol = databaseIdentifier.substring(0, separator1);
494 String host = databaseIdentifier.substring(separator1 + 1, separator2 - separator1 - 1);
496 host = decodeURLEscapeSequences(host);
497 return create(KURL(KURL(), protocol + "://" + host + ":" + String::number(port)));
500 PassRefPtr<SecurityOrigin> SecurityOrigin::create(const String& protocol, const String& host, int port)
502 if (port < 0 || port > MaxAllowedPort)
504 String decodedHost = decodeURLEscapeSequences(host);
505 return create(KURL(KURL(), protocol + "://" + host + ":" + String::number(port)));
508 String SecurityOrigin::databaseIdentifier() const
510 // Historically, we've used the following (somewhat non-sensical) string
511 // for the databaseIdentifier of local files. We used to compute this
512 // string because of a bug in how we handled the scheme for file URLs.
513 // Now that we've fixed that bug, we still need to produce this string
514 // to avoid breaking existing persistent state.
515 if (m_needsDatabaseIdentifierQuirkForFiles)
518 String separatorString(&SeparatorCharacter, 1);
520 if (m_encodedHost.isEmpty())
521 m_encodedHost = encodeForFileName(m_host);
523 return m_protocol + separatorString + m_encodedHost + separatorString + String::number(m_port);
526 bool SecurityOrigin::equal(const SecurityOrigin* other) const
531 if (!isSameSchemeHostPort(other))
534 if (m_domainWasSetInDOM != other->m_domainWasSetInDOM)
537 if (m_domainWasSetInDOM && m_domain != other->m_domain)
543 bool SecurityOrigin::isSameSchemeHostPort(const SecurityOrigin* other) const
545 if (m_host != other->m_host)
548 if (m_protocol != other->m_protocol)
551 if (m_port != other->m_port)
554 if (isLocal() && !passesFileCheck(other))
560 } // namespace WebCore