/
nsScriptSecurityManager.cpp
2659 lines (2304 loc) · 86.6 KB
/
nsScriptSecurityManager.cpp
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* vim: set ts=4 et sw=4 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/. */
#include "nsScriptSecurityManager.h"
#include "mozilla/ArrayUtils.h"
#include "js/OldDebugAPI.h"
#include "xpcprivate.h"
#include "XPCWrapper.h"
#include "nsIServiceManager.h"
#include "nsIScriptObjectPrincipal.h"
#include "nsIScriptContext.h"
#include "nsIURL.h"
#include "nsINestedURI.h"
#include "nspr.h"
#include "nsJSPrincipals.h"
#include "nsSystemPrincipal.h"
#include "nsPrincipal.h"
#include "nsNullPrincipal.h"
#include "DomainPolicy.h"
#include "nsXPIDLString.h"
#include "nsCRT.h"
#include "nsCRTGlue.h"
#include "nsError.h"
#include "nsDOMCID.h"
#include "nsIXPConnect.h"
#include "nsIXPCSecurityManager.h"
#include "nsTextFormatter.h"
#include "nsIStringBundle.h"
#include "nsNetUtil.h"
#include "nsIProperties.h"
#include "nsDirectoryServiceDefs.h"
#include "nsIFile.h"
#include "nsIFileURL.h"
#include "nsIZipReader.h"
#include "nsIXPConnect.h"
#include "nsIScriptGlobalObject.h"
#include "nsPIDOMWindow.h"
#include "nsIDocShell.h"
#include "nsIPrompt.h"
#include "nsIWindowWatcher.h"
#include "nsIConsoleService.h"
#include "nsISecurityCheckedComponent.h"
#include "nsIJSRuntimeService.h"
#include "nsIObserverService.h"
#include "nsIContent.h"
#include "nsAutoPtr.h"
#include "nsDOMJSUtils.h"
#include "nsAboutProtocolUtils.h"
#include "nsIClassInfo.h"
#include "nsIURIFixup.h"
#include "nsCDefaultURIFixup.h"
#include "nsIChromeRegistry.h"
#include "nsIContentSecurityPolicy.h"
#include "nsIAsyncVerifyRedirectCallback.h"
#include "mozilla/Preferences.h"
#include "mozilla/dom/BindingUtils.h"
#include <stdint.h>
#include "mozilla/ClearOnShutdown.h"
#include "mozilla/StaticPtr.h"
#include "nsContentUtils.h"
#include "nsCxPusher.h"
#include "nsJSUtils.h"
// This should be probably defined on some other place... but I couldn't find it
#define WEBAPPS_PERM_NAME "webapps-manage"
using namespace mozilla;
using namespace mozilla::dom;
static NS_DEFINE_CID(kZipReaderCID, NS_ZIPREADER_CID);
nsIIOService *nsScriptSecurityManager::sIOService = nullptr;
nsIStringBundle *nsScriptSecurityManager::sStrBundle = nullptr;
JSRuntime *nsScriptSecurityManager::sRuntime = 0;
bool nsScriptSecurityManager::sStrictFileOriginPolicy = true;
// Lazily initialized. Use the getter below.
static jsid sEnabledID = JSID_VOID;
static JS::HandleId
EnabledID()
{
if (sEnabledID != JSID_VOID)
return JS::HandleId::fromMarkedLocation(&sEnabledID);
AutoSafeJSContext cx;
sEnabledID = INTERNED_STRING_TO_JSID(cx, JS_InternString(cx, "enabled"));
return JS::HandleId::fromMarkedLocation(&sEnabledID);
}
bool
nsScriptSecurityManager::SubjectIsPrivileged()
{
JSContext *cx = GetCurrentJSContext();
if (cx && xpc::IsUniversalXPConnectEnabled(cx))
return true;
bool isSystem = false;
return NS_SUCCEEDED(SubjectPrincipalIsSystem(&isSystem)) && isSystem;
}
///////////////////////////
// Convenience Functions //
///////////////////////////
// Result of this function should not be freed.
static inline const PRUnichar *
IDToString(JSContext *cx, jsid id_)
{
JS::RootedId id(cx, id_);
if (JSID_IS_STRING(id))
return JS_GetInternedStringChars(JSID_TO_STRING(id));
JS::Rooted<JS::Value> idval(cx);
if (!JS_IdToValue(cx, id, idval.address()))
return nullptr;
JSString *str = JS::ToString(cx, idval);
if(!str)
return nullptr;
return JS_GetStringCharsZ(cx, str);
}
class nsAutoInPrincipalDomainOriginSetter {
public:
nsAutoInPrincipalDomainOriginSetter() {
++sInPrincipalDomainOrigin;
}
~nsAutoInPrincipalDomainOriginSetter() {
--sInPrincipalDomainOrigin;
}
static uint32_t sInPrincipalDomainOrigin;
};
uint32_t nsAutoInPrincipalDomainOriginSetter::sInPrincipalDomainOrigin;
static
nsresult
GetOriginFromURI(nsIURI* aURI, nsACString& aOrigin)
{
if (nsAutoInPrincipalDomainOriginSetter::sInPrincipalDomainOrigin > 1) {
// Allow a single recursive call to GetPrincipalDomainOrigin, since that
// might be happening on a different principal from the first call. But
// after that, cut off the recursion; it just indicates that something
// we're doing in this method causes us to reenter a security check here.
return NS_ERROR_NOT_AVAILABLE;
}
nsAutoInPrincipalDomainOriginSetter autoSetter;
nsCOMPtr<nsIURI> uri = NS_GetInnermostURI(aURI);
NS_ENSURE_TRUE(uri, NS_ERROR_UNEXPECTED);
nsAutoCString hostPort;
nsresult rv = uri->GetHostPort(hostPort);
if (NS_SUCCEEDED(rv)) {
nsAutoCString scheme;
rv = uri->GetScheme(scheme);
NS_ENSURE_SUCCESS(rv, rv);
aOrigin = scheme + NS_LITERAL_CSTRING("://") + hostPort;
}
else {
// Some URIs (e.g., nsSimpleURI) don't support host. Just
// get the full spec.
rv = uri->GetSpec(aOrigin);
NS_ENSURE_SUCCESS(rv, rv);
}
return NS_OK;
}
static
nsresult
GetPrincipalDomainOrigin(nsIPrincipal* aPrincipal,
nsACString& aOrigin)
{
nsCOMPtr<nsIURI> uri;
aPrincipal->GetDomain(getter_AddRefs(uri));
if (!uri) {
aPrincipal->GetURI(getter_AddRefs(uri));
}
NS_ENSURE_TRUE(uri, NS_ERROR_UNEXPECTED);
return GetOriginFromURI(uri, aOrigin);
}
inline void SetPendingException(JSContext *cx, const char *aMsg)
{
JS_ReportError(cx, "%s", aMsg);
}
inline void SetPendingException(JSContext *cx, const PRUnichar *aMsg)
{
JS_ReportError(cx, "%hs", aMsg);
}
// DomainPolicy members
uint32_t DomainPolicy::sGeneration = 0;
// Helper class to get stuff from the ClassInfo and not waste extra time with
// virtual method calls for things it has already gotten
class ClassInfoData
{
public:
ClassInfoData(nsIClassInfo *aClassInfo, const char *aName)
: mClassInfo(aClassInfo),
mName(const_cast<char *>(aName)),
mDidGetFlags(false),
mMustFreeName(false)
{
}
~ClassInfoData()
{
if (mMustFreeName)
nsMemory::Free(mName);
}
uint32_t GetFlags()
{
if (!mDidGetFlags) {
if (mClassInfo) {
nsresult rv = mClassInfo->GetFlags(&mFlags);
if (NS_FAILED(rv)) {
mFlags = 0;
}
} else {
mFlags = 0;
}
mDidGetFlags = true;
}
return mFlags;
}
bool IsDOMClass()
{
return !!(GetFlags() & nsIClassInfo::DOM_OBJECT);
}
const char* GetName()
{
if (!mName) {
if (mClassInfo) {
mClassInfo->GetClassDescription(&mName);
}
if (mName) {
mMustFreeName = true;
} else {
mName = const_cast<char *>("UnnamedClass");
}
}
return mName;
}
private:
nsIClassInfo *mClassInfo; // WEAK
uint32_t mFlags;
char *mName;
bool mDidGetFlags;
bool mMustFreeName;
};
JSContext *
nsScriptSecurityManager::GetCurrentJSContext()
{
// Get JSContext from stack.
return nsXPConnect::XPConnect()->GetCurrentJSContext();
}
JSContext *
nsScriptSecurityManager::GetSafeJSContext()
{
// Get JSContext from stack.
return nsXPConnect::XPConnect()->GetSafeJSContext();
}
/* static */
bool
nsScriptSecurityManager::SecurityCompareURIs(nsIURI* aSourceURI,
nsIURI* aTargetURI)
{
return NS_SecurityCompareURIs(aSourceURI, aTargetURI, sStrictFileOriginPolicy);
}
// SecurityHashURI is consistent with SecurityCompareURIs because NS_SecurityHashURI
// is consistent with NS_SecurityCompareURIs. See nsNetUtil.h.
uint32_t
nsScriptSecurityManager::SecurityHashURI(nsIURI* aURI)
{
return NS_SecurityHashURI(aURI);
}
NS_IMETHODIMP
nsScriptSecurityManager::GetChannelPrincipal(nsIChannel* aChannel,
nsIPrincipal** aPrincipal)
{
NS_PRECONDITION(aChannel, "Must have channel!");
nsCOMPtr<nsISupports> owner;
aChannel->GetOwner(getter_AddRefs(owner));
if (owner) {
CallQueryInterface(owner, aPrincipal);
if (*aPrincipal) {
return NS_OK;
}
}
// OK, get the principal from the URI. Make sure this does the same thing
// as nsDocument::Reset and XULDocument::StartDocumentLoad.
nsCOMPtr<nsIURI> uri;
nsresult rv = NS_GetFinalChannelURI(aChannel, getter_AddRefs(uri));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIDocShell> docShell;
NS_QueryNotificationCallbacks(aChannel, docShell);
if (docShell) {
return GetDocShellCodebasePrincipal(uri, docShell, aPrincipal);
}
return GetCodebasePrincipalInternal(uri, UNKNOWN_APP_ID,
/* isInBrowserElement */ false, aPrincipal);
}
NS_IMETHODIMP
nsScriptSecurityManager::IsSystemPrincipal(nsIPrincipal* aPrincipal,
bool* aIsSystem)
{
*aIsSystem = (aPrincipal == mSystemPrincipal);
return NS_OK;
}
NS_IMETHODIMP_(nsIPrincipal *)
nsScriptSecurityManager::GetCxSubjectPrincipal(JSContext *cx)
{
NS_ASSERTION(cx == GetCurrentJSContext(),
"Uh, cx is not the current JS context!");
nsresult rv = NS_ERROR_FAILURE;
nsIPrincipal *principal = GetSubjectPrincipal(cx, &rv);
if (NS_FAILED(rv))
return nullptr;
return principal;
}
////////////////////
// Policy Storage //
////////////////////
// Table of security levels
static bool
DeleteCapability(nsHashKey *aKey, void *aData, void* closure)
{
NS_Free(aData);
return true;
}
//-- Per-Domain Policy - applies to one or more protocols or hosts
struct DomainEntry
{
DomainEntry(const char* aOrigin,
DomainPolicy* aDomainPolicy) : mOrigin(aOrigin),
mDomainPolicy(aDomainPolicy),
mNext(nullptr)
{
mDomainPolicy->Hold();
}
~DomainEntry()
{
mDomainPolicy->Drop();
}
bool Matches(const char *anOrigin)
{
int len = strlen(anOrigin);
int thisLen = mOrigin.Length();
if (len < thisLen)
return false;
if (mOrigin.RFindChar(':', thisLen-1, 1) != -1)
//-- Policy applies to all URLs of this scheme, compare scheme only
return mOrigin.EqualsIgnoreCase(anOrigin, thisLen);
//-- Policy applies to a particular host; compare domains
if (!mOrigin.Equals(anOrigin + (len - thisLen)))
return false;
if (len == thisLen)
return true;
char charBefore = anOrigin[len-thisLen-1];
return (charBefore == '.' || charBefore == ':' || charBefore == '/');
}
nsCString mOrigin;
DomainPolicy* mDomainPolicy;
DomainEntry* mNext;
};
static bool
DeleteDomainEntry(nsHashKey *aKey, void *aData, void* closure)
{
DomainEntry *entry = (DomainEntry*) aData;
do
{
DomainEntry *next = entry->mNext;
delete entry;
entry = next;
} while (entry);
return true;
}
/////////////////////////////
// nsScriptSecurityManager //
/////////////////////////////
////////////////////////////////////
// Methods implementing ISupports //
////////////////////////////////////
NS_IMPL_ISUPPORTS4(nsScriptSecurityManager,
nsIScriptSecurityManager,
nsIXPCSecurityManager,
nsIChannelEventSink,
nsIObserver)
///////////////////////////////////////////////////
// Methods implementing nsIScriptSecurityManager //
///////////////////////////////////////////////////
///////////////// Security Checks /////////////////
bool
nsScriptSecurityManager::ContentSecurityPolicyPermitsJSAction(JSContext *cx)
{
// Get the security manager
nsScriptSecurityManager *ssm =
nsScriptSecurityManager::GetScriptSecurityManager();
NS_ASSERTION(ssm, "Failed to get security manager service");
if (!ssm)
return false;
nsresult rv;
nsIPrincipal* subjectPrincipal = ssm->GetSubjectPrincipal(cx, &rv);
NS_ASSERTION(NS_SUCCEEDED(rv), "CSP: Failed to get nsIPrincipal from js context");
if (NS_FAILED(rv))
return false; // Not just absence of principal, but failure.
if (!subjectPrincipal)
return true;
nsCOMPtr<nsIContentSecurityPolicy> csp;
rv = subjectPrincipal->GetCsp(getter_AddRefs(csp));
NS_ASSERTION(NS_SUCCEEDED(rv), "CSP: Failed to get CSP from principal.");
// don't do anything unless there's a CSP
if (!csp)
return true;
bool evalOK = true;
bool reportViolation = false;
rv = csp->GetAllowsEval(&reportViolation, &evalOK);
if (NS_FAILED(rv))
{
NS_WARNING("CSP: failed to get allowsEval");
return true; // fail open to not break sites.
}
if (reportViolation) {
nsAutoString fileName;
unsigned lineNum = 0;
NS_NAMED_LITERAL_STRING(scriptSample, "call to eval() or related function blocked by CSP");
JS::RootedScript script(cx);
if (JS_DescribeScriptedCaller(cx, &script, &lineNum)) {
if (const char *file = JS_GetScriptFilename(cx, script)) {
CopyUTF8toUTF16(nsDependentCString(file), fileName);
}
}
csp->LogViolationDetails(nsIContentSecurityPolicy::VIOLATION_TYPE_EVAL,
fileName,
scriptSample,
lineNum,
EmptyString());
}
return evalOK;
}
bool
nsScriptSecurityManager::CheckObjectAccess(JSContext *cx, JS::Handle<JSObject*> obj,
JS::Handle<jsid> id, JSAccessMode mode,
JS::MutableHandle<JS::Value> vp)
{
// Get the security manager
nsScriptSecurityManager *ssm =
nsScriptSecurityManager::GetScriptSecurityManager();
NS_WARN_IF_FALSE(ssm, "Failed to get security manager service");
if (!ssm)
return false;
// Get the object being accessed. We protect these cases:
// 1. The Function.prototype.caller property's value, which might lead
// an attacker up a call-stack to a function or another object from
// a different trust domain.
// 2. A user-defined getter or setter function accessible on another
// trust domain's window or document object.
// vp can be a primitive, in that case, we use obj as the target
// object.
JSObject* target = JSVAL_IS_PRIMITIVE(vp) ? obj : JSVAL_TO_OBJECT(vp);
// Do the same-origin check -- this sets a JS exception if the check fails.
// Pass the parent object's class name, as we have no class-info for it.
nsresult rv =
ssm->CheckPropertyAccess(cx, target, js::GetObjectClass(obj)->name, id,
(mode & JSACC_WRITE) ?
(int32_t)nsIXPCSecurityManager::ACCESS_SET_PROPERTY :
(int32_t)nsIXPCSecurityManager::ACCESS_GET_PROPERTY);
if (NS_FAILED(rv))
return false; // Security check failed (XXX was an error reported?)
return true;
}
NS_IMETHODIMP
nsScriptSecurityManager::CheckPropertyAccess(JSContext* cx,
JSObject* aJSObject,
const char* aClassName,
jsid aProperty,
uint32_t aAction)
{
return CheckPropertyAccessImpl(aAction, nullptr, cx, aJSObject,
nullptr, nullptr,
aClassName, aProperty, nullptr);
}
NS_IMETHODIMP
nsScriptSecurityManager::CheckSameOrigin(JSContext* cx,
nsIURI* aTargetURI)
{
nsresult rv;
// Get a context if necessary
if (!cx)
{
cx = GetCurrentJSContext();
if (!cx)
return NS_OK; // No JS context, so allow access
}
// Get a principal from the context
nsIPrincipal* sourcePrincipal = GetSubjectPrincipal(cx, &rv);
if (NS_FAILED(rv))
return rv;
if (!sourcePrincipal)
{
NS_WARNING("CheckSameOrigin called on script w/o principals; should this happen?");
return NS_OK;
}
if (sourcePrincipal == mSystemPrincipal)
{
// This is a system (chrome) script, so allow access
return NS_OK;
}
// Get the original URI from the source principal.
// This has the effect of ignoring any change to document.domain
// which must be done to avoid DNS spoofing (bug 154930)
nsCOMPtr<nsIURI> sourceURI;
sourcePrincipal->GetDomain(getter_AddRefs(sourceURI));
if (!sourceURI) {
sourcePrincipal->GetURI(getter_AddRefs(sourceURI));
NS_ENSURE_TRUE(sourceURI, NS_ERROR_FAILURE);
}
// Compare origins
if (!SecurityCompareURIs(sourceURI, aTargetURI))
{
ReportError(cx, NS_LITERAL_STRING("CheckSameOriginError"), sourceURI, aTargetURI);
return NS_ERROR_DOM_BAD_URI;
}
return NS_OK;
}
NS_IMETHODIMP
nsScriptSecurityManager::CheckSameOriginURI(nsIURI* aSourceURI,
nsIURI* aTargetURI,
bool reportError)
{
if (!SecurityCompareURIs(aSourceURI, aTargetURI))
{
if (reportError) {
ReportError(nullptr, NS_LITERAL_STRING("CheckSameOriginError"),
aSourceURI, aTargetURI);
}
return NS_ERROR_DOM_BAD_URI;
}
return NS_OK;
}
nsresult
nsScriptSecurityManager::CheckPropertyAccessImpl(uint32_t aAction,
nsAXPCNativeCallContext* aCallContext,
JSContext* cx, JSObject* aJSObject,
nsISupports* aObj,
nsIClassInfo* aClassInfo,
const char* aClassName, jsid aProperty,
void** aCachedClassPolicy)
{
nsresult rv;
JS::RootedObject jsObject(cx, aJSObject);
JS::RootedId property(cx, aProperty);
nsIPrincipal* subjectPrincipal = GetSubjectPrincipal(cx, &rv);
if (NS_FAILED(rv))
return rv;
if (!subjectPrincipal || subjectPrincipal == mSystemPrincipal)
// We have native code or the system principal: just allow access
return NS_OK;
nsCOMPtr<nsIPrincipal> objectPrincipal;
// Hold the class info data here so we don't have to go back to virtual
// methods all the time
ClassInfoData classInfoData(aClassInfo, aClassName);
//-- Look up the security policy for this class and subject domain
SecurityLevel securityLevel;
rv = LookupPolicy(subjectPrincipal, classInfoData, property, aAction,
(ClassPolicy**)aCachedClassPolicy, &securityLevel);
if (NS_FAILED(rv))
return rv;
if (securityLevel.level == SCRIPT_SECURITY_UNDEFINED_ACCESS)
{
// No policy found for this property so use the default of last resort.
// If we were called from somewhere other than XPConnect
// (no XPC call context), assume this is a DOM class. Otherwise,
// ask the ClassInfo.
if (!aCallContext || classInfoData.IsDOMClass())
securityLevel.level = SCRIPT_SECURITY_SAME_ORIGIN_ACCESS;
else
securityLevel.level = SCRIPT_SECURITY_NO_ACCESS;
}
if (SECURITY_ACCESS_LEVEL_FLAG(securityLevel))
// This flag means securityLevel is allAccess, noAccess, or sameOrigin
{
switch (securityLevel.level)
{
case SCRIPT_SECURITY_NO_ACCESS:
rv = NS_ERROR_DOM_PROP_ACCESS_DENIED;
break;
case SCRIPT_SECURITY_ALL_ACCESS:
rv = NS_OK;
break;
case SCRIPT_SECURITY_SAME_ORIGIN_ACCESS:
{
nsCOMPtr<nsIPrincipal> principalHolder;
if (jsObject)
{
objectPrincipal = doGetObjectPrincipal(jsObject);
if (!objectPrincipal)
rv = NS_ERROR_DOM_SECURITY_ERR;
}
else
{
NS_ERROR("CheckPropertyAccessImpl called without a target object or URL");
return NS_ERROR_FAILURE;
}
if(NS_SUCCEEDED(rv))
rv = CheckSameOriginDOMProp(subjectPrincipal, objectPrincipal,
aAction);
break;
}
default:
NS_ERROR("Bad Security Level Value");
return NS_ERROR_FAILURE;
}
}
else // if SECURITY_ACCESS_LEVEL_FLAG is false, securityLevel is a capability
{
rv = SubjectIsPrivileged() ? NS_OK : NS_ERROR_DOM_SECURITY_ERR;
}
if (NS_SUCCEEDED(rv))
{
return rv;
}
//--See if the object advertises a non-default level of access
// using nsISecurityCheckedComponent
nsCOMPtr<nsISecurityCheckedComponent> checkedComponent =
do_QueryInterface(aObj);
nsXPIDLCString objectSecurityLevel;
if (checkedComponent)
{
nsCOMPtr<nsIXPConnectWrappedNative> wrapper;
nsCOMPtr<nsIInterfaceInfo> interfaceInfo;
const nsIID* objIID = nullptr;
rv = aCallContext->GetCalleeWrapper(getter_AddRefs(wrapper));
if (NS_SUCCEEDED(rv) && wrapper)
rv = wrapper->FindInterfaceWithMember(property, getter_AddRefs(interfaceInfo));
if (NS_SUCCEEDED(rv) && interfaceInfo)
rv = interfaceInfo->GetIIDShared(&objIID);
if (NS_SUCCEEDED(rv) && objIID)
{
switch (aAction)
{
case nsIXPCSecurityManager::ACCESS_GET_PROPERTY:
checkedComponent->CanGetProperty(objIID,
IDToString(cx, property),
getter_Copies(objectSecurityLevel));
break;
case nsIXPCSecurityManager::ACCESS_SET_PROPERTY:
checkedComponent->CanSetProperty(objIID,
IDToString(cx, property),
getter_Copies(objectSecurityLevel));
break;
case nsIXPCSecurityManager::ACCESS_CALL_METHOD:
checkedComponent->CanCallMethod(objIID,
IDToString(cx, property),
getter_Copies(objectSecurityLevel));
}
}
}
rv = CheckXPCPermissions(cx, aObj, jsObject, subjectPrincipal,
objectSecurityLevel);
if (NS_FAILED(rv)) //-- Security tests failed, access is denied, report error
{
nsAutoString stringName;
switch(aAction)
{
case nsIXPCSecurityManager::ACCESS_GET_PROPERTY:
stringName.AssignLiteral("GetPropertyDeniedOrigins");
break;
case nsIXPCSecurityManager::ACCESS_SET_PROPERTY:
stringName.AssignLiteral("SetPropertyDeniedOrigins");
break;
case nsIXPCSecurityManager::ACCESS_CALL_METHOD:
stringName.AssignLiteral("CallMethodDeniedOrigins");
}
// Null out objectPrincipal for now, so we don't leak information about
// it. Whenever we can report different error strings to content and
// the UI we can take this out again.
objectPrincipal = nullptr;
NS_ConvertUTF8toUTF16 className(classInfoData.GetName());
nsAutoCString subjectOrigin;
nsAutoCString subjectDomain;
if (!nsAutoInPrincipalDomainOriginSetter::sInPrincipalDomainOrigin) {
nsCOMPtr<nsIURI> uri, domain;
subjectPrincipal->GetURI(getter_AddRefs(uri));
if (uri) { // Object principal might be expanded
GetOriginFromURI(uri, subjectOrigin);
}
subjectPrincipal->GetDomain(getter_AddRefs(domain));
if (domain) {
GetOriginFromURI(domain, subjectDomain);
}
} else {
subjectOrigin.AssignLiteral("the security manager");
}
NS_ConvertUTF8toUTF16 subjectOriginUnicode(subjectOrigin);
NS_ConvertUTF8toUTF16 subjectDomainUnicode(subjectDomain);
nsAutoCString objectOrigin;
nsAutoCString objectDomain;
if (!nsAutoInPrincipalDomainOriginSetter::sInPrincipalDomainOrigin &&
objectPrincipal) {
nsCOMPtr<nsIURI> uri, domain;
objectPrincipal->GetURI(getter_AddRefs(uri));
if (uri) { // Object principal might be system
GetOriginFromURI(uri, objectOrigin);
}
objectPrincipal->GetDomain(getter_AddRefs(domain));
if (domain) {
GetOriginFromURI(domain, objectDomain);
}
}
NS_ConvertUTF8toUTF16 objectOriginUnicode(objectOrigin);
NS_ConvertUTF8toUTF16 objectDomainUnicode(objectDomain);
nsXPIDLString errorMsg;
const PRUnichar *formatStrings[] =
{
subjectOriginUnicode.get(),
className.get(),
IDToString(cx, property),
objectOriginUnicode.get(),
subjectDomainUnicode.get(),
objectDomainUnicode.get()
};
uint32_t length = ArrayLength(formatStrings);
// XXXbz Our localization system is stupid and can't handle not showing
// some strings that get passed in. Which means that we have to get
// our length precisely right: it has to be exactly the number of
// strings our format string wants. This means we'll have to move
// strings in the array as needed, sadly...
if (nsAutoInPrincipalDomainOriginSetter::sInPrincipalDomainOrigin ||
!objectPrincipal) {
stringName.AppendLiteral("OnlySubject");
length -= 3;
} else {
// default to a length that doesn't include the domains, then
// increase it as needed.
length -= 2;
if (!subjectDomainUnicode.IsEmpty()) {
stringName.AppendLiteral("SubjectDomain");
length += 1;
}
if (!objectDomainUnicode.IsEmpty()) {
stringName.AppendLiteral("ObjectDomain");
length += 1;
if (length != ArrayLength(formatStrings)) {
// We have an object domain but not a subject domain.
// Scoot our string over one slot. See the XXX comment
// above for why we need to do this.
formatStrings[length-1] = formatStrings[length];
}
}
}
// We need to keep our existing failure rv and not override it
// with a likely success code from the following string bundle
// call in order to throw the correct security exception later.
nsresult rv2 = sStrBundle->FormatStringFromName(stringName.get(),
formatStrings,
length,
getter_Copies(errorMsg));
if (NS_FAILED(rv2)) {
// Might just be missing the string... Do our best
errorMsg = stringName;
}
SetPendingException(cx, errorMsg.get());
}
return rv;
}
/* static */
nsresult
nsScriptSecurityManager::CheckSameOriginPrincipal(nsIPrincipal* aSubject,
nsIPrincipal* aObject)
{
/*
** Get origin of subject and object and compare.
*/
if (aSubject == aObject)
return NS_OK;
if (!AppAttributesEqual(aSubject, aObject)) {
return NS_ERROR_DOM_PROP_ACCESS_DENIED;
}
// Default to false, and change if that turns out wrong.
bool subjectSetDomain = false;
bool objectSetDomain = false;
nsCOMPtr<nsIURI> subjectURI;
nsCOMPtr<nsIURI> objectURI;
aSubject->GetDomain(getter_AddRefs(subjectURI));
if (!subjectURI) {
aSubject->GetURI(getter_AddRefs(subjectURI));
} else {
subjectSetDomain = true;
}
aObject->GetDomain(getter_AddRefs(objectURI));
if (!objectURI) {
aObject->GetURI(getter_AddRefs(objectURI));
} else {
objectSetDomain = true;
}
if (SecurityCompareURIs(subjectURI, objectURI))
{ // If either the subject or the object has changed its principal by
// explicitly setting document.domain then the other must also have
// done so in order to be considered the same origin. This prevents
// DNS spoofing based on document.domain (154930)
// If both or neither explicitly set their domain, allow the access
if (subjectSetDomain == objectSetDomain)
return NS_OK;
}
/*
** Access tests failed, so now report error.
*/
return NS_ERROR_DOM_PROP_ACCESS_DENIED;
}
// It's important that
//
// CheckSameOriginPrincipal(A, B) == NS_OK
//
// imply
//
// HashPrincipalByOrigin(A) == HashPrincipalByOrigin(B)
//
// if principals A and B could ever be used as keys in a hashtable.
// Violation of this invariant leads to spurious failures of hashtable
// lookups. See bug 454850.
/*static*/ uint32_t
nsScriptSecurityManager::HashPrincipalByOrigin(nsIPrincipal* aPrincipal)
{
nsCOMPtr<nsIURI> uri;
aPrincipal->GetDomain(getter_AddRefs(uri));
if (!uri)
aPrincipal->GetURI(getter_AddRefs(uri));
return SecurityHashURI(uri);
}
/* static */ bool
nsScriptSecurityManager::AppAttributesEqual(nsIPrincipal* aFirst,
nsIPrincipal* aSecond)
{
MOZ_ASSERT(aFirst && aSecond, "Don't pass null pointers!");
uint32_t firstAppId = nsIScriptSecurityManager::UNKNOWN_APP_ID;
if (!aFirst->GetUnknownAppId()) {
firstAppId = aFirst->GetAppId();
}
uint32_t secondAppId = nsIScriptSecurityManager::UNKNOWN_APP_ID;
if (!aSecond->GetUnknownAppId()) {
secondAppId = aSecond->GetAppId();
}
return ((firstAppId == secondAppId) &&
(aFirst->GetIsInBrowserElement() == aSecond->GetIsInBrowserElement()));
}
nsresult
nsScriptSecurityManager::CheckSameOriginDOMProp(nsIPrincipal* aSubject,
nsIPrincipal* aObject,
uint32_t aAction)
{
nsresult rv;
bool subsumes;
rv = aSubject->Subsumes(aObject, &subsumes);
if (NS_SUCCEEDED(rv) && !subsumes) {
rv = NS_ERROR_DOM_PROP_ACCESS_DENIED;
}
if (NS_SUCCEEDED(rv))
return NS_OK;
/*
* Content can't ever touch chrome (we check for UniversalXPConnect later)
*/
if (aObject == mSystemPrincipal)
return NS_ERROR_DOM_PROP_ACCESS_DENIED;
/*
** Access tests failed, so now report error.
*/
return NS_ERROR_DOM_PROP_ACCESS_DENIED;
}
nsresult
nsScriptSecurityManager::LookupPolicy(nsIPrincipal* aPrincipal,
ClassInfoData& aClassData,
JS::Handle<jsid> aProperty,
uint32_t aAction,
ClassPolicy** aCachedClassPolicy,
SecurityLevel* result)
{
AutoJSContext cx;
nsresult rv;
JS::RootedId property(cx, aProperty);
result->level = SCRIPT_SECURITY_UNDEFINED_ACCESS;
DomainPolicy* dpolicy = nullptr;
//-- Initialize policies if necessary
if (mPolicyPrefsChanged)
{
if (!mPrefInitialized) {
rv = InitPrefs();
NS_ENSURE_SUCCESS(rv, rv);