summaryrefslogtreecommitdiffstats
path: root/dom/base/nsContentPolicy.cpp
blob: 534466103c07cd9e9c6dc1ec6576c94df3e1336b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
// vim: ft=cpp tw=78 sw=4 et ts=8
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/*
 * Implementation of the "@mozilla.org/layout/content-policy;1" contract.
 */

#include "mozilla/Logging.h"

#include "nsISupports.h"
#include "nsXPCOM.h"
#include "nsContentPolicyUtils.h"
#include "mozilla/dom/nsCSPService.h"
#include "nsContentPolicy.h"
#include "nsIURI.h"
#include "nsIDocShell.h"
#include "nsIDOMElement.h"
#include "nsIDOMNode.h"
#include "nsIDOMWindow.h"
#include "nsITabChild.h"
#include "nsIContent.h"
#include "nsIImageLoadingContent.h"
#include "nsILoadContext.h"
#include "nsCOMArray.h"
#include "nsContentUtils.h"
#include "mozilla/dom/nsMixedContentBlocker.h"

using mozilla::LogLevel;

NS_IMPL_ISUPPORTS(nsContentPolicy, nsIContentPolicy)

static mozilla::LazyLogModule gConPolLog("nsContentPolicy");

nsresult
NS_NewContentPolicy(nsIContentPolicy **aResult)
{
  *aResult = new nsContentPolicy;
  NS_ADDREF(*aResult);
  return NS_OK;
}

nsContentPolicy::nsContentPolicy()
    : mPolicies(NS_CONTENTPOLICY_CATEGORY)
    , mSimplePolicies(NS_SIMPLECONTENTPOLICY_CATEGORY)
{
}

nsContentPolicy::~nsContentPolicy()
{
}

#ifdef DEBUG
#define WARN_IF_URI_UNINITIALIZED(uri,name)                         \
  PR_BEGIN_MACRO                                                    \
    if ((uri)) {                                                    \
        nsAutoCString spec;                                         \
        (uri)->GetAsciiSpec(spec);                                  \
        if (spec.IsEmpty()) {                                       \
            NS_WARNING(name " is uninitialized, fix caller");       \
        }                                                           \
    }                                                               \
  PR_END_MACRO

#else  // ! defined(DEBUG)

#define WARN_IF_URI_UNINITIALIZED(uri,name)

#endif // defined(DEBUG)

inline nsresult
nsContentPolicy::CheckPolicy(CPMethod          policyMethod,
                             SCPMethod         simplePolicyMethod,
                             nsContentPolicyType contentType,
                             nsIURI           *contentLocation,
                             nsIURI           *requestingLocation,
                             nsISupports      *requestingContext,
                             const nsACString &mimeType,
                             nsISupports      *extra,
                             nsIPrincipal     *requestPrincipal,
                             int16_t           *decision)
{
    //sanity-check passed-through parameters
    NS_PRECONDITION(decision, "Null out pointer");
    WARN_IF_URI_UNINITIALIZED(contentLocation, "Request URI");
    WARN_IF_URI_UNINITIALIZED(requestingLocation, "Requesting URI");

#ifdef DEBUG
    {
        nsCOMPtr<nsIDOMNode> node(do_QueryInterface(requestingContext));
        nsCOMPtr<nsIDOMWindow> window(do_QueryInterface(requestingContext));
        nsCOMPtr<nsITabChild> tabChild(do_QueryInterface(requestingContext));
        NS_ASSERTION(!requestingContext || node || window || tabChild,
                     "Context should be a DOM node, DOM window or a tabChild!");
    }
#endif

    /*
     * There might not be a requestinglocation. This can happen for
     * iframes with an image as src. Get the uri from the dom node.
     * See bug 254510
     */
    if (!requestingLocation) {
        nsCOMPtr<nsIDocument> doc;
        nsCOMPtr<nsIContent> node = do_QueryInterface(requestingContext);
        if (node) {
            doc = node->OwnerDoc();
        }
        if (!doc) {
            doc = do_QueryInterface(requestingContext);
        }
        if (doc) {
            requestingLocation = doc->GetDocumentURI();
        }
    }

    nsContentPolicyType externalType =
        nsContentUtils::InternalContentPolicyTypeToExternal(contentType);

    nsCOMPtr<nsIContentPolicy> mixedContentBlocker =
        do_GetService(NS_MIXEDCONTENTBLOCKER_CONTRACTID);

    nsCOMPtr<nsIContentPolicy> cspService =
      do_GetService(CSPSERVICE_CONTRACTID);

    /* 
     * Enumerate mPolicies and ask each of them, taking the logical AND of
     * their permissions.
     */
    nsresult rv;
    nsCOMArray<nsIContentPolicy> entries;
    mPolicies.GetEntries(entries);
    int32_t count = entries.Count();
    for (int32_t i = 0; i < count; i++) {
        /* check the appropriate policy */
        // Send internal content policy type to CSP and mixed content blocker
        nsContentPolicyType type = externalType;
        if (mixedContentBlocker == entries[i] || cspService == entries[i]) {
          type = contentType;
        }
        rv = (entries[i]->*policyMethod)(type, contentLocation,
                                         requestingLocation, requestingContext,
                                         mimeType, extra, requestPrincipal,
                                         decision);

        if (NS_SUCCEEDED(rv) && NS_CP_REJECTED(*decision)) {
            // If we are blocking an image, we have to let the
            // ImageLoadingContent know that we blocked the load.
            if (externalType == nsIContentPolicy::TYPE_IMAGE ||
                externalType == nsIContentPolicy::TYPE_IMAGESET) {
              nsCOMPtr<nsIImageLoadingContent> img =
                do_QueryInterface(requestingContext);
              if (img) {
                img->SetBlockedRequest(*decision);
              }
            }
            /* policy says no, no point continuing to check */
            return NS_OK;
        }
    }

    nsCOMPtr<nsIDOMElement> topFrameElement;
    bool isTopLevel = true;
    nsCOMPtr<nsPIDOMWindowOuter> window;
    if (nsCOMPtr<nsINode> node = do_QueryInterface(requestingContext)) {
        window = node->OwnerDoc()->GetWindow();
    } else {
        window = do_QueryInterface(requestingContext);
    }

    if (window) {
        nsCOMPtr<nsIDocShell> docShell = window->GetDocShell();
        nsCOMPtr<nsILoadContext> loadContext = do_QueryInterface(docShell);
        if (loadContext) {
          loadContext->GetTopFrameElement(getter_AddRefs(topFrameElement));
        }

        MOZ_ASSERT(window->IsOuterWindow());

        if (topFrameElement) {
            nsCOMPtr<nsPIDOMWindowOuter> topWindow = window->GetScriptableTop();
            isTopLevel = topWindow == window;
        } else {
            // If we don't have a top frame element, then requestingContext is
            // part of the top-level XUL document. Presumably it's the <browser>
            // element that content is being loaded into, so we call it the
            // topFrameElement.
            topFrameElement = do_QueryInterface(requestingContext);
            isTopLevel = true;
        }
    }

    nsCOMArray<nsISimpleContentPolicy> simpleEntries;
    mSimplePolicies.GetEntries(simpleEntries);
    count = simpleEntries.Count();
    for (int32_t i = 0; i < count; i++) {
        /* check the appropriate policy */
        rv = (simpleEntries[i]->*simplePolicyMethod)(externalType, contentLocation,
                                                     requestingLocation,
                                                     topFrameElement, isTopLevel,
                                                     mimeType, extra, requestPrincipal,
                                                     decision);

        if (NS_SUCCEEDED(rv) && NS_CP_REJECTED(*decision)) {
            // If we are blocking an image, we have to let the
            // ImageLoadingContent know that we blocked the load.
            if (externalType == nsIContentPolicy::TYPE_IMAGE ||
                externalType == nsIContentPolicy::TYPE_IMAGESET) {
              nsCOMPtr<nsIImageLoadingContent> img =
                do_QueryInterface(requestingContext);
              if (img) {
                img->SetBlockedRequest(*decision);
              }
            }
            /* policy says no, no point continuing to check */
            return NS_OK;
        }
    }

    // everyone returned failure, or no policies: sanitize result
    *decision = nsIContentPolicy::ACCEPT;
    return NS_OK;
}

