1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 #include "PostMessageEvent.h"
8 
9 #include "MessageEvent.h"
10 #include "mozilla/dom/BrowsingContext.h"
11 #include "mozilla/dom/BrowsingContextGroup.h"
12 #include "mozilla/dom/DocGroup.h"
13 #include "mozilla/dom/DocumentInlines.h"
14 #include "mozilla/dom/MessageEventBinding.h"
15 #include "mozilla/dom/MessagePort.h"
16 #include "mozilla/dom/RootedDictionary.h"
17 #include "mozilla/BasePrincipal.h"
18 #include "mozilla/EventDispatcher.h"
19 #include "mozilla/StaticPrefs_dom.h"
20 #include "nsDocShell.h"
21 #include "nsGlobalWindowInner.h"
22 #include "nsGlobalWindowOuter.h"
23 #include "nsIConsoleService.h"
24 #include "nsIPrincipal.h"
25 #include "nsIScriptError.h"
26 #include "nsPresContext.h"
27 #include "nsQueryObject.h"
28 #include "nsServiceManagerUtils.h"
29 
30 namespace mozilla::dom {
31 
PostMessageEvent(BrowsingContext * aSource,const nsAString & aCallerOrigin,nsGlobalWindowOuter * aTargetWindow,nsIPrincipal * aProvidedPrincipal,uint64_t aCallerWindowID,nsIURI * aCallerURI,const nsCString & aScriptLocation,bool aIsFromPrivateWindow,const Maybe<nsID> & aCallerAgentClusterId)32 PostMessageEvent::PostMessageEvent(BrowsingContext* aSource,
33                                    const nsAString& aCallerOrigin,
34                                    nsGlobalWindowOuter* aTargetWindow,
35                                    nsIPrincipal* aProvidedPrincipal,
36                                    uint64_t aCallerWindowID, nsIURI* aCallerURI,
37                                    const nsCString& aScriptLocation,
38                                    bool aIsFromPrivateWindow,
39                                    const Maybe<nsID>& aCallerAgentClusterId)
40     : Runnable("dom::PostMessageEvent"),
41       mSource(aSource),
42       mCallerOrigin(aCallerOrigin),
43       mTargetWindow(aTargetWindow),
44       mProvidedPrincipal(aProvidedPrincipal),
45       mCallerWindowID(aCallerWindowID),
46       mCallerAgentClusterId(aCallerAgentClusterId),
47       mCallerURI(aCallerURI),
48       mScriptLocation(Some(aScriptLocation)),
49       mIsFromPrivateWindow(aIsFromPrivateWindow) {}
50 
51 PostMessageEvent::~PostMessageEvent() = default;
52 
53 NS_IMETHODIMP
Run()54 PostMessageEvent::Run() {
55   // Note: We don't init this AutoJSAPI with targetWindow, because we do not
56   // want exceptions during message deserialization to trigger error events on
57   // targetWindow.
58   AutoJSAPI jsapi;
59   jsapi.Init();
60   JSContext* cx = jsapi.cx();
61 
62   // The document URI is just used for the principal mismatch error message
63   // below. Use a stack variable so mCallerURI is not held onto after
64   // this method finishes, regardless of the method outcome.
65   nsCOMPtr<nsIURI> callerURI = std::move(mCallerURI);
66 
67   // If we bailed before this point we're going to leak mMessage, but
68   // that's probably better than crashing.
69 
70   RefPtr<nsGlobalWindowInner> targetWindow;
71   if (mTargetWindow->IsClosedOrClosing() ||
72       !(targetWindow = mTargetWindow->GetCurrentInnerWindowInternal()) ||
73       targetWindow->IsDying())
74     return NS_OK;
75 
76   // If the window's document has suppressed event handling, hand off this event
77   // for running later. We check the top window's document so that when multiple
78   // same-origin windows exist in the same top window, postMessage events will
79   // be delivered in the same order they were posted, regardless of which window
80   // they were posted to.
81   if (nsCOMPtr<nsPIDOMWindowOuter> topWindow =
82           targetWindow->GetOuterWindow()->GetInProcessTop()) {
83     if (nsCOMPtr<nsPIDOMWindowInner> topInner =
84             topWindow->GetCurrentInnerWindow()) {
85       if (topInner->GetExtantDoc() &&
86           topInner->GetExtantDoc()->SuspendPostMessageEvent(this)) {
87         return NS_OK;
88       }
89     }
90   }
91 
92   JSAutoRealm ar(cx, targetWindow->GetWrapper());
93 
94   // Ensure that any origin which might have been provided is the origin of this
95   // window's document.  Note that we do this *now* instead of when postMessage
96   // is called because the target window might have been navigated to a
97   // different location between then and now.  If this check happened when
98   // postMessage was called, it would be fairly easy for a malicious webpage to
99   // intercept messages intended for another site by carefully timing navigation
100   // of the target window so it changed location after postMessage but before
101   // now.
102   if (mProvidedPrincipal) {
103     // Get the target's origin either from its principal or, in the case the
104     // principal doesn't carry a URI (e.g. the system principal), the target's
105     // document.
106     nsIPrincipal* targetPrin = targetWindow->GetPrincipal();
107     if (NS_WARN_IF(!targetPrin)) return NS_OK;
108 
109     // Note: This is contrary to the spec with respect to file: URLs, which
110     //       the spec groups into a single origin, but given we intentionally
111     //       don't do that in other places it seems better to hold the line for
112     //       now.  Long-term, we want HTML5 to address this so that we can
113     //       be compliant while being safer.
114     if (!targetPrin->Equals(mProvidedPrincipal)) {
115       OriginAttributes sourceAttrs = mProvidedPrincipal->OriginAttributesRef();
116       OriginAttributes targetAttrs = targetPrin->OriginAttributesRef();
117 
118       MOZ_DIAGNOSTIC_ASSERT(
119           sourceAttrs.mUserContextId == targetAttrs.mUserContextId,
120           "Target and source should have the same userContextId attribute.");
121 
122       nsAutoString providedOrigin, targetOrigin;
123       nsresult rv = nsContentUtils::GetUTFOrigin(targetPrin, targetOrigin);
124       NS_ENSURE_SUCCESS(rv, rv);
125       rv = nsContentUtils::GetUTFOrigin(mProvidedPrincipal, providedOrigin);
126       NS_ENSURE_SUCCESS(rv, rv);
127 
128       nsAutoString errorText;
129       nsContentUtils::FormatLocalizedString(
130           errorText, nsContentUtils::eDOM_PROPERTIES,
131           "TargetPrincipalDoesNotMatch", providedOrigin, targetOrigin);
132 
133       nsCOMPtr<nsIScriptError> errorObject =
134           do_CreateInstance(NS_SCRIPTERROR_CONTRACTID, &rv);
135       NS_ENSURE_SUCCESS(rv, rv);
136 
137       if (mCallerWindowID == 0) {
138         rv = errorObject->Init(
139             errorText, NS_ConvertUTF8toUTF16(mScriptLocation.value()), u""_ns,
140             0, 0, nsIScriptError::errorFlag, "DOM Window", mIsFromPrivateWindow,
141             mProvidedPrincipal->IsSystemPrincipal());
142       } else if (callerURI) {
143         rv = errorObject->InitWithSourceURI(errorText, callerURI, u""_ns, 0, 0,
144                                             nsIScriptError::errorFlag,
145                                             "DOM Window", mCallerWindowID);
146       } else {
147         rv = errorObject->InitWithWindowID(
148             errorText, NS_ConvertUTF8toUTF16(mScriptLocation.value()), u""_ns,
149             0, 0, nsIScriptError::errorFlag, "DOM Window", mCallerWindowID);
150       }
151       NS_ENSURE_SUCCESS(rv, rv);
152 
153       nsCOMPtr<nsIConsoleService> consoleService =
154           do_GetService(NS_CONSOLESERVICE_CONTRACTID, &rv);
155       NS_ENSURE_SUCCESS(rv, rv);
156 
157       return consoleService->LogMessage(errorObject);
158     }
159   }
160 
161   IgnoredErrorResult rv;
162   JS::Rooted<JS::Value> messageData(cx);
163   nsCOMPtr<mozilla::dom::EventTarget> eventTarget =
164       do_QueryObject(targetWindow);
165 
166   JS::CloneDataPolicy cloneDataPolicy;
167   MOZ_DIAGNOSTIC_ASSERT(targetWindow);
168   if (mCallerAgentClusterId.isSome() && targetWindow->GetDocGroup() &&
169       targetWindow->GetDocGroup()->AgentClusterId().Equals(
170           mCallerAgentClusterId.ref())) {
171     cloneDataPolicy.allowIntraClusterClonableSharedObjects();
172   }
173 
174   if (targetWindow->IsSharedMemoryAllowed()) {
175     cloneDataPolicy.allowSharedMemoryObjects();
176   }
177 
178   if (mHolder.empty()) {
179     DispatchError(cx, targetWindow, eventTarget);
180     return NS_OK;
181   }
182 
183   StructuredCloneHolder* holder;
184   if (mHolder.constructed<StructuredCloneHolder>()) {
185     mHolder.ref<StructuredCloneHolder>().Read(
186         targetWindow->AsGlobal(), cx, &messageData, cloneDataPolicy, rv);
187     holder = &mHolder.ref<StructuredCloneHolder>();
188   } else {
189     MOZ_ASSERT(mHolder.constructed<ipc::StructuredCloneData>());
190     mHolder.ref<ipc::StructuredCloneData>().Read(cx, &messageData, rv);
191     holder = &mHolder.ref<ipc::StructuredCloneData>();
192   }
193   if (NS_WARN_IF(rv.Failed())) {
194     JS_ClearPendingException(cx);
195     DispatchError(cx, targetWindow, eventTarget);
196     return NS_OK;
197   }
198 
199   // Create the event
200   RefPtr<MessageEvent> event = new MessageEvent(eventTarget, nullptr, nullptr);
201 
202   Nullable<WindowProxyOrMessagePortOrServiceWorker> source;
203   if (mSource) {
204     source.SetValue().SetAsWindowProxy() = mSource;
205   }
206 
207   Sequence<OwningNonNull<MessagePort>> ports;
208   if (!holder->TakeTransferredPortsAsSequence(ports)) {
209     DispatchError(cx, targetWindow, eventTarget);
210     return NS_OK;
211   }
212 
213   event->InitMessageEvent(nullptr, u"message"_ns, CanBubble::eNo,
214                           Cancelable::eNo, messageData, mCallerOrigin, u""_ns,
215                           source, ports);
216 
217   Dispatch(targetWindow, event);
218   return NS_OK;
219 }
220 
DispatchError(JSContext * aCx,nsGlobalWindowInner * aTargetWindow,mozilla::dom::EventTarget * aEventTarget)221 void PostMessageEvent::DispatchError(JSContext* aCx,
222                                      nsGlobalWindowInner* aTargetWindow,
223                                      mozilla::dom::EventTarget* aEventTarget) {
224   RootedDictionary<MessageEventInit> init(aCx);
225   init.mBubbles = false;
226   init.mCancelable = false;
227   init.mOrigin = mCallerOrigin;
228 
229   if (mSource) {
230     init.mSource.SetValue().SetAsWindowProxy() = mSource;
231   }
232 
233   RefPtr<Event> event =
234       MessageEvent::Constructor(aEventTarget, u"messageerror"_ns, init);
235   Dispatch(aTargetWindow, event);
236 }
237 
Dispatch(nsGlobalWindowInner * aTargetWindow,Event * aEvent)238 void PostMessageEvent::Dispatch(nsGlobalWindowInner* aTargetWindow,
239                                 Event* aEvent) {
240   // We can't simply call dispatchEvent on the window because doing so ends
241   // up flipping the trusted bit on the event, and we don't want that to
242   // happen because then untrusted content can call postMessage on a chrome
243   // window if it can get a reference to it.
244 
245   RefPtr<nsPresContext> presContext =
246       aTargetWindow->GetExtantDoc()->GetPresContext();
247 
248   aEvent->SetTrusted(true);
249   WidgetEvent* internalEvent = aEvent->WidgetEventPtr();
250 
251   nsEventStatus status = nsEventStatus_eIgnore;
252   EventDispatcher::Dispatch(ToSupports(aTargetWindow), presContext,
253                             internalEvent, aEvent, &status);
254 }
255 
DispatchToTargetThread(ErrorResult & aError)256 void PostMessageEvent::DispatchToTargetThread(ErrorResult& aError) {
257   nsCOMPtr<nsIRunnable> event = this;
258 
259   if (StaticPrefs::dom_separate_event_queue_for_post_message_enabled() &&
260       !DocGroup::TryToLoadIframesInBackground()) {
261     BrowsingContext* bc = mTargetWindow->GetBrowsingContext();
262     bc = bc ? bc->Top() : nullptr;
263     if (bc && bc->IsLoading()) {
264       // As long as the top level is loading, we can dispatch events to the
265       // queue because the queue will be flushed eventually
266       aError = bc->Group()->QueuePostMessageEvent(event.forget());
267       return;
268     }
269   }
270 
271   // XXX Loading iframes in background isn't enabled by default and doesn't
272   //     work with Fission at the moment.
273   if (DocGroup::TryToLoadIframesInBackground()) {
274     RefPtr<nsIDocShell> docShell = mTargetWindow->GetDocShell();
275     RefPtr<nsDocShell> dShell = nsDocShell::Cast(docShell);
276 
277     // PostMessage that are added to the BrowsingContextGroup are the ones that
278     // can be flushed when the top level document is loaded.
279     // TreadAsBackgroundLoad DocShells are treated specially.
280     if (dShell) {
281       if (!dShell->TreatAsBackgroundLoad()) {
282         BrowsingContext* bc = mTargetWindow->GetBrowsingContext();
283         bc = bc ? bc->Top() : nullptr;
284         if (bc && bc->IsLoading()) {
285           // As long as the top level is loading, we can dispatch events to the
286           // queue because the queue will be flushed eventually
287           aError = bc->Group()->QueuePostMessageEvent(event.forget());
288           return;
289         }
290       } else if (mTargetWindow->GetExtantDoc() &&
291                  mTargetWindow->GetExtantDoc()->GetReadyStateEnum() <
292                      Document::READYSTATE_COMPLETE) {
293         mozilla::dom::DocGroup* docGroup = mTargetWindow->GetDocGroup();
294         aError = docGroup->QueueIframePostMessages(event.forget(),
295                                                    dShell->GetOuterWindowID());
296         return;
297       }
298     }
299   }
300 
301   aError = mTargetWindow->Dispatch(TaskCategory::Other, event.forget());
302 }
303 
304 }  // namespace mozilla::dom
305