1 /* -*- Mode: C++; tab-width: 20; 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/. */
9 #include "nsICanvasRenderingContextInternal.h"
10 #include "nsIHTMLCollection.h"
11 #include "mozilla/dom/BrowserChild.h"
12 #include "mozilla/dom/Document.h"
13 #include "mozilla/dom/HTMLCanvasElement.h"
14 #include "mozilla/dom/UserActivation.h"
15 #include "mozilla/BasePrincipal.h"
16 #include "mozilla/StaticPrefs_dom.h"
17 #include "mozilla/StaticPrefs_privacy.h"
18 #include "mozilla/StaticPrefs_webgl.h"
19 #include "nsIPrincipal.h"
21 #include "nsGfxCIID.h"
25 #include "CanvasUtils.h"
26 #include "mozilla/gfx/Matrix.h"
27 #include "WebGL2Context.h"
29 #include "nsIScriptError.h"
30 #include "nsIScriptObjectPrincipal.h"
31 #include "nsIPermissionManager.h"
32 #include "nsIObserverService.h"
33 #include "mozilla/Services.h"
34 #include "mozIThirdPartyUtil.h"
35 #include "nsContentUtils.h"
36 #include "nsUnicharUtils.h"
37 #include "nsPrintfCString.h"
40 #define TOPIC_CANVAS_PERMISSIONS_PROMPT "canvas-permissions-prompt"
41 #define TOPIC_CANVAS_PERMISSIONS_PROMPT_HIDE_DOORHANGER \
42 "canvas-permissions-prompt-hide-doorhanger"
43 #define PERMISSION_CANVAS_EXTRACT_DATA "canvas"_ns
45 using namespace mozilla::gfx
;
47 namespace mozilla::CanvasUtils
{
49 bool IsImageExtractionAllowed(dom::Document
* aDocument
, JSContext
* aCx
,
50 nsIPrincipal
& aPrincipal
) {
51 // Do the rest of the checks only if privacy.resistFingerprinting is on.
52 if (!nsContentUtils::ShouldResistFingerprinting(aDocument
)) {
56 // Don't proceed if we don't have a document or JavaScript context.
57 if (!aDocument
|| !aCx
) {
61 // The system principal can always extract canvas data.
62 if (aPrincipal
.IsSystemPrincipal()) {
66 // Allow extension principals.
67 auto principal
= BasePrincipal::Cast(&aPrincipal
);
68 if (principal
->AddonPolicy() || principal
->ContentScriptAddonPolicy()) {
72 // Get the document URI and its spec.
73 nsIURI
* docURI
= aDocument
->GetDocumentURI();
75 docURI
->GetSpec(docURISpec
);
77 // Allow local files to extract canvas data.
78 if (docURI
->SchemeIs("file")) {
82 // Don't show canvas prompt for PDF.js
83 JS::AutoFilename scriptFile
;
84 if (JS::DescribeScriptedCaller(aCx
, &scriptFile
) && scriptFile
.get() &&
85 strcmp(scriptFile
.get(), "resource://pdf.js/build/pdf.js") == 0) {
89 dom::Document
* topLevelDocument
= aDocument
->GetTopLevelContentDocument();
90 nsIURI
* topLevelDocURI
=
91 topLevelDocument
? topLevelDocument
->GetDocumentURI() : nullptr;
92 nsCString topLevelDocURISpec
;
94 topLevelDocURI
->GetSpec(topLevelDocURISpec
);
97 // Load Third Party Util service.
99 nsCOMPtr
<mozIThirdPartyUtil
> thirdPartyUtil
=
100 do_GetService(THIRDPARTYUTIL_CONTRACTID
, &rv
);
101 NS_ENSURE_SUCCESS(rv
, false);
103 // Block all third-party attempts to extract canvas.
104 bool isThirdParty
= true;
105 rv
= thirdPartyUtil
->IsThirdPartyURI(topLevelDocURI
, docURI
, &isThirdParty
);
106 NS_ENSURE_SUCCESS(rv
, false);
108 nsAutoString message
;
109 message
.AppendPrintf("Blocked third party %s from extracting canvas data.",
111 nsContentUtils::ReportToConsoleNonLocalized(
112 message
, nsIScriptError::warningFlag
, "Security"_ns
, aDocument
);
116 // Load Permission Manager service.
117 nsCOMPtr
<nsIPermissionManager
> permissionManager
=
118 do_GetService(NS_PERMISSIONMANAGER_CONTRACTID
, &rv
);
119 NS_ENSURE_SUCCESS(rv
, false);
121 // Check if the site has permission to extract canvas data.
122 // Either permit or block extraction if a stored permission setting exists.
124 rv
= permissionManager
->TestPermissionFromPrincipal(
125 principal
, PERMISSION_CANVAS_EXTRACT_DATA
, &permission
);
126 NS_ENSURE_SUCCESS(rv
, false);
127 switch (permission
) {
128 case nsIPermissionManager::ALLOW_ACTION
:
130 case nsIPermissionManager::DENY_ACTION
:
136 // At this point, permission is unknown
137 // (nsIPermissionManager::UNKNOWN_ACTION).
139 // Check if the request is in response to user input
140 bool isAutoBlockCanvas
=
142 privacy_resistFingerprinting_autoDeclineNoUserInputCanvasPrompts() &&
143 !dom::UserActivation::IsHandlingUserInput();
145 if (isAutoBlockCanvas
) {
146 nsAutoString message
;
147 message
.AppendPrintf(
148 "Blocked %s from extracting canvas data because no user input was "
151 nsContentUtils::ReportToConsoleNonLocalized(
152 message
, nsIScriptError::warningFlag
, "Security"_ns
, aDocument
);
154 // It was in response to user input, so log and display the prompt.
155 nsAutoString message
;
156 message
.AppendPrintf(
157 "Blocked %s from extracting canvas data, but prompting the user.",
159 nsContentUtils::ReportToConsoleNonLocalized(
160 message
, nsIScriptError::warningFlag
, "Security"_ns
, aDocument
);
163 // Prompt the user (asynchronous).
164 nsPIDOMWindowOuter
* win
= aDocument
->GetWindow();
165 nsAutoCString origin
;
166 rv
= principal
->GetOrigin(origin
);
167 NS_ENSURE_SUCCESS(rv
, false);
169 if (XRE_IsContentProcess()) {
170 dom::BrowserChild
* browserChild
= dom::BrowserChild::GetFrom(win
);
172 browserChild
->SendShowCanvasPermissionPrompt(origin
, isAutoBlockCanvas
);
175 nsCOMPtr
<nsIObserverService
> obs
= mozilla::services::GetObserverService();
177 obs
->NotifyObservers(win
,
179 ? TOPIC_CANVAS_PERMISSIONS_PROMPT_HIDE_DOORHANGER
180 : TOPIC_CANVAS_PERMISSIONS_PROMPT
,
181 NS_ConvertUTF8toUTF16(origin
).get());
185 // We don't extract the image for now -- user may override at prompt.
189 bool GetCanvasContextType(const nsAString
& str
,
190 dom::CanvasContextType
* const out_type
) {
191 if (str
.EqualsLiteral("2d")) {
192 *out_type
= dom::CanvasContextType::Canvas2D
;
196 if (str
.EqualsLiteral("webgl") || str
.EqualsLiteral("experimental-webgl")) {
197 *out_type
= dom::CanvasContextType::WebGL1
;
201 if (StaticPrefs::webgl_enable_webgl2()) {
202 if (str
.EqualsLiteral("webgl2")) {
203 *out_type
= dom::CanvasContextType::WebGL2
;
208 if (StaticPrefs::dom_webgpu_enabled()) {
209 if (str
.EqualsLiteral("gpupresent")) {
210 *out_type
= dom::CanvasContextType::WebGPU
;
215 if (str
.EqualsLiteral("bitmaprenderer")) {
216 *out_type
= dom::CanvasContextType::ImageBitmap
;
224 * This security check utility might be called from an source that never taints
225 * others. For example, while painting a CanvasPattern, which is created from an
226 * ImageBitmap, onto a canvas. In this case, the caller could set the CORSUsed
227 * true in order to pass this check and leave the aPrincipal to be a nullptr
228 * since the aPrincipal is not going to be used.
230 void DoDrawImageSecurityCheck(dom::HTMLCanvasElement
* aCanvasElement
,
231 nsIPrincipal
* aPrincipal
, bool forceWriteOnly
,
233 // Callers should ensure that mCanvasElement is non-null before calling this
234 if (!aCanvasElement
) {
235 NS_WARNING("DoDrawImageSecurityCheck called without canvas element!");
239 if (aCanvasElement
->IsWriteOnly() && !aCanvasElement
->mExpandedReader
) {
243 // If we explicitly set WriteOnly just do it and get out
244 if (forceWriteOnly
) {
245 aCanvasElement
->SetWriteOnly();
249 // No need to do a security check if the image used CORS for the load
250 if (CORSUsed
) return;
252 MOZ_ASSERT(aPrincipal
, "Must have a principal here");
254 if (aCanvasElement
->NodePrincipal()->Subsumes(aPrincipal
)) {
255 // This canvas has access to that image anyway
259 if (BasePrincipal::Cast(aPrincipal
)->AddonPolicy()) {
260 // This is a resource from an extension content script principal.
262 if (aCanvasElement
->mExpandedReader
&&
263 aCanvasElement
->mExpandedReader
->Subsumes(aPrincipal
)) {
264 // This canvas already allows reading from this principal.
268 if (!aCanvasElement
->mExpandedReader
) {
269 // Allow future reads from this same princial only.
270 aCanvasElement
->SetWriteOnly(aPrincipal
);
274 // If we got here, this must be the *second* extension tainting
275 // the canvas. Fall through to mark it WriteOnly for everyone.
278 aCanvasElement
->SetWriteOnly();
281 bool CoerceDouble(const JS::Value
& v
, double* d
) {
284 } else if (v
.isInt32()) {
285 *d
= double(v
.toInt32());
286 } else if (v
.isUndefined()) {
294 bool HasDrawWindowPrivilege(JSContext
* aCx
, JSObject
* /* unused */) {
295 return nsContentUtils::CallerHasPermission(aCx
,
296 nsGkAtoms::all_urlsPermission
);
299 bool CheckWriteOnlySecurity(bool aCORSUsed
, nsIPrincipal
* aPrincipal
,
300 bool aHadCrossOriginRedirects
) {
306 if (aHadCrossOriginRedirects
) {
310 nsIGlobalObject
* incumbentSettingsObject
= dom::GetIncumbentGlobal();
311 if (!incumbentSettingsObject
) {
315 nsIPrincipal
* principal
= incumbentSettingsObject
->PrincipalOrNull();
316 if (NS_WARN_IF(!principal
) || !(principal
->Subsumes(aPrincipal
))) {
324 } // namespace mozilla::CanvasUtils