//uses the parameters from ShouldXYZ to produce and log a message
//logType must be a literal string constant
#define LOG_CHECK(logType)                                                     \
  PR_BEGIN_MACRO                                                               \
    /* skip all this nonsense if the call failed or logging is disabled */     \
    if (NS_SUCCEEDED(rv) && MOZ_LOG_TEST(gConPolLog, LogLevel::Debug)) {       \
      const char *resultName;                                                  \
      if (decision) {                                                          \
        resultName = NS_CP_ResponseName(*decision);                            \
      } else {                                                                 \
        resultName = "(null ptr)";                                             \
      }                                                                        \
      MOZ_LOG(gConPolLog, LogLevel::Debug,                                     \
             ("Content Policy: " logType ": <%s> <Ref:%s> result=%s",          \
              contentLocation ? contentLocation->GetSpecOrDefault().get()      \
                              : "None",                                        \
              requestingLocation ? requestingLocation->GetSpecOrDefault().get()\
                                 : "None",                                     \
              resultName)                                                      \
             );                                                                \
    }                                                                          \
  PR_END_MACRO

NS_IMETHODIMP
nsContentPolicy::ShouldLoad(uint32_t          contentType,
                            nsIURI           *contentLocation,
                            nsIURI           *requestingLocation,
                            nsISupports      *requestingContext,
                            const nsACString &mimeType,
                            nsISupports      *extra,
                            nsIPrincipal     *requestPrincipal,
                            int16_t          *decision)
{
    // ShouldProcess does not need a content location, but we do
    NS_PRECONDITION(contentLocation, "Must provide request location");
    nsresult rv = CheckPolicy(&nsIContentPolicy::ShouldLoad,
                              &nsISimpleContentPolicy::ShouldLoad,
                              contentType,
                              contentLocation, requestingLocation,
                              requestingContext, mimeType, extra,
                              requestPrincipal, decision);
    LOG_CHECK("ShouldLoad");

    return rv;
}

NS_IMETHODIMP
nsContentPolicy::ShouldProcess(uint32_t          contentType,
                               nsIURI           *contentLocation,
                               nsIURI           *requestingLocation,
                               nsISupports      *requestingContext,
                               const nsACString &mimeType,
                               nsISupports      *extra,
                               nsIPrincipal     *requestPrincipal,
                               int16_t          *decision)
{
    nsresult rv = CheckPolicy(&nsIContentPolicy::ShouldProcess,
                              &nsISimpleContentPolicy::ShouldProcess,
                              contentType,
                              contentLocation, requestingLocation,
                              requestingContext, mimeType, extra,
                              requestPrincipal, decision);
    LOG_CHECK("ShouldProcess");

    return rv;
}