1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3  * License, v. 2.0. If a copy of the MPL was not distributed with this
4  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 
6 #include "base/basictypes.h"
7 #include "mozilla/ArrayUtils.h"
8 
9 #include "nsAboutProtocolHandler.h"
10 #include "nsIURI.h"
11 #include "nsIAboutModule.h"
12 #include "nsString.h"
13 #include "nsNetCID.h"
14 #include "nsAboutProtocolUtils.h"
15 #include "nsError.h"
16 #include "nsNetUtil.h"
17 #include "nsIObjectInputStream.h"
18 #include "nsIObjectOutputStream.h"
19 #include "nsIWritablePropertyBag2.h"
20 #include "nsIChannel.h"
21 #include "nsIScriptError.h"
22 #include "nsIClassInfoImpl.h"
23 
24 #include "mozilla/ipc/URIUtils.h"
25 
26 namespace mozilla {
27 namespace net {
28 
29 static NS_DEFINE_CID(kSimpleURICID, NS_SIMPLEURI_CID);
30 static NS_DEFINE_CID(kNestedAboutURICID, NS_NESTEDABOUTURI_CID);
31 
IsSafeForUntrustedContent(nsIAboutModule * aModule,nsIURI * aURI)32 static bool IsSafeForUntrustedContent(nsIAboutModule* aModule, nsIURI* aURI) {
33   uint32_t flags;
34   nsresult rv = aModule->GetURIFlags(aURI, &flags);
35   NS_ENSURE_SUCCESS(rv, false);
36 
37   return (flags & nsIAboutModule::URI_SAFE_FOR_UNTRUSTED_CONTENT) != 0;
38 }
39 
IsSafeToLinkForUntrustedContent(nsIURI * aURI)40 static bool IsSafeToLinkForUntrustedContent(nsIURI* aURI) {
41   nsAutoCString path;
42   aURI->GetPathQueryRef(path);
43 
44   int32_t f = path.FindChar('#');
45   if (f >= 0) {
46     path.SetLength(f);
47   }
48 
49   f = path.FindChar('?');
50   if (f >= 0) {
51     path.SetLength(f);
52   }
53 
54   ToLowerCase(path);
55 
56   // The about modules for these URL types have the
57   // URI_SAFE_FOR_UNTRUSTED_CONTENT and MAKE_LINKABLE flags set.
58   return path.EqualsLiteral("blank") || path.EqualsLiteral("logo") ||
59          path.EqualsLiteral("srcdoc");
60 }
61 
62 ////////////////////////////////////////////////////////////////////////////////
63 
NS_IMPL_ISUPPORTS(nsAboutProtocolHandler,nsIProtocolHandler,nsIProtocolHandlerWithDynamicFlags,nsISupportsWeakReference)64 NS_IMPL_ISUPPORTS(nsAboutProtocolHandler, nsIProtocolHandler,
65                   nsIProtocolHandlerWithDynamicFlags, nsISupportsWeakReference)
66 
67 ////////////////////////////////////////////////////////////////////////////////
68 // nsIProtocolHandler methods:
69 
70 NS_IMETHODIMP
71 nsAboutProtocolHandler::GetScheme(nsACString& result) {
72   result.AssignLiteral("about");
73   return NS_OK;
74 }
75 
76 NS_IMETHODIMP
GetDefaultPort(int32_t * result)77 nsAboutProtocolHandler::GetDefaultPort(int32_t* result) {
78   *result = -1;  // no port for about: URLs
79   return NS_OK;
80 }
81 
82 NS_IMETHODIMP
GetProtocolFlags(uint32_t * result)83 nsAboutProtocolHandler::GetProtocolFlags(uint32_t* result) {
84   *result = URI_NORELATIVE | URI_NOAUTH | URI_DANGEROUS_TO_LOAD |
85             URI_SCHEME_NOT_SELF_LINKABLE;
86   return NS_OK;
87 }
88 
89 NS_IMETHODIMP
GetFlagsForURI(nsIURI * aURI,uint32_t * aFlags)90 nsAboutProtocolHandler::GetFlagsForURI(nsIURI* aURI, uint32_t* aFlags) {
91   // First use the default (which is "unsafe for content"):
92   GetProtocolFlags(aFlags);
93 
94   // Now try to see if this URI overrides the default:
95   nsCOMPtr<nsIAboutModule> aboutMod;
96   nsresult rv = NS_GetAboutModule(aURI, getter_AddRefs(aboutMod));
97   if (NS_FAILED(rv)) {
98     // Swallow this and just tell the consumer the default:
99     return NS_OK;
100   }
101   uint32_t aboutModuleFlags = 0;
102   rv = aboutMod->GetURIFlags(aURI, &aboutModuleFlags);
103   // This should never happen, so pass back the error:
104   NS_ENSURE_SUCCESS(rv, rv);
105 
106   // Secure (https) pages can load safe about pages without becoming
107   // mixed content.
108   if (aboutModuleFlags & nsIAboutModule::URI_SAFE_FOR_UNTRUSTED_CONTENT) {
109     *aFlags |= URI_IS_POTENTIALLY_TRUSTWORTHY;
110     // about: pages can only be loaded by unprivileged principals
111     // if they are marked as LINKABLE
112     if (aboutModuleFlags & nsIAboutModule::MAKE_LINKABLE) {
113       // Replace URI_DANGEROUS_TO_LOAD with URI_LOADABLE_BY_ANYONE.
114       *aFlags &= ~URI_DANGEROUS_TO_LOAD;
115       *aFlags |= URI_LOADABLE_BY_ANYONE;
116     }
117   }
118   return NS_OK;
119 }
120 
121 // static
CreateNewURI(const nsACString & aSpec,const char * aCharset,nsIURI * aBaseURI,nsIURI ** aResult)122 nsresult nsAboutProtocolHandler::CreateNewURI(const nsACString& aSpec,
123                                               const char* aCharset,
124                                               nsIURI* aBaseURI,
125                                               nsIURI** aResult) {
126   *aResult = nullptr;
127   nsresult rv;
128 
129   // Use a simple URI to parse out some stuff first
130   nsCOMPtr<nsIURI> url;
131   rv = NS_MutateURI(new nsSimpleURI::Mutator()).SetSpec(aSpec).Finalize(url);
132 
133   if (NS_FAILED(rv)) {
134     return rv;
135   }
136 
137   if (IsSafeToLinkForUntrustedContent(url)) {
138     // We need to indicate that this baby is safe.  Use an inner URI that
139     // no one but the security manager will see.  Make sure to preserve our
140     // path, in case someone decides to hardcode checks for particular
141     // about: URIs somewhere.
142     nsAutoCString spec;
143     rv = url->GetPathQueryRef(spec);
144     NS_ENSURE_SUCCESS(rv, rv);
145 
146     spec.InsertLiteral("moz-safe-about:", 0);
147 
148     nsCOMPtr<nsIURI> inner;
149     rv = NS_NewURI(getter_AddRefs(inner), spec);
150     NS_ENSURE_SUCCESS(rv, rv);
151 
152     nsCOMPtr<nsIURI> base(aBaseURI);
153     rv = NS_MutateURI(new nsNestedAboutURI::Mutator())
154              .Apply(NS_MutatorMethod(&nsINestedAboutURIMutator::InitWithBase,
155                                      inner, base))
156              .SetSpec(aSpec)
157              .Finalize(url);
158     NS_ENSURE_SUCCESS(rv, rv);
159   }
160 
161   url.swap(*aResult);
162   return NS_OK;
163 }
164 
165 NS_IMETHODIMP
NewChannel(nsIURI * uri,nsILoadInfo * aLoadInfo,nsIChannel ** result)166 nsAboutProtocolHandler::NewChannel(nsIURI* uri, nsILoadInfo* aLoadInfo,
167                                    nsIChannel** result) {
168   NS_ENSURE_ARG_POINTER(uri);
169 
170   // about:what you ask?
171   nsCOMPtr<nsIAboutModule> aboutMod;
172   nsresult rv = NS_GetAboutModule(uri, getter_AddRefs(aboutMod));
173 
174   nsAutoCString path;
175   nsresult rv2 = NS_GetAboutModuleName(uri, path);
176   if (NS_SUCCEEDED(rv2) && path.EqualsLiteral("srcdoc")) {
177     // about:srcdoc is meant to be unresolvable, yet is included in the
178     // about lookup tables so that it can pass security checks when used in
179     // a srcdoc iframe.  To ensure that it stays unresolvable, we pretend
180     // that it doesn't exist.
181     rv = NS_ERROR_FACTORY_NOT_REGISTERED;
182   }
183 
184   if (NS_SUCCEEDED(rv)) {
185     // The standard return case:
186     rv = aboutMod->NewChannel(uri, aLoadInfo, result);
187     if (NS_SUCCEEDED(rv)) {
188       // Not all implementations of nsIAboutModule::NewChannel()
189       // set the LoadInfo on the newly created channel yet, as
190       // an interim solution we set the LoadInfo here if not
191       // available on the channel. Bug 1087720
192       nsCOMPtr<nsILoadInfo> loadInfo = (*result)->LoadInfo();
193       if (aLoadInfo != loadInfo) {
194         NS_ASSERTION(false,
195                      "nsIAboutModule->newChannel(aURI, aLoadInfo) needs to "
196                      "set LoadInfo");
197         AutoTArray<nsString, 2> params = {
198             u"nsIAboutModule->newChannel(aURI)"_ns,
199             u"nsIAboutModule->newChannel(aURI, aLoadInfo)"_ns};
200         nsContentUtils::ReportToConsole(
201             nsIScriptError::warningFlag, "Security by Default"_ns,
202             nullptr,  // aDocument
203             nsContentUtils::eNECKO_PROPERTIES, "APIDeprecationWarning", params);
204         (*result)->SetLoadInfo(aLoadInfo);
205       }
206 
207       // If this URI is safe for untrusted content, enforce that its
208       // principal be based on the channel's originalURI by setting the
209       // owner to null.
210       // Note: this relies on aboutMod's newChannel implementation
211       // having set the proper originalURI, which probably isn't ideal.
212       if (IsSafeForUntrustedContent(aboutMod, uri)) {
213         (*result)->SetOwner(nullptr);
214       }
215 
216       RefPtr<nsNestedAboutURI> aboutURI;
217       nsresult rv2 =
218           uri->QueryInterface(kNestedAboutURICID, getter_AddRefs(aboutURI));
219       if (NS_SUCCEEDED(rv2) && aboutURI->GetBaseURI()) {
220         nsCOMPtr<nsIWritablePropertyBag2> writableBag =
221             do_QueryInterface(*result);
222         if (writableBag) {
223           writableBag->SetPropertyAsInterface(u"baseURI"_ns,
224                                               aboutURI->GetBaseURI());
225         }
226       }
227     }
228     return rv;
229   }
230 
231   // mumble...
232 
233   if (rv == NS_ERROR_FACTORY_NOT_REGISTERED) {
234     // This looks like an about: we don't know about.  Convert
235     // this to an invalid URI error.
236     rv = NS_ERROR_MALFORMED_URI;
237   }
238 
239   return rv;
240 }
241 
242 NS_IMETHODIMP
AllowPort(int32_t port,const char * scheme,bool * _retval)243 nsAboutProtocolHandler::AllowPort(int32_t port, const char* scheme,
244                                   bool* _retval) {
245   // don't override anything.
246   *_retval = false;
247   return NS_OK;
248 }
249 
250 ////////////////////////////////////////////////////////////////////////////////
251 // Safe about protocol handler impl
252 
NS_IMPL_ISUPPORTS(nsSafeAboutProtocolHandler,nsIProtocolHandler,nsISupportsWeakReference)253 NS_IMPL_ISUPPORTS(nsSafeAboutProtocolHandler, nsIProtocolHandler,
254                   nsISupportsWeakReference)
255 
256 // nsIProtocolHandler methods:
257 
258 NS_IMETHODIMP
259 nsSafeAboutProtocolHandler::GetScheme(nsACString& result) {
260   result.AssignLiteral("moz-safe-about");
261   return NS_OK;
262 }
263 
264 NS_IMETHODIMP
GetDefaultPort(int32_t * result)265 nsSafeAboutProtocolHandler::GetDefaultPort(int32_t* result) {
266   *result = -1;  // no port for moz-safe-about: URLs
267   return NS_OK;
268 }
269 
270 NS_IMETHODIMP
GetProtocolFlags(uint32_t * result)271 nsSafeAboutProtocolHandler::GetProtocolFlags(uint32_t* result) {
272   *result = URI_NORELATIVE | URI_NOAUTH | URI_LOADABLE_BY_ANYONE |
273             URI_IS_POTENTIALLY_TRUSTWORTHY;
274   return NS_OK;
275 }
276 
277 NS_IMETHODIMP
NewChannel(nsIURI * uri,nsILoadInfo * aLoadInfo,nsIChannel ** result)278 nsSafeAboutProtocolHandler::NewChannel(nsIURI* uri, nsILoadInfo* aLoadInfo,
279                                        nsIChannel** result) {
280   *result = nullptr;
281   return NS_ERROR_NOT_AVAILABLE;
282 }
283 
284 NS_IMETHODIMP
AllowPort(int32_t port,const char * scheme,bool * _retval)285 nsSafeAboutProtocolHandler::AllowPort(int32_t port, const char* scheme,
286                                       bool* _retval) {
287   // don't override anything.
288   *_retval = false;
289   return NS_OK;
290 }
291 
292 ////////////////////////////////////////////////////////////
293 // nsNestedAboutURI implementation
294 
295 NS_IMPL_CLASSINFO(nsNestedAboutURI, nullptr, nsIClassInfo::THREADSAFE,
296                   NS_NESTEDABOUTURI_CID);
297 // Empty CI getter. We only need nsIClassInfo for Serialization
298 NS_IMPL_CI_INTERFACE_GETTER0(nsNestedAboutURI)
299 
300 NS_INTERFACE_MAP_BEGIN(nsNestedAboutURI)
301   if (aIID.Equals(kNestedAboutURICID)) {
302     foundInterface = static_cast<nsIURI*>(this);
303   } else
304     NS_IMPL_QUERY_CLASSINFO(nsNestedAboutURI)
NS_INTERFACE_MAP_END_INHERITING(nsSimpleNestedURI)305 NS_INTERFACE_MAP_END_INHERITING(nsSimpleNestedURI)
306 
307 // nsISerializable
308 
309 NS_IMETHODIMP
310 nsNestedAboutURI::Read(nsIObjectInputStream* aStream) {
311   MOZ_ASSERT_UNREACHABLE("Use nsIURIMutator.read() instead");
312   return NS_ERROR_NOT_IMPLEMENTED;
313 }
314 
ReadPrivate(nsIObjectInputStream * aStream)315 nsresult nsNestedAboutURI::ReadPrivate(nsIObjectInputStream* aStream) {
316   nsresult rv = nsSimpleNestedURI::ReadPrivate(aStream);
317   if (NS_FAILED(rv)) return rv;
318 
319   bool haveBase;
320   rv = aStream->ReadBoolean(&haveBase);
321   if (NS_FAILED(rv)) return rv;
322 
323   if (haveBase) {
324     nsCOMPtr<nsISupports> supports;
325     rv = aStream->ReadObject(true, getter_AddRefs(supports));
326     if (NS_FAILED(rv)) return rv;
327 
328     mBaseURI = do_QueryInterface(supports, &rv);
329     if (NS_FAILED(rv)) return rv;
330   }
331 
332   return NS_OK;
333 }
334 
335 NS_IMETHODIMP
Write(nsIObjectOutputStream * aStream)336 nsNestedAboutURI::Write(nsIObjectOutputStream* aStream) {
337   nsresult rv = nsSimpleNestedURI::Write(aStream);
338   if (NS_FAILED(rv)) return rv;
339 
340   rv = aStream->WriteBoolean(mBaseURI != nullptr);
341   if (NS_FAILED(rv)) return rv;
342 
343   if (mBaseURI) {
344     // A previous iteration of this code wrote out mBaseURI as nsISupports
345     // and then read it in as nsIURI, which is non-kosher when mBaseURI
346     // implements more than just a single line of interfaces and the
347     // canonical nsISupports* isn't the one a static_cast<> of mBaseURI
348     // would produce.  For backwards compatibility with existing
349     // serializations we continue to write mBaseURI as nsISupports but
350     // switch to reading it as nsISupports, with a post-read QI to get to
351     // nsIURI.
352     rv = aStream->WriteCompoundObject(mBaseURI, NS_GET_IID(nsISupports), true);
353     if (NS_FAILED(rv)) return rv;
354   }
355 
356   return NS_OK;
357 }
358 
NS_IMETHODIMP_(void)359 NS_IMETHODIMP_(void)
360 nsNestedAboutURI::Serialize(mozilla::ipc::URIParams& aParams) {
361   using namespace mozilla::ipc;
362 
363   NestedAboutURIParams params;
364   URIParams nestedParams;
365 
366   nsSimpleNestedURI::Serialize(nestedParams);
367   params.nestedParams() = nestedParams;
368 
369   if (mBaseURI) {
370     SerializeURI(mBaseURI, params.baseURI());
371   }
372 
373   aParams = params;
374 }
375 
Deserialize(const mozilla::ipc::URIParams & aParams)376 bool nsNestedAboutURI::Deserialize(const mozilla::ipc::URIParams& aParams) {
377   using namespace mozilla::ipc;
378 
379   if (aParams.type() != URIParams::TNestedAboutURIParams) {
380     NS_ERROR("Received unknown parameters from the other process!");
381     return false;
382   }
383 
384   const NestedAboutURIParams& params = aParams.get_NestedAboutURIParams();
385   if (!nsSimpleNestedURI::Deserialize(params.nestedParams())) {
386     return false;
387   }
388 
389   mBaseURI = nullptr;
390   if (params.baseURI()) {
391     mBaseURI = DeserializeURI(*params.baseURI());
392   }
393   return true;
394 }
395 
396 // nsSimpleURI
StartClone(nsSimpleURI::RefHandlingEnum aRefHandlingMode,const nsACString & aNewRef)397 /* virtual */ nsSimpleURI* nsNestedAboutURI::StartClone(
398     nsSimpleURI::RefHandlingEnum aRefHandlingMode, const nsACString& aNewRef) {
399   // Sadly, we can't make use of nsSimpleNestedURI::StartClone here.
400   // However, this function is expected to exactly match that function,
401   // aside from the "new ns***URI()" call.
402   NS_ENSURE_TRUE(mInnerURI, nullptr);
403 
404   nsCOMPtr<nsIURI> innerClone;
405   nsresult rv = NS_OK;
406   if (aRefHandlingMode == eHonorRef) {
407     innerClone = mInnerURI;
408   } else if (aRefHandlingMode == eReplaceRef) {
409     rv = NS_GetURIWithNewRef(mInnerURI, aNewRef, getter_AddRefs(innerClone));
410   } else {
411     rv = NS_GetURIWithoutRef(mInnerURI, getter_AddRefs(innerClone));
412   }
413 
414   if (NS_FAILED(rv)) {
415     return nullptr;
416   }
417 
418   nsNestedAboutURI* url = new nsNestedAboutURI(innerClone, mBaseURI);
419   SetRefOnClone(url, aRefHandlingMode, aNewRef);
420 
421   return url;
422 }
423 
424 // Queries this list of interfaces. If none match, it queries mURI.
NS_IMPL_NSIURIMUTATOR_ISUPPORTS(nsNestedAboutURI::Mutator,nsIURISetters,nsIURIMutator,nsISerializable,nsINestedAboutURIMutator)425 NS_IMPL_NSIURIMUTATOR_ISUPPORTS(nsNestedAboutURI::Mutator, nsIURISetters,
426                                 nsIURIMutator, nsISerializable,
427                                 nsINestedAboutURIMutator)
428 
429 NS_IMETHODIMP
430 nsNestedAboutURI::Mutate(nsIURIMutator** aMutator) {
431   RefPtr<nsNestedAboutURI::Mutator> mutator = new nsNestedAboutURI::Mutator();
432   nsresult rv = mutator->InitFromURI(this);
433   if (NS_FAILED(rv)) {
434     return rv;
435   }
436   mutator.forget(aMutator);
437   return NS_OK;
438 }
439 
440 }  // namespace net
441 }  // namespace mozilla
442