WrapperFactory.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
  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. #include "WaiveXrayWrapper.h"
  6. #include "FilteringWrapper.h"
  7. #include "AddonWrapper.h"
  8. #include "XrayWrapper.h"
  9. #include "AccessCheck.h"
  10. #include "XPCWrapper.h"
  11. #include "ChromeObjectWrapper.h"
  12. #include "WrapperFactory.h"
  13. #include "xpcprivate.h"
  14. #include "XPCMaps.h"
  15. #include "mozilla/dom/BindingUtils.h"
  16. #include "jsfriendapi.h"
  17. #include "mozilla/jsipc/CrossProcessObjectWrappers.h"
  18. #include "mozilla/Likely.h"
  19. #include "mozilla/dom/ScriptSettings.h"
  20. #include "nsContentUtils.h"
  21. #include "nsXULAppAPI.h"
  22. using namespace JS;
  23. using namespace js;
  24. using namespace mozilla;
  25. namespace xpc {
  26. // When chrome pulls a naked property across the membrane using
  27. // .wrappedJSObject, we want it to cross the membrane into the
  28. // chrome compartment without automatically being wrapped into an
  29. // X-ray wrapper. We achieve this by wrapping it into a special
  30. // transparent wrapper in the origin (non-chrome) compartment. When
  31. // an object with that special wrapper applied crosses into chrome,
  32. // we know to not apply an X-ray wrapper.
  33. const Wrapper XrayWaiver(WrapperFactory::WAIVE_XRAY_WRAPPER_FLAG);
  34. // When objects for which we waived the X-ray wrapper cross into
  35. // chrome, we wrap them into a special cross-compartment wrapper
  36. // that transitively extends the waiver to all properties we get
  37. // off it.
  38. const WaiveXrayWrapper WaiveXrayWrapper::singleton(0);
  39. bool
  40. WrapperFactory::IsCOW(JSObject* obj)
  41. {
  42. return IsWrapper(obj) &&
  43. Wrapper::wrapperHandler(obj) == &ChromeObjectWrapper::singleton;
  44. }
  45. JSObject*
  46. WrapperFactory::GetXrayWaiver(HandleObject obj)
  47. {
  48. // Object should come fully unwrapped but outerized.
  49. MOZ_ASSERT(obj == UncheckedUnwrap(obj));
  50. MOZ_ASSERT(!js::IsWindow(obj));
  51. XPCWrappedNativeScope* scope = ObjectScope(obj);
  52. MOZ_ASSERT(scope);
  53. if (!scope->mWaiverWrapperMap)
  54. return nullptr;
  55. return scope->mWaiverWrapperMap->Find(obj);
  56. }
  57. JSObject*
  58. WrapperFactory::CreateXrayWaiver(JSContext* cx, HandleObject obj)
  59. {
  60. // The caller is required to have already done a lookup.
  61. // NB: This implictly performs the assertions of GetXrayWaiver.
  62. MOZ_ASSERT(!GetXrayWaiver(obj));
  63. XPCWrappedNativeScope* scope = ObjectScope(obj);
  64. JSAutoCompartment ac(cx, obj);
  65. JSObject* waiver = Wrapper::New(cx, obj, &XrayWaiver);
  66. if (!waiver)
  67. return nullptr;
  68. // Add the new waiver to the map. It's important that we only ever have
  69. // one waiver for the lifetime of the target object.
  70. if (!scope->mWaiverWrapperMap) {
  71. scope->mWaiverWrapperMap =
  72. JSObject2JSObjectMap::newMap(XPC_WRAPPER_MAP_LENGTH);
  73. }
  74. if (!scope->mWaiverWrapperMap->Add(cx, obj, waiver))
  75. return nullptr;
  76. return waiver;
  77. }
  78. JSObject*
  79. WrapperFactory::WaiveXray(JSContext* cx, JSObject* objArg)
  80. {
  81. RootedObject obj(cx, objArg);
  82. obj = UncheckedUnwrap(obj);
  83. MOZ_ASSERT(!js::IsWindow(obj));
  84. JSObject* waiver = GetXrayWaiver(obj);
  85. if (!waiver) {
  86. waiver = CreateXrayWaiver(cx, obj);
  87. }
  88. MOZ_ASSERT(!ObjectIsMarkedGray(waiver));
  89. return waiver;
  90. }
  91. /* static */ bool
  92. WrapperFactory::AllowWaiver(JSCompartment* target, JSCompartment* origin)
  93. {
  94. return CompartmentPrivate::Get(target)->allowWaivers &&
  95. AccessCheck::subsumes(target, origin);
  96. }
  97. /* static */ bool
  98. WrapperFactory::AllowWaiver(JSObject* wrapper) {
  99. MOZ_ASSERT(js::IsCrossCompartmentWrapper(wrapper));
  100. return AllowWaiver(js::GetObjectCompartment(wrapper),
  101. js::GetObjectCompartment(js::UncheckedUnwrap(wrapper)));
  102. }
  103. inline bool
  104. ShouldWaiveXray(JSContext* cx, JSObject* originalObj)
  105. {
  106. unsigned flags;
  107. (void) js::UncheckedUnwrap(originalObj, /* stopAtWindowProxy = */ true, &flags);
  108. // If the original object did not point through an Xray waiver, we're done.
  109. if (!(flags & WrapperFactory::WAIVE_XRAY_WRAPPER_FLAG))
  110. return false;
  111. // If the original object was not a cross-compartment wrapper, that means
  112. // that the caller explicitly created a waiver. Preserve it so that things
  113. // like WaiveXrayAndWrap work.
  114. if (!(flags & Wrapper::CROSS_COMPARTMENT))
  115. return true;
  116. // Otherwise, this is a case of explicitly passing a wrapper across a
  117. // compartment boundary. In that case, we only want to preserve waivers
  118. // in transactions between same-origin compartments.
  119. JSCompartment* oldCompartment = js::GetObjectCompartment(originalObj);
  120. JSCompartment* newCompartment = js::GetContextCompartment(cx);
  121. bool sameOrigin =
  122. AccessCheck::subsumesConsideringDomain(oldCompartment, newCompartment) &&
  123. AccessCheck::subsumesConsideringDomain(newCompartment, oldCompartment);
  124. return sameOrigin;
  125. }
  126. void
  127. WrapperFactory::PrepareForWrapping(JSContext* cx, HandleObject scope,
  128. HandleObject objArg, HandleObject objectPassedToWrap,
  129. MutableHandleObject retObj)
  130. {
  131. bool waive = ShouldWaiveXray(cx, objectPassedToWrap);
  132. RootedObject obj(cx, objArg);
  133. retObj.set(nullptr);
  134. // Outerize any raw inner objects at the entry point here, so that we don't
  135. // have to worry about them for the rest of the wrapping code.
  136. if (js::IsWindow(obj)) {
  137. JSAutoCompartment ac(cx, obj);
  138. obj = js::ToWindowProxyIfWindow(obj);
  139. MOZ_ASSERT(obj);
  140. // ToWindowProxyIfWindow can return a CCW if |obj| was a
  141. // navigated-away-from Window. Strip any CCWs.
  142. obj = js::UncheckedUnwrap(obj);
  143. if (JS_IsDeadWrapper(obj)) {
  144. JS_ReportErrorASCII(cx, "Can't wrap dead object");
  145. return;
  146. }
  147. MOZ_ASSERT(js::IsWindowProxy(obj));
  148. // We crossed a compartment boundary there, so may now have a gray
  149. // object. This function is not allowed to return gray objects, so
  150. // don't do that.
  151. ExposeObjectToActiveJS(obj);
  152. }
  153. // If we've got a WindowProxy, there's nothing special that needs to be
  154. // done here, and we can move on to the next phase of wrapping. We handle
  155. // this case first to allow us to assert against wrappers below.
  156. if (js::IsWindowProxy(obj)) {
  157. retObj.set(waive ? WaiveXray(cx, obj) : obj);
  158. return;
  159. }
  160. // Here are the rules for wrapping:
  161. // We should never get a proxy here (the JS engine unwraps those for us).
  162. MOZ_ASSERT(!IsWrapper(obj));
  163. // Now, our object is ready to be wrapped, but several objects (notably
  164. // nsJSIIDs) have a wrapper per scope. If we are about to wrap one of
  165. // those objects in a security wrapper, then we need to hand back the
  166. // wrapper for the new scope instead. Also, global objects don't move
  167. // between scopes so for those we also want to return the wrapper. So...
  168. if (!IS_WN_REFLECTOR(obj) || JS_IsGlobalObject(obj)) {
  169. retObj.set(waive ? WaiveXray(cx, obj) : obj);
  170. return;
  171. }
  172. XPCWrappedNative* wn = XPCWrappedNative::Get(obj);
  173. JSAutoCompartment ac(cx, obj);
  174. XPCCallContext ccx(cx, obj);
  175. RootedObject wrapScope(cx, scope);
  176. {
  177. if (NATIVE_HAS_FLAG(&ccx, WantPreCreate)) {
  178. // We have a precreate hook. This object might enforce that we only
  179. // ever create JS object for it.
  180. // Note: this penalizes objects that only have one wrapper, but are
  181. // being accessed across compartments. We would really prefer to
  182. // replace the above code with a test that says "do you only have one
  183. // wrapper?"
  184. nsresult rv = wn->GetScriptableInfo()->GetCallback()->
  185. PreCreate(wn->Native(), cx, scope, wrapScope.address());
  186. if (NS_FAILED(rv)) {
  187. retObj.set(waive ? WaiveXray(cx, obj) : obj);
  188. return;
  189. }
  190. // If the handed back scope differs from the passed-in scope and is in
  191. // a separate compartment, then this object is explicitly requesting
  192. // that we don't create a second JS object for it: create a security
  193. // wrapper.
  194. if (js::GetObjectCompartment(scope) != js::GetObjectCompartment(wrapScope)) {
  195. retObj.set(waive ? WaiveXray(cx, obj) : obj);
  196. return;
  197. }
  198. RootedObject currentScope(cx, JS_GetGlobalForObject(cx, obj));
  199. if (MOZ_UNLIKELY(wrapScope != currentScope)) {
  200. // The wrapper claims it wants to be in the new scope, but
  201. // currently has a reflection that lives in the old scope. This
  202. // can mean one of two things, both of which are rare:
  203. //
  204. // 1 - The object has a PreCreate hook (we checked for it above),
  205. // but is deciding to request one-wrapper-per-scope (rather than
  206. // one-wrapper-per-native) for some reason. Usually, a PreCreate
  207. // hook indicates one-wrapper-per-native. In this case we want to
  208. // make a new wrapper in the new scope.
  209. //
  210. // 2 - We're midway through wrapper reparenting. The document has
  211. // moved to a new scope, but |wn| hasn't been moved yet, and
  212. // we ended up calling JS_WrapObject() on its JS object. In this
  213. // case, we want to return the existing wrapper.
  214. //
  215. // So we do a trick: call PreCreate _again_, but say that we're
  216. // wrapping for the old scope, rather than the new one. If (1) is
  217. // the case, then PreCreate will return the scope we pass to it
  218. // (the old scope). If (2) is the case, PreCreate will return the
  219. // scope of the document (the new scope).
  220. RootedObject probe(cx);
  221. rv = wn->GetScriptableInfo()->GetCallback()->
  222. PreCreate(wn->Native(), cx, currentScope, probe.address());
  223. // Check for case (2).
  224. if (probe != currentScope) {
  225. MOZ_ASSERT(probe == wrapScope);
  226. retObj.set(waive ? WaiveXray(cx, obj) : obj);
  227. return;
  228. }
  229. // Ok, must be case (1). Fall through and create a new wrapper.
  230. }
  231. // Nasty hack for late-breaking bug 781476. This will confuse identity checks,
  232. // but it's probably better than any of our alternatives.
  233. //
  234. // Note: We have to ignore domain here. The JS engine assumes that, given a
  235. // compartment c, if c->wrap(x) returns a cross-compartment wrapper at time t0,
  236. // it will also return a cross-compartment wrapper for any time t1 > t0 unless
  237. // an explicit transplant is performed. In particular, wrapper recomputation
  238. // assumes that recomputing a wrapper will always result in a wrapper.
  239. //
  240. // This doesn't actually pose a security issue, because we'll still compute
  241. // the correct (opaque) wrapper for the object below given the security
  242. // characteristics of the two compartments.
  243. if (!AccessCheck::isChrome(js::GetObjectCompartment(wrapScope)) &&
  244. AccessCheck::subsumes(js::GetObjectCompartment(wrapScope),
  245. js::GetObjectCompartment(obj)))
  246. {
  247. retObj.set(waive ? WaiveXray(cx, obj) : obj);
  248. return;
  249. }
  250. }
  251. }
  252. // This public WrapNativeToJSVal API enters the compartment of 'wrapScope'
  253. // so we don't have to.
  254. RootedValue v(cx);
  255. nsresult rv =
  256. nsXPConnect::XPConnect()->WrapNativeToJSVal(cx, wrapScope, wn->Native(), nullptr,
  257. &NS_GET_IID(nsISupports), false, &v);
  258. if (NS_FAILED(rv)) {
  259. return;
  260. }
  261. obj.set(&v.toObject());
  262. MOZ_ASSERT(IS_WN_REFLECTOR(obj), "bad object");
  263. MOZ_ASSERT(!ObjectIsMarkedGray(obj), "Should never return gray reflectors");
  264. // Because the underlying native didn't have a PreCreate hook, we had
  265. // to a new (or possibly pre-existing) XPCWN in our compartment.
  266. // This could be a problem for chrome code that passes XPCOM objects
  267. // across compartments, because the effects of QI would disappear across
  268. // compartments.
  269. //
  270. // So whenever we pull an XPCWN across compartments in this manner, we
  271. // give the destination object the union of the two native sets. We try
  272. // to do this cleverly in the common case to avoid too much overhead.
  273. XPCWrappedNative* newwn = XPCWrappedNative::Get(obj);
  274. RefPtr<XPCNativeSet> unionSet = XPCNativeSet::GetNewOrUsed(newwn->GetSet(),
  275. wn->GetSet(), false);
  276. if (!unionSet) {
  277. return;
  278. }
  279. newwn->SetSet(unionSet.forget());
  280. retObj.set(waive ? WaiveXray(cx, obj) : obj);
  281. }
  282. #ifdef DEBUG
  283. static void
  284. DEBUG_CheckUnwrapSafety(HandleObject obj, const js::Wrapper* handler,
  285. JSCompartment* origin, JSCompartment* target)
  286. {
  287. if (AccessCheck::isChrome(target) || xpc::IsUniversalXPConnectEnabled(target)) {
  288. // If the caller is chrome (or effectively so), unwrap should always be allowed.
  289. MOZ_ASSERT(!handler->hasSecurityPolicy());
  290. } else if (CompartmentPrivate::Get(origin)->forcePermissiveCOWs) {
  291. // Similarly, if this is a privileged scope that has opted to make itself
  292. // accessible to the world (allowed only during automation), unwrap should
  293. // be allowed.
  294. MOZ_ASSERT(!handler->hasSecurityPolicy());
  295. } else {
  296. // Otherwise, it should depend on whether the target subsumes the origin.
  297. MOZ_ASSERT(handler->hasSecurityPolicy() == !AccessCheck::subsumesConsideringDomain(target, origin));
  298. }
  299. }
  300. #else
  301. #define DEBUG_CheckUnwrapSafety(obj, handler, origin, target) {}
  302. #endif
  303. static const Wrapper*
  304. SelectWrapper(bool securityWrapper, bool wantXrays, XrayType xrayType,
  305. bool waiveXrays, bool originIsXBLScope, JSObject* obj)
  306. {
  307. // Waived Xray uses a modified CCW that has transparent behavior but
  308. // transitively waives Xrays on arguments.
  309. if (waiveXrays) {
  310. MOZ_ASSERT(!securityWrapper);
  311. return &WaiveXrayWrapper::singleton;
  312. }
  313. // If we don't want or can't use Xrays, select a wrapper that's either
  314. // entirely transparent or entirely opaque.
  315. if (!wantXrays || xrayType == NotXray) {
  316. if (!securityWrapper)
  317. return &CrossCompartmentWrapper::singleton;
  318. return &FilteringWrapper<CrossCompartmentSecurityWrapper, Opaque>::singleton;
  319. }
  320. // Ok, we're using Xray. If this isn't a security wrapper, use the permissive
  321. // version and skip the filter.
  322. if (!securityWrapper) {
  323. if (xrayType == XrayForWrappedNative)
  324. return &PermissiveXrayXPCWN::singleton;
  325. else if (xrayType == XrayForDOMObject)
  326. return &PermissiveXrayDOM::singleton;
  327. else if (xrayType == XrayForJSObject)
  328. return &PermissiveXrayJS::singleton;
  329. MOZ_ASSERT(xrayType == XrayForOpaqueObject);
  330. return &PermissiveXrayOpaque::singleton;
  331. }
  332. // This is a security wrapper. Use the security versions and filter.
  333. if (xrayType == XrayForDOMObject && IdentifyCrossOriginObject(obj) != CrossOriginOpaque)
  334. return &FilteringWrapper<CrossOriginXrayWrapper,
  335. CrossOriginAccessiblePropertiesOnly>::singleton;
  336. // There's never any reason to expose other objects to non-subsuming actors.
  337. // Just use an opaque wrapper in these cases.
  338. //
  339. // In general, we don't want opaque function wrappers to be callable.
  340. // But in the case of XBL, we rely on content being able to invoke
  341. // functions exposed from the XBL scope. We could remove this exception,
  342. // if needed, by using ExportFunction to generate the content-side
  343. // representations of XBL methods.
  344. if (xrayType == XrayForJSObject && originIsXBLScope)
  345. return &FilteringWrapper<CrossCompartmentSecurityWrapper, OpaqueWithCall>::singleton;
  346. return &FilteringWrapper<CrossCompartmentSecurityWrapper, Opaque>::singleton;
  347. }
  348. static const Wrapper*
  349. SelectAddonWrapper(JSContext* cx, HandleObject obj, const Wrapper* wrapper)
  350. {
  351. JSAddonId* originAddon = JS::AddonIdOfObject(obj);
  352. JSAddonId* targetAddon = JS::AddonIdOfObject(JS::CurrentGlobalOrNull(cx));
  353. MOZ_ASSERT(AccessCheck::isChrome(JS::CurrentGlobalOrNull(cx)));
  354. MOZ_ASSERT(targetAddon);
  355. if (targetAddon == originAddon)
  356. return wrapper;
  357. // Add-on interposition only supports certain wrapper types, so we check if
  358. // we would have used one of the supported ones.
  359. if (wrapper == &CrossCompartmentWrapper::singleton)
  360. return &AddonWrapper<CrossCompartmentWrapper>::singleton;
  361. else if (wrapper == &PermissiveXrayXPCWN::singleton)
  362. return &AddonWrapper<PermissiveXrayXPCWN>::singleton;
  363. else if (wrapper == &PermissiveXrayDOM::singleton)
  364. return &AddonWrapper<PermissiveXrayDOM>::singleton;
  365. // |wrapper| is not supported for interposition, so we don't do it.
  366. return wrapper;
  367. }
  368. JSObject*
  369. WrapperFactory::Rewrap(JSContext* cx, HandleObject existing, HandleObject obj)
  370. {
  371. MOZ_ASSERT(!IsWrapper(obj) ||
  372. GetProxyHandler(obj) == &XrayWaiver ||
  373. js::IsWindowProxy(obj),
  374. "wrapped object passed to rewrap");
  375. MOZ_ASSERT(!XrayUtils::IsXPCWNHolderClass(JS_GetClass(obj)), "trying to wrap a holder");
  376. MOZ_ASSERT(!js::IsWindow(obj));
  377. MOZ_ASSERT(dom::IsJSAPIActive());
  378. // Compute the information we need to select the right wrapper.
  379. JSCompartment* origin = js::GetObjectCompartment(obj);
  380. JSCompartment* target = js::GetContextCompartment(cx);
  381. bool originIsChrome = AccessCheck::isChrome(origin);
  382. bool targetIsChrome = AccessCheck::isChrome(target);
  383. bool originSubsumesTarget = AccessCheck::subsumesConsideringDomain(origin, target);
  384. bool targetSubsumesOrigin = AccessCheck::subsumesConsideringDomain(target, origin);
  385. bool sameOrigin = targetSubsumesOrigin && originSubsumesTarget;
  386. XrayType xrayType = GetXrayType(obj);
  387. const Wrapper* wrapper;
  388. //
  389. // First, handle the special cases.
  390. //
  391. // If UniversalXPConnect is enabled, this is just some dumb mochitest. Use
  392. // a vanilla CCW.
  393. if (xpc::IsUniversalXPConnectEnabled(target)) {
  394. CrashIfNotInAutomation();
  395. wrapper = &CrossCompartmentWrapper::singleton;
  396. }
  397. // Let the SpecialPowers scope make its stuff easily accessible to content.
  398. else if (CompartmentPrivate::Get(origin)->forcePermissiveCOWs) {
  399. CrashIfNotInAutomation();
  400. wrapper = &CrossCompartmentWrapper::singleton;
  401. }
  402. // Special handling for chrome objects being exposed to content.
  403. else if (originIsChrome && !targetIsChrome) {
  404. // If this is a chrome function being exposed to content, we need to allow
  405. // call (but nothing else). We allow CPOWs that purport to be function's
  406. // here, but only in the content process.
  407. if ((IdentifyStandardInstance(obj) == JSProto_Function ||
  408. (jsipc::IsCPOW(obj) && JS::IsCallable(obj) &&
  409. XRE_IsContentProcess())))
  410. {
  411. wrapper = &FilteringWrapper<CrossCompartmentSecurityWrapper, OpaqueWithCall>::singleton;
  412. }
  413. // For Vanilla JSObjects exposed from chrome to content, we use a wrapper
  414. // that supports __exposedProps__. We'd like to get rid of these eventually,
  415. // but in their current form they don't cause much trouble.
  416. else if (IdentifyStandardInstance(obj) == JSProto_Object) {
  417. wrapper = &ChromeObjectWrapper::singleton;
  418. }
  419. // Otherwise we get an opaque wrapper.
  420. else {
  421. wrapper = &FilteringWrapper<CrossCompartmentSecurityWrapper, Opaque>::singleton;
  422. }
  423. }
  424. //
  425. // Now, handle the regular cases.
  426. //
  427. // These are wrappers we can compute using a rule-based approach. In order
  428. // to do so, we need to compute some parameters.
  429. //
  430. else {
  431. // The wrapper is a security wrapper (protecting the wrappee) if and
  432. // only if the target does not subsume the origin.
  433. bool securityWrapper = !targetSubsumesOrigin;
  434. // Xrays are warranted if either the target or the origin don't trust
  435. // each other. This is generally the case, unless the two are same-origin
  436. // and the caller has not requested same-origin Xrays.
  437. //
  438. // Xrays are a bidirectional protection, since it affords clarity to the
  439. // caller and privacy to the callee.
  440. bool sameOriginXrays = CompartmentPrivate::Get(origin)->wantXrays ||
  441. CompartmentPrivate::Get(target)->wantXrays;
  442. bool wantXrays = !sameOrigin || sameOriginXrays;
  443. // If Xrays are warranted, the caller may waive them for non-security
  444. // wrappers (unless explicitly forbidden from doing so).
  445. bool waiveXrays = wantXrays && !securityWrapper &&
  446. CompartmentPrivate::Get(target)->allowWaivers &&
  447. HasWaiveXrayFlag(obj);
  448. // We have slightly different behavior for the case when the object
  449. // being wrapped is in an XBL scope.
  450. bool originIsContentXBLScope = IsContentXBLScope(origin);
  451. wrapper = SelectWrapper(securityWrapper, wantXrays, xrayType, waiveXrays,
  452. originIsContentXBLScope, obj);
  453. // If we want to apply add-on interposition in the target compartment,
  454. // then we try to "upgrade" the wrapper to an interposing one.
  455. if (CompartmentPrivate::Get(target)->scope->HasInterposition())
  456. wrapper = SelectAddonWrapper(cx, obj, wrapper);
  457. }
  458. if (!targetSubsumesOrigin) {
  459. // Do a belt-and-suspenders check against exposing eval()/Function() to
  460. // non-subsuming content.
  461. if (JSFunction* fun = JS_GetObjectFunction(obj)) {
  462. if (JS_IsBuiltinEvalFunction(fun) || JS_IsBuiltinFunctionConstructor(fun)) {
  463. NS_WARNING("Trying to expose eval or Function to non-subsuming content!");
  464. wrapper = &FilteringWrapper<CrossCompartmentSecurityWrapper, Opaque>::singleton;
  465. }
  466. }
  467. }
  468. DEBUG_CheckUnwrapSafety(obj, wrapper, origin, target);
  469. if (existing)
  470. return Wrapper::Renew(existing, obj, wrapper);
  471. return Wrapper::New(cx, obj, wrapper);
  472. }
  473. // Call WaiveXrayAndWrap when you have a JS object that you don't want to be
  474. // wrapped in an Xray wrapper. cx->compartment is the compartment that will be
  475. // using the returned object. If the object to be wrapped is already in the
  476. // correct compartment, then this returns the unwrapped object.
  477. bool
  478. WrapperFactory::WaiveXrayAndWrap(JSContext* cx, MutableHandleValue vp)
  479. {
  480. if (vp.isPrimitive())
  481. return JS_WrapValue(cx, vp);
  482. RootedObject obj(cx, &vp.toObject());
  483. if (!WaiveXrayAndWrap(cx, &obj))
  484. return false;
  485. vp.setObject(*obj);
  486. return true;
  487. }
  488. bool
  489. WrapperFactory::WaiveXrayAndWrap(JSContext* cx, MutableHandleObject argObj)
  490. {
  491. MOZ_ASSERT(argObj);
  492. RootedObject obj(cx, js::UncheckedUnwrap(argObj));
  493. MOZ_ASSERT(!js::IsWindow(obj));
  494. if (js::IsObjectInContextCompartment(obj, cx)) {
  495. argObj.set(obj);
  496. return true;
  497. }
  498. // Even though waivers have no effect on access by scopes that don't subsume
  499. // the underlying object, good defense-in-depth dictates that we should avoid
  500. // handing out waivers to callers that can't use them. The transitive waiving
  501. // machinery unconditionally calls WaiveXrayAndWrap on return values from
  502. // waived functions, even though the return value might be not be same-origin
  503. // with the function. So if we find ourselves trying to create a waiver for
  504. // |cx|, we should check whether the caller has any business with waivers
  505. // to things in |obj|'s compartment.
  506. JSCompartment* target = js::GetContextCompartment(cx);
  507. JSCompartment* origin = js::GetObjectCompartment(obj);
  508. obj = AllowWaiver(target, origin) ? WaiveXray(cx, obj) : obj;
  509. if (!obj)
  510. return false;
  511. if (!JS_WrapObject(cx, &obj))
  512. return false;
  513. argObj.set(obj);
  514. return true;
  515. }
  516. /*
  517. * Calls to JS_TransplantObject* should go through these helpers here so that
  518. * waivers get fixed up properly.
  519. */
  520. static bool
  521. FixWaiverAfterTransplant(JSContext* cx, HandleObject oldWaiver, HandleObject newobj)
  522. {
  523. MOZ_ASSERT(Wrapper::wrapperHandler(oldWaiver) == &XrayWaiver);
  524. MOZ_ASSERT(!js::IsCrossCompartmentWrapper(newobj));
  525. // Create a waiver in the new compartment. We know there's not one already
  526. // because we _just_ transplanted, which means that |newobj| was either
  527. // created from scratch, or was previously cross-compartment wrapper (which
  528. // should have no waiver). CreateXrayWaiver asserts this.
  529. JSObject* newWaiver = WrapperFactory::CreateXrayWaiver(cx, newobj);
  530. if (!newWaiver)
  531. return false;
  532. // Update all the cross-compartment references to oldWaiver to point to
  533. // newWaiver.
  534. if (!js::RemapAllWrappersForObject(cx, oldWaiver, newWaiver))
  535. return false;
  536. // There should be no same-compartment references to oldWaiver, and we
  537. // just remapped all cross-compartment references. It's dead, so we can
  538. // remove it from the map.
  539. XPCWrappedNativeScope* scope = ObjectScope(oldWaiver);
  540. JSObject* key = Wrapper::wrappedObject(oldWaiver);
  541. MOZ_ASSERT(scope->mWaiverWrapperMap->Find(key));
  542. scope->mWaiverWrapperMap->Remove(key);
  543. return true;
  544. }
  545. JSObject*
  546. TransplantObject(JSContext* cx, JS::HandleObject origobj, JS::HandleObject target)
  547. {
  548. RootedObject oldWaiver(cx, WrapperFactory::GetXrayWaiver(origobj));
  549. RootedObject newIdentity(cx, JS_TransplantObject(cx, origobj, target));
  550. if (!newIdentity || !oldWaiver)
  551. return newIdentity;
  552. if (!FixWaiverAfterTransplant(cx, oldWaiver, newIdentity))
  553. return nullptr;
  554. return newIdentity;
  555. }
  556. nsIGlobalObject*
  557. NativeGlobal(JSObject* obj)
  558. {
  559. obj = js::GetGlobalForObjectCrossCompartment(obj);
  560. // Every global needs to hold a native as its private or be a
  561. // WebIDL object with an nsISupports DOM object.
  562. MOZ_ASSERT((GetObjectClass(obj)->flags & (JSCLASS_PRIVATE_IS_NSISUPPORTS |
  563. JSCLASS_HAS_PRIVATE)) ||
  564. dom::UnwrapDOMObjectToISupports(obj));
  565. nsISupports* native = dom::UnwrapDOMObjectToISupports(obj);
  566. if (!native) {
  567. native = static_cast<nsISupports*>(js::GetObjectPrivate(obj));
  568. MOZ_ASSERT(native);
  569. // In some cases (like for windows) it is a wrapped native,
  570. // in other cases (sandboxes, backstage passes) it's just
  571. // a direct pointer to the native. If it's a wrapped native
  572. // let's unwrap it first.
  573. if (nsCOMPtr<nsIXPConnectWrappedNative> wn = do_QueryInterface(native)) {
  574. native = wn->Native();
  575. }
  576. }
  577. nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(native);
  578. MOZ_ASSERT(global, "Native held by global needs to implement nsIGlobalObject!");
  579. return global;
  580. }
  581. } // namespace xpc