Merge "[CherryPick] Refactoring: Move the content of HTMLInputElement::subtreeHasChan...
[framework/web/webkit-efl.git] / Source / WebCore / page / SecurityOrigin.cpp
1 /*
2  * Copyright (C) 2007 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
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.
16  *
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.
27  */
28
29 #include "config.h"
30 #include "SecurityOrigin.h"
31
32 #include "BlobURL.h"
33 #include "Document.h"
34 #include "FileSystem.h"
35 #include "KURL.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>
42
43 namespace WebCore {
44
45 const int InvalidPort = 0;
46 const int MaxAllowedPort = 65535;
47
48 static bool schemeRequiresAuthority(const KURL& url)
49 {
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
52     // as unique.
53     return url.protocolIsInHTTPFamily() || url.protocolIs("ftp");
54 }
55
56 // Some URL schemes use nested URLs for their security context. For example,
57 // filesystem URLs look like the following:
58 //
59 //   filesystem:http://example.com/temporary/path/to/file.png
60 //
61 // We're supposed to use "http://example.com" as the origin.
62 //
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.
66 //
67 static bool shouldUseInnerURL(const KURL& url)
68 {
69 #if ENABLE(BLOB)
70     if (url.protocolIs("blob"))
71         return true;
72 #endif
73 #if ENABLE(FILE_SYSTEM)
74     if (url.protocolIs("filesystem"))
75         return true;
76 #endif
77     UNUSED_PARAM(url);
78     return false;
79 }
80
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)
85 {
86     if (url.innerURL())
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()));
91 }
92
93 static PassRefPtr<SecurityOrigin> getCachedOrigin(const KURL& url)
94 {
95 #if ENABLE(BLOB)
96     if (url.protocolIs("blob"))
97         return ThreadableBlobRegistry::getCachedOrigin(url);
98 #endif
99     return 0;
100 }
101
102 static bool shouldTreatAsUniqueOrigin(const KURL& url)
103 {
104     if (!url.isValid())
105         return true;
106
107     // FIXME: Do we need to unwrap the URL further?
108     KURL innerURL = shouldUseInnerURL(url) ? extractInnerURL(url) : url;
109
110     // FIXME: Check whether innerURL is valid.
111
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())
116         return true;
117
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();
121
122     if (SchemeRegistry::shouldTreatURLSchemeAsNoAccess(protocol))
123         return true;
124
125     // This is the common case.
126     return false;
127 }
128
129 SecurityOrigin::SecurityOrigin(const KURL& url)
130     : m_protocol(url.protocol().isNull() ? "" : url.protocol().lower())
131     , m_host(url.host().isNull() ? "" : url.host().lower())
132     , m_port(url.port())
133     , m_isUnique(false)
134     , m_universalAccess(false)
135     , m_domainWasSetInDOM(false)
136     , m_enforceFilePathSeparation(false)
137     , m_needsDatabaseIdentifierQuirkForFiles(false)
138 {
139     // document.domain starts as m_host, but can be set by the DOM.
140     m_domain = m_host;
141
142     if (isDefaultPortForProtocol(m_port, m_protocol))
143         m_port = InvalidPort;
144
145     // By default, only local SecurityOrigins can load local resources.
146     m_canLoadLocalResources = isLocal();
147
148     if (m_canLoadLocalResources)
149         m_filePath = url.path(); // In case enforceFilePathSeparation() is called.
150 }
151
152 SecurityOrigin::SecurityOrigin()
153     : m_protocol("")
154     , m_host("")
155     , m_domain("")
156     , m_port(InvalidPort)
157     , m_isUnique(true)
158     , m_universalAccess(false)
159     , m_domainWasSetInDOM(false)
160     , m_canLoadLocalResources(false)
161     , m_enforceFilePathSeparation(false)
162     , m_needsDatabaseIdentifierQuirkForFiles(false)
163 {
164 }
165
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)
179 {
180 }
181
182 PassRefPtr<SecurityOrigin> SecurityOrigin::create(const KURL& url)
183 {
184     RefPtr<SecurityOrigin> cachedOrigin = getCachedOrigin(url);
185     if (cachedOrigin.get())
186         return cachedOrigin;
187
188     if (shouldTreatAsUniqueOrigin(url)) {
189         RefPtr<SecurityOrigin> origin = adoptRef(new SecurityOrigin());
190
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;
197         }
198
199         return origin.release();
200     }
201
202     if (shouldUseInnerURL(url))
203         return adoptRef(new SecurityOrigin(extractInnerURL(url)));
204
205     return adoptRef(new SecurityOrigin(url));
206 }
207
208 PassRefPtr<SecurityOrigin> SecurityOrigin::createUnique()
209 {
210     RefPtr<SecurityOrigin> origin = adoptRef(new SecurityOrigin());
211     ASSERT(origin->isUnique());
212     return origin.release();
213 }
214
215 PassRefPtr<SecurityOrigin> SecurityOrigin::isolatedCopy()
216 {
217     return adoptRef(new SecurityOrigin(this));
218 }
219
220 void SecurityOrigin::setDomainFromDOM(const String& newDomain)
221 {
222     m_domainWasSetInDOM = true;
223     m_domain = newDomain.lower();
224 }
225
226 bool SecurityOrigin::isSecure(const KURL& url)
227 {
228     // Invalid URLs are secure, as are URLs which have a secure protocol.
229     if (!url.isValid() || SchemeRegistry::shouldTreatURLSchemeAsSecure(url.protocol()))
230         return true;
231
232     // URLs that wrap inner URLs are secure if those inner URLs are secure.
233     if (shouldUseInnerURL(url) && SchemeRegistry::shouldTreatURLSchemeAsSecure(extractInnerURL(url).protocol()))
234         return true;
235
236     return false;
237 }
238
239 bool SecurityOrigin::canAccess(const SecurityOrigin* other) const
240 {
241     if (m_universalAccess)
242         return true;
243
244     if (this == other)
245         return true;
246
247     if (isUnique() || other->isUnique())
248         return false;
249
250     // Here are two cases where we should permit access:
251     //
252     // 1) Neither document has set document.domain. In this case, we insist
253     //    that the scheme, host, and port of the URLs match.
254     //
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.
258     //
259     // This matches the behavior of Firefox 2 and Internet Explorer 6.
260     //
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.
263     //
264     // FIXME: Evaluate whether we can tighten this policy to require matched
265     //        port numbers.
266     //
267     // Opera 9 allows access when only one page has set document.domain, but
268     // this is a security vulnerability.
269
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)
274                 canAccess = true;
275         } else if (m_domainWasSetInDOM && other->m_domainWasSetInDOM) {
276             if (m_domain == other->m_domain)
277                 canAccess = true;
278         }
279     }
280
281     if (canAccess && isLocal())
282        canAccess = passesFileCheck(other);
283
284     return canAccess;
285 }
286
287 bool SecurityOrigin::passesFileCheck(const SecurityOrigin* other) const
288 {
289     ASSERT(isLocal() && other->isLocal());
290
291     if (!m_enforceFilePathSeparation && !other->m_enforceFilePathSeparation)
292         return true;
293
294     return (m_filePath == other->m_filePath);
295 }
296
297 bool SecurityOrigin::canRequest(const KURL& url) const
298 {
299     if (m_universalAccess)
300         return true;
301
302     if (getCachedOrigin(url) == this)
303         return true;
304
305     if (isUnique())
306         return false;
307
308     RefPtr<SecurityOrigin> targetOrigin = SecurityOrigin::create(url);
309
310     if (targetOrigin->isUnique())
311         return false;
312
313     // We call isSameSchemeHostPort here instead of canAccess because we want
314     // to ignore document.domain effects.
315     if (isSameSchemeHostPort(targetOrigin.get()))
316         return true;
317
318     if (SecurityPolicy::isAccessWhiteListed(this, targetOrigin.get()))
319         return true;
320
321     return false;
322 }
323
324 bool SecurityOrigin::taintsCanvas(const KURL& url) const
325 {
326     if (canRequest(url))
327         return false;
328
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
334     // !canRequest.
335     if (url.protocolIsData())
336         return false;
337
338     return true;
339 }
340
341 bool SecurityOrigin::canReceiveDragData(const SecurityOrigin* dragInitiator) const
342 {
343     if (this == dragInitiator)
344         return true;
345
346     return canAccess(dragInitiator);  
347 }
348
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)
358 {
359     const String& urlString = url.string();
360     if (!urlString.startsWith("feed", false))
361         return false;
362
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);
367 }
368
369 bool SecurityOrigin::canDisplay(const KURL& url) const
370 {
371     if (m_universalAccess)
372         return true;
373
374     String protocol = url.protocol().lower();
375
376     if (isFeedWithNestedProtocolInHTTPFamily(url))
377         return true;
378
379     if (SchemeRegistry::canDisplayOnlyIfCanRequest(protocol))
380         return canRequest(url);
381
382     if (SchemeRegistry::shouldTreatURLSchemeAsDisplayIsolated(protocol))
383         return m_protocol == protocol || SecurityPolicy::isAccessToURLWhiteListed(this, url);
384
385     if (SecurityPolicy::restrictAccessToLocal() && SchemeRegistry::shouldTreatURLSchemeAsLocal(protocol))
386         return canLoadLocalResources() || SecurityPolicy::isAccessToURLWhiteListed(this, url);
387
388     return true;
389 }
390
391 SecurityOrigin::Policy SecurityOrigin::canShowNotifications() const
392 {
393     if (m_universalAccess)
394         return AlwaysAllow;
395     if (isUnique())
396         return AlwaysDeny;
397     return Ask;
398 }
399
400 void SecurityOrigin::grantLoadLocalResources()
401 {
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.
406     //
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;
412 }
413
414 void SecurityOrigin::grantUniversalAccess()
415 {
416     m_universalAccess = true;
417 }
418
419 void SecurityOrigin::enforceFilePathSeparation()
420 {
421     ASSERT(isLocal());
422     m_enforceFilePathSeparation = true;
423 }
424
425 bool SecurityOrigin::isLocal() const
426 {
427     return SchemeRegistry::shouldTreatURLSchemeAsLocal(m_protocol);
428 }
429
430 String SecurityOrigin::toString() const
431 {
432     if (isUnique())
433         return "null";
434     if (m_protocol == "file" && m_enforceFilePathSeparation)
435         return "null";
436     return toRawString();
437 }
438
439 String SecurityOrigin::toRawString() const
440 {
441     if (m_protocol == "file")
442         return "file://";
443
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);
449
450     if (m_port) {
451         result.append(":");
452         result.append(String::number(m_port));
453     }
454
455     return result.toString();
456 }
457
458 PassRefPtr<SecurityOrigin> SecurityOrigin::createFromString(const String& originString)
459 {
460     return SecurityOrigin::create(KURL(KURL(), originString));
461 }
462
463 static const char SeparatorCharacter = '_';
464
465 PassRefPtr<SecurityOrigin> SecurityOrigin::createFromDatabaseIdentifier(const String& databaseIdentifier)
466
467     // Make sure there's a first separator
468     size_t separator1 = databaseIdentifier.find(SeparatorCharacter);
469     if (separator1 == notFound)
470         return create(KURL());
471         
472     // Make sure there's a second separator
473     size_t separator2 = databaseIdentifier.reverseFind(SeparatorCharacter);
474     if (separator2 == notFound)
475         return create(KURL());
476         
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());
481         
482     // Make sure the port section is a valid port number or doesn't exist
483     bool portOkay;
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());
488     
489     if (port < 0 || port > MaxAllowedPort)
490         return create(KURL());
491         
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);
495     
496     host = decodeURLEscapeSequences(host);
497     return create(KURL(KURL(), protocol + "://" + host + ":" + String::number(port)));
498 }
499
500 PassRefPtr<SecurityOrigin> SecurityOrigin::create(const String& protocol, const String& host, int port)
501 {
502     if (port < 0 || port > MaxAllowedPort)
503         createUnique();
504     String decodedHost = decodeURLEscapeSequences(host);
505     return create(KURL(KURL(), protocol + "://" + host + ":" + String::number(port)));
506 }
507
508 String SecurityOrigin::databaseIdentifier() const 
509 {
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)
516         return "file__0";
517
518     String separatorString(&SeparatorCharacter, 1);
519
520     if (m_encodedHost.isEmpty())
521         m_encodedHost = encodeForFileName(m_host);
522
523     return m_protocol + separatorString + m_encodedHost + separatorString + String::number(m_port); 
524 }
525
526 bool SecurityOrigin::equal(const SecurityOrigin* other) const 
527 {
528     if (other == this)
529         return true;
530     
531     if (!isSameSchemeHostPort(other))
532         return false;
533
534     if (m_domainWasSetInDOM != other->m_domainWasSetInDOM)
535         return false;
536
537     if (m_domainWasSetInDOM && m_domain != other->m_domain)
538         return false;
539
540     return true;
541 }
542
543 bool SecurityOrigin::isSameSchemeHostPort(const SecurityOrigin* other) const 
544 {
545     if (m_host != other->m_host)
546         return false;
547
548     if (m_protocol != other->m_protocol)
549         return false;
550
551     if (m_port != other->m_port)
552         return false;
553
554     if (isLocal() && !passesFileCheck(other))
555         return false;
556
557     return true;
558 }
559
560 } // namespace WebCore