DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Implementation

Mercurial (03b97487f359)

VCS Links

Line Code
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 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* 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/. */

#ifndef mozilla_BasePrincipal_h
#define mozilla_BasePrincipal_h

#include "nsJSPrincipals.h"

#include "mozilla/Attributes.h"
#include "mozilla/OriginAttributes.h"

class nsAtom;
class nsIContentSecurityPolicy;
class nsIObjectOutputStream;
class nsIObjectInputStream;
class nsIURI;

class ExpandedPrincipal;

namespace Json {
class Value;
}
namespace mozilla {
namespace dom {
class Document;
}
namespace extensions {
class WebExtensionPolicy;
}

class BasePrincipal;

// Codebase principals (and codebase principals embedded within expanded
// principals) stored in SiteIdentifier are guaranteed to contain only the
// eTLD+1 part of the original domain. This is used to determine whether two
// origins are same-site: if it's possible for two origins to access each other
// (maybe after mutating document.domain), then they must have the same site
// identifier.
class SiteIdentifier {
 public:
  void Init(BasePrincipal* aPrincipal) {
    MOZ_ASSERT(aPrincipal);
    mPrincipal = aPrincipal;
  }

  bool IsInitialized() const { return !!mPrincipal; }

  bool Equals(const SiteIdentifier& aOther) const;

 private:
  friend class ::ExpandedPrincipal;

  BasePrincipal* GetPrincipal() const {
    MOZ_ASSERT(IsInitialized());
    return mPrincipal;
  }

  RefPtr<BasePrincipal> mPrincipal;
};

/*
 * Base class from which all nsIPrincipal implementations inherit. Use this for
 * default implementations and other commonalities between principal
 * implementations.
 *
 * We should merge nsJSPrincipals into this class at some point.
 */
class BasePrincipal : public nsJSPrincipals {
 public:
  // Warning: this enum impacts Principal serialization into JSON format.
  // Only update if you know exactly what you are doing
  enum PrincipalKind {
    eNullPrincipal = 0,
    eCodebasePrincipal,
    eExpandedPrincipal,
    eSystemPrincipal,
    eKindMax = eSystemPrincipal
  };

  explicit BasePrincipal(PrincipalKind aKind);

  template <typename T>
  bool Is() const {
    return mKind == T::Kind();
  }

  template <typename T>
  T* As() {
    MOZ_ASSERT(Is<T>());
    return static_cast<T*>(this);
  }

  enum DocumentDomainConsideration {
    DontConsiderDocumentDomain,
    ConsiderDocumentDomain
  };
  bool Subsumes(nsIPrincipal* aOther,
                DocumentDomainConsideration aConsideration);

  NS_IMETHOD GetOrigin(nsACString& aOrigin) final;
  NS_IMETHOD GetOriginNoSuffix(nsACString& aOrigin) final;
  NS_IMETHOD Equals(nsIPrincipal* other, bool* _retval) final;
  NS_IMETHOD EqualsConsideringDomain(nsIPrincipal* other, bool* _retval) final;
  NS_IMETHOD Subsumes(nsIPrincipal* other, bool* _retval) final;
  NS_IMETHOD SubsumesConsideringDomain(nsIPrincipal* other,
                                       bool* _retval) final;
  NS_IMETHOD SubsumesConsideringDomainIgnoringFPD(nsIPrincipal* other,
                                                  bool* _retval) final;
  NS_IMETHOD CheckMayLoad(nsIURI* uri, bool report,
                          bool allowIfInheritsPrincipal) final;
  NS_IMETHOD GetAddonPolicy(nsISupports** aResult) final;
  NS_IMETHOD GetIsNullPrincipal(bool* aResult) override;
  NS_IMETHOD GetIsCodebasePrincipal(bool* aResult) override;
  NS_IMETHOD GetIsExpandedPrincipal(bool* aResult) override;
  NS_IMETHOD GetIsSystemPrincipal(bool* aResult) override;
  NS_IMETHOD GetIsAddonOrExpandedAddonPrincipal(bool* aResult) override;
  NS_IMETHOD GetOriginAttributes(JSContext* aCx,
                                 JS::MutableHandle<JS::Value> aVal) final;
  NS_IMETHOD GetOriginSuffix(nsACString& aOriginSuffix) final;
  NS_IMETHOD GetIsInIsolatedMozBrowserElement(
      bool* aIsInIsolatedMozBrowserElement) final;
  NS_IMETHOD GetUserContextId(uint32_t* aUserContextId) final;
  NS_IMETHOD GetPrivateBrowsingId(uint32_t* aPrivateBrowsingId) final;
  NS_IMETHOD GetSiteOrigin(nsACString& aOrigin) override;

