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 "nsContentUtils.h"
13 #include "nsString.h"
14 #include "nsNetCID.h"
15 #include "nsAboutProtocolUtils.h"
16 #include "nsError.h"
17 #include "nsNetUtil.h"
18 #include "nsIObjectInputStream.h"
19 #include "nsIObjectOutputStream.h"
20 #include "nsIWritablePropertyBag2.h"
21 #include "nsIChannel.h"
22 #include "nsIScriptError.h"
23 #include "nsIClassInfoImpl.h"
24 
25 #include "mozilla/ipc/URIUtils.h"
26 
27 namespace mozilla {
28 namespace net {
29 
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     rv = NS_MutateURI(new nsNestedAboutURI::Mutator())
153              .Apply(&nsINestedAboutURIMutator::InitWithBase, inner, aBaseURI)
154              .SetSpec(aSpec)
155              .Finalize(url);
156     NS_ENSURE_SUCCESS(rv, rv);
157   }
158 
159   url.swap(*aResult);
160   return NS_OK;
161 }
162 
163 NS_IMETHODIMP
NewChannel(nsIURI * uri,nsILoadInfo * aLoadInfo,nsIChannel ** result)164 nsAboutProtocolHandler::NewChannel(nsIURI* uri, nsILoadInfo* aLoadInfo,
165                                    nsIChannel** result) {
166   NS_ENSURE_ARG_POINTER(uri);
167 
168   // about:what you ask?
169   nsCOMPtr<nsIAboutModule> aboutMod;
170   nsresult rv = NS_GetAboutModule(uri, getter_AddRefs(aboutMod));
171 
172   nsAutoCString path;
173   nsresult rv2 = NS_GetAboutModuleName(uri, path);
174   if (NS_SUCCEEDED(rv2) && path.EqualsLiteral("srcdoc")) {
175     // about:srcdoc is meant to be unresolvable, yet is included in the
176     // about lookup tables so that it can pass security checks when used in
177     // a srcdoc iframe.  To ensure that it stays unresolvable, we pretend
178     // that it doesn't exist.
179     rv = NS_ERROR_FACTORY_NOT_REGISTERED;
180   }
181 
182   if (NS_SUCCEEDED(rv)) {
183     // The standard return case:
184     rv = aboutMod->NewChannel(uri, aLoadInfo, result);
185     if (NS_SUCCEEDED(rv)) {
186       // Not all implementations of nsIAboutModule::NewChannel()
187       // set the LoadInfo on the newly created channel yet, as
188       // an interim solution we set the LoadInfo here if not
189       // available on the channel. Bug 1087720
190       nsCOMPtr<nsILoadInfo> loadInfo = (*result)->LoadInfo();
191       if (aLoadInfo != loadInfo) {
192         NS_ASSERTION(false,
193                      "nsIAboutModule->newChannel(aURI, aLoadInfo) needs to "
194                      "set LoadInfo");
195         AutoTArray<nsString, 2> params = {
196             u"nsIAboutModule->newChannel(aURI)"_ns,
197             u"nsIAboutModule->newChannel(aURI, aLoadInfo)"_ns};
198         nsContentUtils::ReportToConsole(
199             nsIScriptError::warningFlag, "Security by Default"_ns,
200             nullptr,  // aDocument
201             nsContentUtils::eNECKO_PROPERTIES, "APIDeprecationWarning", params);
202         (*result)->SetLoadInfo(aLoadInfo);
203       }
204 
205       // If this URI is safe for untrusted content, enforce that its
206       // principal be based on the channel's originalURI by setting the
207       // owner to null.
208       // Note: this relies on aboutMod's newChannel implementation
209       // having set the proper originalURI, which probably isn't ideal.
210       if (IsSafeForUntrustedContent(aboutMod, uri)) {
211         (*result)->SetOwner(nullptr);
212       }
213 
214       RefPtr<nsNestedAboutURI> aboutURI;
215       nsresult rv2 =
216           uri->QueryInterface(kNestedAboutURICID, getter_AddRefs(aboutURI));
217       if (NS_SUCCEEDED(rv2) && aboutURI->GetBaseURI()) {
218         nsCOMPtr<nsIWritablePropertyBag2> writableBag =
219             do_QueryInterface(*result);
220         if (writableBag) {
221           writableBag->SetPropertyAsInterface(u"baseURI"_ns,
222                                               aboutURI->GetBaseURI());
223         }
224       }
225     }
226     return rv;
227   }
228 
229   // mumble...
230 
231   if (rv == NS_ERROR_FACTORY_NOT_REGISTERED) {
232     // This looks like an about: we don't know about.  Convert
233     // this to an invalid URI error.
234     rv = NS_ERROR_MALFORMED_URI;
235   }
236 
237   return rv;
238 }
239 
240 NS_IMETHODIMP
AllowPort(int32_t port,const char * scheme,bool * _retval)241 nsAboutProtocolHandler::AllowPort(int32_t port, const char* scheme,
242                                   bool* _retval) {
243   // don't override anything.
244   *_retval = false;
245   return NS_OK;
246 }
247 
248 ////////////////////////////////////////////////////////////////////////////////
249 // Safe about protocol handler impl
250 
NS_IMPL_ISUPPORTS(nsSafeAboutProtocolHandler,nsIProtocolHandler,nsISupportsWeakReference)251 NS_IMPL_ISUPPORTS(nsSafeAboutProtocolHandler, nsIProtocolHandler,
252                   nsISupportsWeakReference)
253 
254 // nsIProtocolHandler methods:
255 
256 NS_IMETHODIMP
257 nsSafeAboutProtocolHandler::GetScheme(nsACString& result) {
258   result.AssignLiteral("moz-safe-about");
259   return NS_OK;
260 }
261 
262 NS_IMETHODIMP
GetDefaultPort(int32_t * result)263 nsSafeAboutProtocolHandler::GetDefaultPort(int32_t* result) {
264   *result = -1;  // no port for moz-safe-about: URLs
265   return NS_OK;
266 }
267 
268 NS_IMETHODIMP
GetProtocolFlags(uint32_t * result)269 nsSafeAboutProtocolHandler::GetProtocolFlags(uint32_t* result) {
270   *result = URI_NORELATIVE | URI_NOAUTH | URI_LOADABLE_BY_ANYONE |
271             URI_IS_POTENTIALLY_TRUSTWORTHY;
272   return NS_OK;
273 }
274 
275 NS_IMETHODIMP
NewChannel(nsIURI * uri,nsILoadInfo * aLoadInfo,nsIChannel ** result)276 nsSafeAboutProtocolHandler::NewChannel(nsIURI* uri, nsILoadInfo* aLoadInfo,
277                                        nsIChannel** result) {
278   *result = nullptr;
279   return NS_ERROR_NOT_AVAILABLE;
280 }
281 
282 NS_IMETHODIMP
AllowPort(int32_t port,const char * scheme,bool * _retval)283 nsSafeAboutProtocolHandler::AllowPort(int32_t port, const char* scheme,
284                                       bool* _retval) {
285   // don't override anything.
286   *_retval = false;
287   return NS_OK;
288 }
289 
290 ////////////////////////////////////////////////////////////
291 // nsNestedAboutURI implementation
292 
293 NS_IMPL_CLASSINFO(nsNestedAboutURI, nullptr, nsIClassInfo::THREADSAFE,
294                   NS_NESTEDABOUTURI_CID);
295 // Empty CI getter. We only need nsIClassInfo for Serialization
296 NS_IMPL_CI_INTERFACE_GETTER0(nsNestedAboutURI)
297 
298 NS_INTERFACE_MAP_BEGIN(nsNestedAboutURI)
299   if (aIID.Equals(kNestedAboutURICID)) {
300     foundInterface = static_cast<nsIURI*>(this);
301   } else
302     NS_IMPL_QUERY_CLASSINFO(nsNestedAboutURI)
NS_INTERFACE_MAP_END_INHERITING(nsSimpleNestedURI)303 NS_INTERFACE_MAP_END_INHERITING(nsSimpleNestedURI)
304 
305 // nsISerializable
306 
307 NS_IMETHODIMP
308 nsNestedAboutURI::Read(nsIObjectInputStream* aStream) {
309   MOZ_ASSERT_UNREACHABLE("Use nsIURIMutator.read() instead");
310   return NS_ERROR_NOT_IMPLEMENTED;
311 }
312 
ReadPrivate(nsIObjectInputStream * aStream)313 nsresult nsNestedAboutURI::ReadPrivate(nsIObjectInputStream* aStream) {
314   nsresult rv = nsSimpleNestedURI::ReadPrivate(aStream);
315   if (NS_FAILED(rv)) return rv;
316 
317   bool haveBase;
318   rv = aStream->ReadBoolean(&haveBase);
319   if (NS_FAILED(rv)) return rv;
320 
321   if (haveBase) {
322     nsCOMPtr<nsISupports> supports;
323     rv = aStream->ReadObject(true, getter_AddRefs(supports));
324     if (NS_FAILED(rv)) return rv;
325 
326     mBaseURI = do_QueryInterface(supports, &rv);
327     if (NS_FAILED(rv)) return rv;
328   }
329 
330   return NS_OK;
331 }
332 
333 NS_IMETHODIMP
Write(nsIObjectOutputStream * aStream)334 nsNestedAboutURI::Write(nsIObjectOutputStream* aStream) {
335   nsresult rv = nsSimpleNestedURI::Write(aStream);
336   if (NS_FAILED(rv)) return rv;
337 
338   rv = aStream->WriteBoolean(mBaseURI != nullptr);
339   if (NS_FAILED(rv)) return rv;
340 
341   if (mBaseURI) {
342     // A previous iteration of this code wrote out mBaseURI as nsISupports
343     // and then read it in as nsIURI, which is non-kosher when mBaseURI
344     // implements more than just a single line of interfaces and the
345     // canonical nsISupports* isn't the one a static_cast<> of mBaseURI
346     // would produce.  For backwards compatibility with existing
347     // serializations we continue to write mBaseURI as nsISupports but
348     // switch to reading it as nsISupports, with a post-read QI to get to
349     // nsIURI.
350     rv = aStream->WriteCompoundObject(mBaseURI, NS_GET_IID(nsISupports), true);
351     if (NS_FAILED(rv)) return rv;
352   }
353 
354   return NS_OK;
355 }
356 
NS_IMETHODIMP_(void)357 NS_IMETHODIMP_(void)
358 nsNestedAboutURI::Serialize(mozilla::ipc::URIParams& aParams) {
359   using namespace mozilla::ipc;
360 
361   NestedAboutURIParams params;
362   URIParams nestedParams;
363 
364   nsSimpleNestedURI::Serialize(nestedParams);
365   params.nestedParams() = nestedParams;
366 
367   if (mBaseURI) {
368     SerializeURI(mBaseURI, params.baseURI());
369   }
370 
371   aParams = params;
372 }
373 
Deserialize(const mozilla::ipc::URIParams & aParams)374 bool nsNestedAboutURI::Deserialize(const mozilla::ipc::URIParams& aParams) {
375   using namespace mozilla::ipc;
376 
377   if (aParams.type() != URIParams::TNestedAboutURIParams) {
378     NS_ERROR("Received unknown parameters from the other process!");
379     return false;
380   }
381 
382   const NestedAboutURIParams& params = aParams.get_NestedAboutURIParams();
383   if (!nsSimpleNestedURI::Deserialize(params.nestedParams())) {
384     return false;
385   }
386 
387   mBaseURI = nullptr;
388   if (params.baseURI()) {
389     mBaseURI = DeserializeURI(*params.baseURI());
390   }
391   return true;
392 }
393 
394 // nsSimpleURI
StartClone(nsSimpleURI::RefHandlingEnum aRefHandlingMode,const nsACString & aNewRef)395 /* virtual */ nsSimpleURI* nsNestedAboutURI::StartClone(
396     nsSimpleURI::RefHandlingEnum aRefHandlingMode, const nsACString& aNewRef) {
397   // Sadly, we can't make use of nsSimpleNestedURI::StartClone here.
398   // However, this function is expected to exactly match that function,
399   // aside from the "new ns***URI()" call.
400   NS_ENSURE_TRUE(mInnerURI, nullptr);
401 
402   nsCOMPtr<nsIURI> innerClone;
403   nsresult rv = NS_OK;
404   if (aRefHandlingMode == eHonorRef) {
405     innerClone = mInnerURI;
406   } else if (aRefHandlingMode == eReplaceRef) {
407     rv = NS_GetURIWithNewRef(mInnerURI, aNewRef, getter_AddRefs(innerClone));
408   } else {
409     rv = NS_GetURIWithoutRef(mInnerURI, getter_AddRefs(innerClone));
410   }
411 
412   if (NS_FAILED(rv)) {
413     return nullptr;
414   }
415 
416   nsNestedAboutURI* url = new nsNestedAboutURI(innerClone, mBaseURI);
417   SetRefOnClone(url, aRefHandlingMode, aNewRef);
418 
419   return url;
420 }
421 
422 // Queries this list of interfaces. If none match, it queries mURI.
NS_IMPL_NSIURIMUTATOR_ISUPPORTS(nsNestedAboutURI::Mutator,nsIURISetters,nsIURIMutator,nsISerializable,nsINestedAboutURIMutator)423 NS_IMPL_NSIURIMUTATOR_ISUPPORTS(nsNestedAboutURI::Mutator, nsIURISetters,
424                                 nsIURIMutator, nsISerializable,
425                                 nsINestedAboutURIMutator)
426 
427 NS_IMETHODIMP
428 nsNestedAboutURI::Mutate(nsIURIMutator** aMutator) {
429   RefPtr<nsNestedAboutURI::Mutator> mutator = new nsNestedAboutURI::Mutator();
430   nsresult rv = mutator->InitFromURI(this);
431   if (NS_FAILED(rv)) {
432     return rv;
433   }
434   mutator.forget(aMutator);
435   return NS_OK;
436 }
437 
438 }  // namespace net
439 }  // namespace mozilla
440