  nsresult ToJSON(nsACString& aJSON);
  static already_AddRefed<BasePrincipal> FromJSON(const nsACString& aJSON);
  // Method populates a passed Json::Value with serializable fields
  // which represent all of the fields to deserialize the principal
  virtual nsresult PopulateJSONObject(Json::Value& aObject);

  virtual bool AddonHasPermission(const nsAtom* aPerm);

  virtual bool IsCodebasePrincipal() const { return false; };

  static BasePrincipal* Cast(nsIPrincipal* aPrin) {
    return static_cast<BasePrincipal*>(aPrin);
  }

  static const BasePrincipal* Cast(const nsIPrincipal* aPrin) {
    return static_cast<const BasePrincipal*>(aPrin);
  }

  static already_AddRefed<BasePrincipal> CreateCodebasePrincipal(
      const nsACString& aOrigin);

  // These following method may not create a codebase principal in case it's
  // not possible to generate a correct origin from the passed URI. If this
  // happens, a NullPrincipal is returned.

  static already_AddRefed<BasePrincipal> CreateCodebasePrincipal(
      nsIURI* aURI, const OriginAttributes& aAttrs);

  const OriginAttributes& OriginAttributesRef() final {
    return mOriginAttributes;
  }
  extensions::WebExtensionPolicy* AddonPolicy();
  uint32_t UserContextId() const { return mOriginAttributes.mUserContextId; }
  uint32_t PrivateBrowsingId() const {
    return mOriginAttributes.mPrivateBrowsingId;
  }
  bool IsInIsolatedMozBrowserElement() const {
    return mOriginAttributes.mInIsolatedMozBrowser;
  }

  PrincipalKind Kind() const { return mKind; }

  already_AddRefed<BasePrincipal> CloneForcingOriginAttributes(
      const OriginAttributes& aOriginAttributes);

  // If this is an add-on content script principal, returns its AddonPolicy.
  // Otherwise returns null.
  extensions::WebExtensionPolicy* ContentScriptAddonPolicy();

  // Helper to check whether this principal is associated with an addon that
  // allows unprivileged code to load aURI.  aExplicit == true will prevent
  // use of all_urls permission, requiring the domain in its permissions.
  bool AddonAllowsLoad(nsIURI* aURI, bool aExplicit = false);

  // Call these to avoid the cost of virtual dispatch.
  inline bool FastEquals(nsIPrincipal* aOther);
  inline bool FastEqualsConsideringDomain(nsIPrincipal* aOther);
  inline bool FastSubsumes(nsIPrincipal* aOther);
  inline bool FastSubsumesConsideringDomain(nsIPrincipal* aOther);
  inline bool FastSubsumesIgnoringFPD(nsIPrincipal* aOther);
  inline bool FastSubsumesConsideringDomainIgnoringFPD(nsIPrincipal* aOther);

  // Fast way to check whether we have a system principal.
  inline bool IsSystemPrincipal() const;

  // Returns the principal to inherit when a caller with this principal loads
  // the given URI.
  //
  // For most principal types, this returns the principal itself. For expanded
  // principals, it returns the first sub-principal which subsumes the given URI
  // (or, if no URI is given, the last allowlist principal).
  nsIPrincipal* PrincipalToInherit(nsIURI* aRequestedURI = nullptr);

  /* Returns true if this principal's CSP should override a document's CSP for
   * loads that it triggers. Currently true for expanded principals which
   * subsume the document principal, and add-on codebase principals regardless
   * of whether they subsume the document principal.
   */
  bool OverridesCSP(nsIPrincipal* aDocumentPrincipal) {
    // Expanded principals override CSP if and only if they subsume the document
    // principal.
    if (mKind == eExpandedPrincipal) {
      return FastSubsumes(aDocumentPrincipal);
    }
    // Extension principals always override the CSP non-extension principals.
    // This is primarily for the sake of their stylesheets, which are usually
    // loaded from channels and cannot have expanded principals.
    return (AddonPolicy() &&
            !BasePrincipal::Cast(aDocumentPrincipal)->AddonPolicy());
  }

  uint32_t GetOriginNoSuffixHash() const { return mOriginNoSuffix->hash(); }

  virtual nsresult GetSiteIdentifier(SiteIdentifier& aSite) = 0;

 protected:
  virtual ~BasePrincipal();

  // Note that this does not check OriginAttributes. Callers that depend on
  // those must call Subsumes instead.
  virtual bool SubsumesInternal(nsIPrincipal* aOther,
                                DocumentDomainConsideration aConsider) = 0;

  // Internal, side-effect-free check to determine whether the concrete
  // principal would allow the load ignoring any common behavior implemented in
  // BasePrincipal::CheckMayLoad.
  virtual bool MayLoadInternal(nsIURI* aURI) = 0;
  friend class ::ExpandedPrincipal;

  void SetHasExplicitDomain() { mHasExplicitDomain = true; }

  // Either of these functions should be called as the last step of the
  // initialization of the principal objects.  It's typically called as the
  // last step from the Init() method of the child classes.
  void FinishInit(const nsACString& aOriginNoSuffix,
                  const OriginAttributes& aOriginAttributes);
  void FinishInit(BasePrincipal* aOther,
                  const OriginAttributes& aOriginAttributes);

 private:
  static already_AddRefed<BasePrincipal> CreateCodebasePrincipal(
      nsIURI* aURI, const OriginAttributes& aAttrs,
      const nsACString& aOriginNoSuffix);

  inline bool FastSubsumesIgnoringFPD(
      nsIPrincipal* aOther, DocumentDomainConsideration aConsideration);

  RefPtr<nsAtom> mOriginNoSuffix;
  RefPtr<nsAtom> mOriginSuffix;

  OriginAttributes mOriginAttributes;
  PrincipalKind mKind;
  bool mHasExplicitDomain;
  bool mInitialized;
};

inline bool BasePrincipal::FastEquals(nsIPrincipal* aOther) {
  auto other = Cast(aOther);
  if (Kind() != other->Kind()) {
    // Principals of different kinds can't be equal.
    return false;
  }

  // Two principals are considered to be equal if their origins are the same.
  // If the two principals are codebase principals, their origin attributes
  // (aka the origin suffix) must also match.
  if (Kind() == eSystemPrincipal) {
    return this == other;
  }

  if (Kind() == eCodebasePrincipal || Kind() == eNullPrincipal) {
    return mOriginNoSuffix == other->mOriginNoSuffix &&
           mOriginSuffix == other->mOriginSuffix;
  }

  MOZ_ASSERT(Kind() == eExpandedPrincipal);
  return mOriginNoSuffix == other->mOriginNoSuffix;
}

inline bool BasePrincipal::FastEqualsConsideringDomain(nsIPrincipal* aOther) {
  // If neither of the principals have document.domain set, we use the fast path
  // in Equals().  Otherwise, we fall back to the slow path below.
  auto other = Cast(aOther);
  if (!mHasExplicitDomain && !other->mHasExplicitDomain) {
    return FastEquals(aOther);
  }

  return Subsumes(aOther, ConsiderDocumentDomain) &&
         other->Subsumes(this, ConsiderDocumentDomain);
}

inline bool BasePrincipal::FastSubsumes(nsIPrincipal* aOther) {
  // If two principals are equal, then they both subsume each other.
  if (FastEquals(aOther)) {
    return true;
  }

  // Otherwise, fall back to the slow path.
  return Subsumes(aOther, DontConsiderDocumentDomain);
}

inline bool BasePrincipal::FastSubsumesConsideringDomain(nsIPrincipal* aOther) {
  // If neither of the principals have document.domain set, we hand off to
  // FastSubsumes() which has fast paths for some special cases. Otherwise, we
  // fall back to the slow path below.
  if (!mHasExplicitDomain && !Cast(aOther)->mHasExplicitDomain) {
    return FastSubsumes(aOther);
  }

  return Subsumes(aOther, ConsiderDocumentDomain);
}

inline bool BasePrincipal::FastSubsumesIgnoringFPD(
    nsIPrincipal* aOther, DocumentDomainConsideration aConsideration) {
  if (Kind() == eCodebasePrincipal &&
      !dom::ChromeUtils::IsOriginAttributesEqualIgnoringFPD(
          mOriginAttributes, Cast(aOther)->mOriginAttributes)) {
    return false;
  }

  return SubsumesInternal(aOther, aConsideration);
}

inline bool BasePrincipal::FastSubsumesIgnoringFPD(nsIPrincipal* aOther) {
  return FastSubsumesIgnoringFPD(aOther, DontConsiderDocumentDomain);
}

inline bool BasePrincipal::FastSubsumesConsideringDomainIgnoringFPD(
    nsIPrincipal* aOther) {
  return FastSubsumesIgnoringFPD(aOther, ConsiderDocumentDomain);
}

inline bool BasePrincipal::IsSystemPrincipal() const {
  return Kind() == eSystemPrincipal;
}

}  // namespace mozilla

inline bool nsIPrincipal::IsSystemPrincipal() const {
  return mozilla::BasePrincipal::Cast(this)->IsSystemPrincipal();
}

#endif /* mozilla_BasePrincipal_h */