Back to index

lightning-sunbird  0.9+nobinonly
Public Member Functions | Static Public Member Functions | Public Attributes | Private Member Functions | Static Private Member Functions | Private Attributes | Static Private Attributes
nsScriptSecurityManager Class Reference

#include <nsScriptSecurityManager.h>

Inheritance diagram for nsScriptSecurityManager:
Inheritance graph
[legend]
Collaboration diagram for nsScriptSecurityManager:
Collaboration graph
[legend]

List of all members.

Public Member Functions

JSContextGetCurrentJSContext ()
JSContextGetSafeJSContext ()
void checkPropertyAccess (in JSContextPtr aJSContext, in JSObjectPtr aJSObject, in string aClassName, in JSVal aProperty, in PRUint32 aAction)
 Checks whether the running script is allowed to access aProperty.
void checkConnect (in JSContextPtr aJSContext, in nsIURI aTargetURI, in string aClassName, in string aProperty)
 Checks whether the running script is allowed to connect to aTargetURI.
void checkLoadURIFromScript (in JSContextPtr cx, in nsIURI uri)
 Check that the script currently running in context "cx" can load "uri".
void checkLoadURIWithPrincipal (in nsIPrincipal aPrincipal, in nsIURI uri, in unsigned long flags)
 Check that content with principal aPrincipal can load "uri".
void checkLoadURI (in nsIURI from, in nsIURI uri, in unsigned long flags)
 Check that content from "from" can load "uri".
void checkLoadURIStr (in AUTF8String from, in AUTF8String uri, in unsigned long flags)
 Same as CheckLoadURI but takes string arguments for ease of use by scripts.
void checkFunctionAccess (in JSContextPtr cx, in voidPtr funObj, in voidPtr targetObj)
 Check that the function 'funObj' is allowed to run on 'targetObj'.
boolean canExecuteScripts (in JSContextPtr cx, in nsIPrincipal principal)
 Return true if content from the given principal is allowed to execute scripts.
nsIPrincipal getSubjectPrincipal ()
 Return the principal of the innermost frame of the currently executing script.
nsIPrincipal getSystemPrincipal ()
 Return the all-powerful system principal.
nsIPrincipal getCertificatePrincipal (in AUTF8String aCertFingerprint, in AUTF8String aSubjectName, in AUTF8String aPrettyName, in nsISupports aCert, in nsIURI aURI)
 Return a principal with the specified certificate fingerprint, subject name (the full name or concatenated set of names of the entity represented by the certificate), pretty name, certificate, and codebase URI.
nsIPrincipal getCodebasePrincipal (in nsIURI aURI)
 Return a principal that has the same origin as aURI.
short requestCapability (in nsIPrincipal principal, in string capability)
 Request that 'capability' can be enabled by scripts or applets running with 'principal'.
boolean isCapabilityEnabled (in string capability)
 Return true if the currently executing script has 'capability' enabled.
void enableCapability (in string capability)
 Enable 'capability' in the innermost frame of the currently executing script.
void revertCapability (in string capability)
 Remove 'capability' from the innermost frame of the currently executing script.
void disableCapability (in string capability)
 Disable 'capability' in the innermost frame of the currently executing script.
void setCanEnableCapability (in AUTF8String certificateFingerprint, in string capability, in short canEnable)
 Allow 'certificateID' to enable 'capability.
nsIPrincipal getObjectPrincipal (in JSContextPtr cx, in JSObjectPtr obj)
 Return the principal of the specified object in the specified context.
boolean subjectPrincipalIsSystem ()
 Returns true if the principal of the currently running script is the system principal, false otherwise.
void checkSameOrigin (in JSContextPtr aJSContext, in nsIURI aTargetURI)
 Returns OK if aJSContext and target have the same "origin" (scheme, host, and port).
void checkSameOriginURI (in nsIURI aSourceURI, in nsIURI aTargetURI)
 Returns OK if aSourceURI and target have the same "origin" (scheme, host, and port).
void checkSameOriginPrincipal (in nsIPrincipal aSourcePrincipal, in nsIPrincipal aTargetPrincipal)
 Returns OK if aSourcePrincipal and aTargetPrincipal have the same "origin" (scheme, host, and port).
nsIPrincipal getPrincipalFromContext (in JSContextPtr cx)
 Returns the principal of the global object of the given context, or null if no global or no principal.
boolean securityCompareURIs (in nsIURI aSubjectURI, in nsIURI aObjectURI)
 Utility method for comparing two URIs.
void CanCreateWrapper (in JSContextPtr aJSContext, in nsIIDRef aIID, in nsISupports aObj, in nsIClassInfo aClassInfo, inout voidPtr aPolicy)
 For each of these hooks returning NS_OK means 'let the action continue'.
void CanCreateInstance (in JSContextPtr aJSContext, in nsCIDRef aCID)
void CanGetService (in JSContextPtr aJSContext, in nsCIDRef aCID)
void CanAccess (in PRUint32 aAction, in nsIXPCNativeCallContext aCallContext, in JSContextPtr aJSContext, in JSObjectPtr aJSObject, in nsISupports aObj, in nsIClassInfo aClassInfo, in JSVal aName, inout voidPtr aPolicy)
boolean canAccessSecurityPreferences ()
 Checks whether the currently executing script (if any) can access security preferences.
void observe (in nsISupports aSubject, in string aTopic, in wstring aData)
 Observe will be called when there is a notification for the topic |aTopic|.

Static Public Member Functions

static void Shutdown ()
NS_DECL_ISUPPORTS
NS_DECL_NSISCRIPTSECURITYMANAGER
NS_DECL_NSIXPCSECURITYMANAGER
NS_DECL_NSIPREFSECURITYCHECK
static NS_DECL_NSIOBSERVER
nsScriptSecurityManager
GetScriptSecurityManager ()
static nsSystemPrincipalSystemPrincipalSingletonConstructor ()
static PRBool SecurityCompareURIs (nsIURI *aSourceURI, nsIURI *aTargetURI)
 Utility method for comparing two URIs.
static nsresult CheckSameOriginPrincipal (nsIPrincipal *aSubject, nsIPrincipal *aObject, PRBool aIsCheckConnect)

Public Attributes

const unsigned long STANDARD = 0
 Default CheckLoadURI permissions.
const unsigned long DISALLOW_FROM_MAIL = 1 << 0
const unsigned long ALLOW_CHROME = 1 << 1
const unsigned long DISALLOW_SCRIPT_OR_DATA = 1 << 2
const unsigned long DISALLOW_SCRIPT = 1 << 3
const PRUint32 HOOK_CREATE_WRAPPER = 1 << 0
 These flags are used when calling nsIXPConnect::SetSecurityManager.
const PRUint32 HOOK_CREATE_INSTANCE = 1 << 1
const PRUint32 HOOK_GET_SERVICE = 1 << 2
const PRUint32 HOOK_CALL_METHOD = 1 << 3
const PRUint32 HOOK_GET_PROPERTY = 1 << 4
const PRUint32 HOOK_SET_PROPERTY = 1 << 5
const PRUint32 HOOK_ALL
const PRUint32 ACCESS_CALL_METHOD = 0
const PRUint32 ACCESS_GET_PROPERTY = 1
const PRUint32 ACCESS_SET_PROPERTY = 2

Private Member Functions

 nsScriptSecurityManager ()
virtual ~nsScriptSecurityManager ()
nsIPrincipaldoGetSubjectPrincipal (nsresult *rv)
nsresult GetRootDocShell (JSContext *cx, nsIDocShell **result)
nsresult CheckPropertyAccessImpl (PRUint32 aAction, nsIXPCNativeCallContext *aCallContext, JSContext *cx, JSObject *aJSObject, nsISupports *aObj, nsIURI *aTargetURI, nsIClassInfo *aClassInfo, const char *aClassName, jsval aProperty, void **aCachedClassPolicy)
nsresult CheckSameOriginDOMProp (nsIPrincipal *aSubject, nsIPrincipal *aObject, PRUint32 aAction, PRBool aIsCheckConnect)
nsresult LookupPolicy (nsIPrincipal *principal, const char *aClassName, jsval aProperty, PRUint32 aAction, ClassPolicy **aCachedClassPolicy, SecurityLevel *result)
nsresult CreateCodebasePrincipal (nsIURI *aURI, nsIPrincipal **result)
nsresult DoGetCertificatePrincipal (const nsACString &aCertFingerprint, const nsACString &aSubjectName, const nsACString &aPrettyName, nsISupports *aCertificate, nsIURI *aURI, PRBool aModifyTable, nsIPrincipal **result)
nsresult SavePrincipal (nsIPrincipal *aToSave)
nsresult CheckXPCPermissions (nsISupports *aObj, const char *aObjectSecurityLevel)
nsresult Init ()
nsresult InitPrefs ()
nsresult InitPolicies ()
nsresult InitDomainPolicy (JSContext *cx, const char *aPolicyName, DomainPolicy *aDomainPolicy)
nsresult InitPrincipals (PRUint32 prefCount, const char **prefNames, nsISecurityPref *securityPref)
void JSEnabledPrefChanged (nsISecurityPref *aSecurityPref)

Static Private Member Functions

static JSBool JS_DLL_CALLBACK CheckObjectAccess (JSContext *cx, JSObject *obj, jsval id, JSAccessMode mode, jsval *vp)
static nsIPrincipaldoGetObjectPrincipal (JSContext *cx, JSObject *obj)
static nsresult GetBaseURIScheme (nsIURI *aURI, nsCString &aScheme)
static nsresult ReportError (JSContext *cx, const nsAString &messageTag, nsIURI *aSource, nsIURI *aTarget)
static nsIPrincipalGetSubjectPrincipal (JSContext *cx, nsresult *rv)
static nsIPrincipalGetFramePrincipal (JSContext *cx, JSStackFrame *fp, nsresult *rv)
static nsIPrincipalGetScriptPrincipal (JSContext *cx, JSScript *script, nsresult *rv)
static nsIPrincipalGetFunctionObjectPrincipal (JSContext *cx, JSObject *obj, JSStackFrame *fp, nsresult *rv)
static nsIPrincipalGetPrincipalAndFrame (JSContext *cx, JSStackFrame **frameResult, nsresult *rv)
static PRBool CheckConfirmDialog (JSContext *cx, nsIPrincipal *aPrincipal, const char *aCapability, PRBool *checkValue)
static void FormatCapabilityString (nsAString &aCapability)
static nsresult GetPrincipalPrefNames (const char *prefBase, nsCString &grantedPref, nsCString &deniedPref, nsCString &subjectNamePref)

Private Attributes

nsObjectHashtable * mOriginToPolicyMap
DomainPolicymDefaultPolicy
nsObjectHashtable * mCapabilities
nsCOMPtr< nsIPrefBranchmPrefBranch
nsCOMPtr< nsISecurityPrefmSecurityPref
nsCOMPtr< nsIPrincipalmSystemPrincipal
nsCOMPtr< nsIPrincipalmSystemCertificate
nsInterfaceHashtable
< PrincipalKey, nsIPrincipal
mPrincipals
nsCOMPtr< nsIThreadJSContextStackmJSContextStack
PRPackedBool mIsJavaScriptEnabled
PRPackedBool mIsMailJavaScriptEnabled
PRPackedBool mIsWritingPrefs
PRPackedBool mPolicyPrefsChanged

Static Private Attributes

static jsval sEnabledID = JSVAL_VOID
static const char sJSEnabledPrefName [] = "javascript.enabled"
static const char sJSMailEnabledPrefName [] = "javascript.allow.mailnews"
static nsIIOServicesIOService = nsnull
static nsIXPConnectsXPConnect = nsnull
static nsIStringBundlesStrBundle = nsnull
static JSRuntimesRuntime = 0

Detailed Description

Definition at line 376 of file nsScriptSecurityManager.h.


Constructor & Destructor Documentation

Definition at line 3082 of file nsScriptSecurityManager.cpp.

    : mOriginToPolicyMap(nsnull),
      mDefaultPolicy(nsnull),
      mCapabilities(nsnull),
      mIsJavaScriptEnabled(PR_FALSE),
      mIsMailJavaScriptEnabled(PR_FALSE),
      mIsWritingPrefs(PR_FALSE),
      mPolicyPrefsChanged(PR_TRUE)
#ifdef XPC_IDISPATCH_SUPPORT
      ,mXPCDefaultGrantAll(PR_FALSE)
#endif
{
    NS_ASSERTION(sizeof(long) == sizeof(void*), "long and void* have different lengths on this platform. This may cause a security failure.");
    mPrincipals.Init(31);
}

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 3147 of file nsScriptSecurityManager.cpp.

Here is the call graph for this function:


Member Function Documentation

void nsIXPCSecurityManager::CanAccess ( in PRUint32  aAction,
in nsIXPCNativeCallContext  aCallContext,
in JSContextPtr  aJSContext,
in JSObjectPtr  aJSObject,
in nsISupports  aObj,
in nsIClassInfo  aClassInfo,
in JSVal  aName,
inout voidPtr  aPolicy 
) [inherited]

Here is the caller graph for this function:

Checks whether the currently executing script (if any) can access security preferences.

Corresponds to CapabilityPreferencesAccess.

Exceptions from this method should be treated like a return value of false.

void nsIXPCSecurityManager::CanCreateInstance ( in JSContextPtr  aJSContext,
in nsCIDRef  aCID 
) [inherited]

Here is the caller graph for this function:

void nsIXPCSecurityManager::CanCreateWrapper ( in JSContextPtr  aJSContext,
in nsIIDRef  aIID,
in nsISupports  aObj,
in nsIClassInfo  aClassInfo,
inout voidPtr  aPolicy 
) [inherited]

For each of these hooks returning NS_OK means 'let the action continue'.

Returning an error code means 'veto the action'. XPConnect will return JS_FALSE to the js engine if the action is vetoed. The implementor of this interface is responsible for setting a JS exception into the JSContext if that is appropriate.

Return true if content from the given principal is allowed to execute scripts.

void nsIXPCSecurityManager::CanGetService ( in JSContextPtr  aJSContext,
in nsCIDRef  aCID 
) [inherited]
PRBool nsScriptSecurityManager::CheckConfirmDialog ( JSContext cx,
nsIPrincipal aPrincipal,
const char *  aCapability,
PRBool checkValue 
) [static, private]

Definition at line 2459 of file nsScriptSecurityManager.cpp.

{
    nsresult rv;
    *checkValue = PR_FALSE;

    //-- Get a prompter for the current window.
    nsCOMPtr<nsIPrompt> prompter;
    if (cx)
    {
        nsIScriptContext *scriptContext = GetScriptContext(cx);
        if (scriptContext)
        {
            nsCOMPtr<nsIDOMWindowInternal> domWin =
                do_QueryInterface(scriptContext->GetGlobalObject());
            if (domWin)
                domWin->GetPrompter(getter_AddRefs(prompter));
        }
    }

    if (!prompter)
    {
        //-- Couldn't get prompter from the current window, so get the prompt service.
        nsCOMPtr<nsIWindowWatcher> wwatch(do_GetService(NS_WINDOWWATCHER_CONTRACTID));
        if (wwatch)
          wwatch->GetNewPrompter(0, getter_AddRefs(prompter));
        if (!prompter)
            return PR_FALSE;
    }

    //-- Localize the dialog text
    nsXPIDLString check;
    rv = sStrBundle->GetStringFromName(NS_LITERAL_STRING("CheckMessage").get(),
                                       getter_Copies(check));
    if (NS_FAILED(rv))
        return PR_FALSE;

    nsXPIDLString title;
    rv = sStrBundle->GetStringFromName(NS_LITERAL_STRING("Titleline").get(),
                                       getter_Copies(title));
    if (NS_FAILED(rv))
        return PR_FALSE;

    nsXPIDLString yesStr;
    rv = sStrBundle->GetStringFromName(NS_LITERAL_STRING("Yes").get(),
                                       getter_Copies(yesStr));
    if (NS_FAILED(rv))
        return PR_FALSE;

    nsXPIDLString noStr;
    rv = sStrBundle->GetStringFromName(NS_LITERAL_STRING("No").get(),
                                       getter_Copies(noStr));
    if (NS_FAILED(rv))
        return PR_FALSE;

    nsCAutoString val;
    PRBool hasCert;
    aPrincipal->GetHasCertificate(&hasCert);
    if (hasCert)
        rv = aPrincipal->GetPrettyName(val);
    else
        rv = GetPrincipalDomainOrigin(aPrincipal, val);

    if (NS_FAILED(rv))
        return PR_FALSE;

    NS_ConvertUTF8toUTF16 location(val);
    NS_ConvertASCIItoUTF16 capability(aCapability);
    FormatCapabilityString(capability);
    const PRUnichar *formatStrings[] = { location.get(), capability.get() };

    nsXPIDLString message;
    rv = sStrBundle->FormatStringFromName(NS_LITERAL_STRING("EnableCapabilityQuery").get(),
                                          formatStrings,
                                          NS_ARRAY_LENGTH(formatStrings),
                                          getter_Copies(message));
    if (NS_FAILED(rv))
        return PR_FALSE;

    PRInt32 buttonPressed = 1; // If the user exits by clicking the close box, assume No (button 1)
    rv = prompter->ConfirmEx(title.get(), message.get(),
                             (nsIPrompt::BUTTON_DELAY_ENABLE) +
                             (nsIPrompt::BUTTON_POS_1_DEFAULT) +
                             (nsIPrompt::BUTTON_TITLE_IS_STRING * nsIPrompt::BUTTON_POS_0) +
                             (nsIPrompt::BUTTON_TITLE_IS_STRING * nsIPrompt::BUTTON_POS_1),
                             yesStr.get(), noStr.get(), nsnull, check.get(), checkValue, &buttonPressed);

    if (NS_FAILED(rv))
        *checkValue = PR_FALSE;
    return (buttonPressed == 0);
}

Here is the call graph for this function:

void nsIScriptSecurityManager::checkConnect ( in JSContextPtr  aJSContext,
in nsIURI  aTargetURI,
in string  aClassName,
in string  aProperty 
) [inherited]

Checks whether the running script is allowed to connect to aTargetURI.

void nsIScriptSecurityManager::checkFunctionAccess ( in JSContextPtr  cx,
in voidPtr  funObj,
in voidPtr  targetObj 
) [inherited]

Check that the function 'funObj' is allowed to run on 'targetObj'.

Will return error code NS_ERROR_DOM_SECURITY_ERR if the function should not run

Parameters:
cxThe current active JavaScript context.
funObjThe function trying to run..
targetObjThe object the function will run on.
void nsIScriptSecurityManager::checkLoadURI ( in nsIURI  from,
in nsIURI  uri,
in unsigned long  flags 
) [inherited]

Check that content from "from" can load "uri".

Will return error code NS_ERROR_DOM_BAD_URI if the load request should be denied.

Parameters:
fromthe URI causing the load
urithe URI that is being loaded
flagsthe permission set, see above

Check that the script currently running in context "cx" can load "uri".

Will return error code NS_ERROR_DOM_BAD_URI if the load request should be denied.

Parameters:
cxthe JSContext of the script causing the load
urithe URI that is being loaded
void nsIScriptSecurityManager::checkLoadURIStr ( in AUTF8String  from,
in AUTF8String  uri,
in unsigned long  flags 
) [inherited]

Same as CheckLoadURI but takes string arguments for ease of use by scripts.

void nsIScriptSecurityManager::checkLoadURIWithPrincipal ( in nsIPrincipal  aPrincipal,
in nsIURI  uri,
in unsigned long  flags 
) [inherited]

Check that content with principal aPrincipal can load "uri".

Will return error code NS_ERROR_DOM_BAD_URI if the load request should be denied.

Parameters:
aPrincipalthe URI causing the load
urithe URI that is being loaded
flagsthe permission set, see above
static JSBool JS_DLL_CALLBACK nsScriptSecurityManager::CheckObjectAccess ( JSContext cx,
JSObject obj,
jsval  id,
JSAccessMode  mode,
jsval vp 
) [static, private]

Here is the caller graph for this function:

void nsIScriptSecurityManager::checkPropertyAccess ( in JSContextPtr  aJSContext,
in JSObjectPtr  aJSObject,
in string  aClassName,
in JSVal  aProperty,
in PRUint32  aAction 
) [inherited]

Checks whether the running script is allowed to access aProperty.

nsresult nsScriptSecurityManager::CheckPropertyAccessImpl ( PRUint32  aAction,
nsIXPCNativeCallContext aCallContext,
JSContext cx,
JSObject aJSObject,
nsISupports *  aObj,
nsIURI aTargetURI,
nsIClassInfo aClassInfo,
const char *  aClassName,
jsval  aProperty,
void **  aCachedClassPolicy 
) [private]

Definition at line 642 of file nsScriptSecurityManager.cpp.

{
    nsresult rv;
    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;

    // Hold the class info data here so we don't have to go back to virtual
    // methods all the time
    ClassInfoData classInfoData(aClassInfo, aClassName);
#ifdef DEBUG_CAPS_CheckPropertyAccessImpl
    nsCAutoString propertyName;
    propertyName.AssignWithConversion((PRUnichar*)JSValIDToString(cx, aProperty));
    printf("### CanAccess(%s.%s, %i) ", classInfoData.GetName(), 
           propertyName.get(), aAction);
#endif

    //-- Look up the security policy for this class and subject domain
    SecurityLevel securityLevel;
    rv = LookupPolicy(subjectPrincipal, classInfoData.GetName(), aProperty, 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:
#ifdef DEBUG_CAPS_CheckPropertyAccessImpl
            printf("noAccess ");
#endif
            rv = NS_ERROR_DOM_PROP_ACCESS_DENIED;
            break;

        case SCRIPT_SECURITY_ALL_ACCESS:
#ifdef DEBUG_CAPS_CheckPropertyAccessImpl
            printf("allAccess ");
#endif
            rv = NS_OK;
            break;

        case SCRIPT_SECURITY_SAME_ORIGIN_ACCESS:
            {
#ifdef DEBUG_CAPS_CheckPropertyAccessImpl
                printf("sameOrigin ");
#endif
                nsCOMPtr<nsIPrincipal> objectPrincipal;
                if(aJSObject)
                {
                    objectPrincipal = doGetObjectPrincipal(cx, aJSObject);
                    if (!objectPrincipal)
                        return NS_ERROR_FAILURE;
                }
                else if(aTargetURI)
                {
                    if (NS_FAILED(GetCodebasePrincipal(
                          aTargetURI, getter_AddRefs(objectPrincipal))))
                        return NS_ERROR_FAILURE;
                }
                else
                {
                    NS_ERROR("CheckPropertyAccessImpl called without a target object or URL");
                    return NS_ERROR_FAILURE;
                }
                rv = CheckSameOriginDOMProp(subjectPrincipal, objectPrincipal,
                                            aAction, aTargetURI != nsnull);
                break;
            }
        default:
#ifdef DEBUG_CAPS_CheckPropertyAccessImpl
                printf("ERROR ");
#endif
            NS_ERROR("Bad Security Level Value");
            return NS_ERROR_FAILURE;
        }
    }
    else // if SECURITY_ACCESS_LEVEL_FLAG is false, securityLevel is a capability
    {
#ifdef DEBUG_CAPS_CheckPropertyAccessImpl
        printf("Cap:%s ", securityLevel.capability);
#endif
        PRBool capabilityEnabled = PR_FALSE;
        rv = IsCapabilityEnabled(securityLevel.capability, &capabilityEnabled);
        if (NS_FAILED(rv) || !capabilityEnabled)
            rv = NS_ERROR_DOM_SECURITY_ERR;
        else
            rv = NS_OK;
    }

    if (NS_SUCCEEDED(rv) && classInfoData.IsContentNode())
    {
        // No access to anonymous content from the web!  (bug 164086)
        nsCOMPtr<nsIContent> content(do_QueryInterface(aObj));
        NS_ASSERTION(content, "classinfo had CONTENT_NODE set but node did not"
                              "implement nsIContent!  Fasten your seat belt.");
        if (content->IsNativeAnonymous()) {
            rv = NS_ERROR_DOM_SECURITY_ERR;
        }
    }

    if (NS_SUCCEEDED(rv))
    {
#ifdef DEBUG_CAPS_CheckPropertyAccessImpl
    printf(" GRANTED.\n");
#endif
        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;
        rv = aCallContext->GetCalleeWrapper(getter_AddRefs(wrapper));
        if (NS_SUCCEEDED(rv))
            rv = wrapper->FindInterfaceWithMember(aProperty, getter_AddRefs(interfaceInfo));
        if (NS_SUCCEEDED(rv))
            rv = interfaceInfo->GetIIDShared(&objIID);
        if (NS_SUCCEEDED(rv))
        {
            switch (aAction)
            {
            case nsIXPCSecurityManager::ACCESS_GET_PROPERTY:
                checkedComponent->CanGetProperty(objIID,
                                                 JSValIDToString(cx, aProperty),
                                                 getter_Copies(objectSecurityLevel));
                break;
            case nsIXPCSecurityManager::ACCESS_SET_PROPERTY:
                checkedComponent->CanSetProperty(objIID,
                                                 JSValIDToString(cx, aProperty),
                                                 getter_Copies(objectSecurityLevel));
                break;
            case nsIXPCSecurityManager::ACCESS_CALL_METHOD:
                checkedComponent->CanCallMethod(objIID,
                                                JSValIDToString(cx, aProperty),
                                                getter_Copies(objectSecurityLevel));
            }
        }
    }
    rv = CheckXPCPermissions(aObj, objectSecurityLevel);
#ifdef DEBUG_CAPS_CheckPropertyAccessImpl
    if(NS_SUCCEEDED(rv))
        printf("CheckXPCPerms GRANTED.\n");
    else
        printf("CheckXPCPerms DENIED.\n");
#endif

    if (NS_FAILED(rv)) //-- Security tests failed, access is denied, report error
    {
        nsAutoString stringName;
        switch(aAction)
        {
        case nsIXPCSecurityManager::ACCESS_GET_PROPERTY:
            stringName.AssignLiteral("GetPropertyDenied");
            break;
        case nsIXPCSecurityManager::ACCESS_SET_PROPERTY:
            stringName.AssignLiteral("SetPropertyDenied");
            break;
        case nsIXPCSecurityManager::ACCESS_CALL_METHOD:
            stringName.AssignLiteral("CallMethodDenied");
        }

        NS_ConvertUTF8toUTF16 className(classInfoData.GetName());
        const PRUnichar *formatStrings[] =
        {
            className.get(),
            JSValIDToString(cx, aProperty)
        };

        nsXPIDLString errorMsg;
        // 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,
                                                        NS_ARRAY_LENGTH(formatStrings),
                                                        getter_Copies(errorMsg));
        NS_ENSURE_SUCCESS(rv2, rv2);

        SetPendingException(cx, errorMsg.get());

        if (sXPConnect)
        {
            nsCOMPtr<nsIXPCNativeCallContext> xpcCallContext;
            sXPConnect->GetCurrentNativeCallContext(getter_AddRefs(xpcCallContext));
            if (xpcCallContext)
                xpcCallContext->SetExceptionWasThrown(PR_TRUE);
        }
    }

    return rv;
}

Here is the call graph for this function:

void nsIScriptSecurityManager::checkSameOrigin ( in JSContextPtr  aJSContext,
in nsIURI  aTargetURI 
) [inherited]

Returns OK if aJSContext and target have the same "origin" (scheme, host, and port).

nsresult nsScriptSecurityManager::CheckSameOriginDOMProp ( nsIPrincipal aSubject,
nsIPrincipal aObject,
PRUint32  aAction,
PRBool  aIsCheckConnect 
) [private]

Definition at line 934 of file nsScriptSecurityManager.cpp.

{
    nsresult rv;
    if (aIsCheckConnect) {
        // Don't do equality compares, just do a same-origin compare,
        // since the object principal isn't a real principal, just a
        // GetCodebasePrincipal() on whatever URI we started with.
        rv = CheckSameOriginPrincipal(aSubject, aObject, aIsCheckConnect);
    } else {
        PRBool 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;

    /*
    * If we failed the origin tests it still might be the case that we
    * are a signed script and have permissions to do this operation.
    * Check for that here.
    */
    PRBool capabilityEnabled = PR_FALSE;
    const char* cap = aAction == nsIXPCSecurityManager::ACCESS_SET_PROPERTY ?
                      "UniversalBrowserWrite" : "UniversalBrowserRead";
    rv = IsCapabilityEnabled(cap, &capabilityEnabled);
    NS_ENSURE_SUCCESS(rv, rv);
    if (capabilityEnabled)
        return NS_OK;

    /*
    ** Access tests failed, so now report error.
    */
    return NS_ERROR_DOM_PROP_ACCESS_DENIED;
}

Here is the call graph for this function:

Here is the caller graph for this function:

void nsIScriptSecurityManager::checkSameOriginPrincipal ( in nsIPrincipal  aSourcePrincipal,
in nsIPrincipal  aTargetPrincipal 
) [inherited]

Returns OK if aSourcePrincipal and aTargetPrincipal have the same "origin" (scheme, host, and port).

nsresult nsScriptSecurityManager::CheckSameOriginPrincipal ( nsIPrincipal aSubject,
nsIPrincipal aObject,
PRBool  aIsCheckConnect 
) [static]

Definition at line 633 of file nsScriptSecurityManager.cpp.

{
    return CheckSameOriginPrincipal(aSourcePrincipal, aTargetPrincipal,
                                    PR_FALSE);
}

Here is the caller graph for this function:

void nsIScriptSecurityManager::checkSameOriginURI ( in nsIURI  aSourceURI,
in nsIURI  aTargetURI 
) [inherited]

Returns OK if aSourceURI and target have the same "origin" (scheme, host, and port).

nsresult nsScriptSecurityManager::CheckXPCPermissions ( nsISupports *  aObj,
const char *  aObjectSecurityLevel 
) [private]

Definition at line 2982 of file nsScriptSecurityManager.cpp.

{
    //-- Check for the all-powerful UniversalXPConnect privilege
    PRBool ok = PR_FALSE;
    if (NS_SUCCEEDED(IsCapabilityEnabled("UniversalXPConnect", &ok)) && ok)
        return NS_OK;

    //-- If the object implements nsISecurityCheckedComponent, it has a non-default policy.
    if (aObjectSecurityLevel)
    {
        if (PL_strcasecmp(aObjectSecurityLevel, "AllAccess") == 0)
            return NS_OK;
        else if (PL_strcasecmp(aObjectSecurityLevel, "NoAccess") != 0)
        {
            PRBool canAccess = PR_FALSE;
            if (NS_SUCCEEDED(IsCapabilityEnabled(aObjectSecurityLevel, &canAccess)) &&
                canAccess)
                return NS_OK;
        }
    }

    //-- If user allows scripting of plugins by untrusted scripts,
    //   and the target object is a plugin, allow the access.
    if(aObj)
    {
        nsresult rv;
        nsCOMPtr<nsIPluginInstance> plugin(do_QueryInterface(aObj, &rv));
        if (NS_SUCCEEDED(rv))
        {
            static PRBool prefSet = PR_FALSE;
            static PRBool allowPluginAccess = PR_FALSE;
            if (!prefSet)
            {
                rv = mSecurityPref->SecurityGetBoolPref("security.xpconnect.plugin.unrestricted",
                                                       &allowPluginAccess);
                prefSet = PR_TRUE;
            }
            if (allowPluginAccess)
                return NS_OK;
        }
    }

    //-- Access tests failed
    return NS_ERROR_DOM_XPCONNECT_ACCESS_DENIED;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 1989 of file nsScriptSecurityManager.cpp.

{
    nsRefPtr<nsPrincipal> codebase = new nsPrincipal();
    if (!codebase)
        return NS_ERROR_OUT_OF_MEMORY;

    nsresult rv = codebase->Init(EmptyCString(), EmptyCString(),
                                 EmptyCString(), nsnull, aURI);
    if (NS_FAILED(rv))
        return rv;

    NS_ADDREF(*result = codebase);

    return NS_OK;
}

Here is the call graph for this function:

Disable 'capability' in the innermost frame of the currently executing script.

nsresult nsScriptSecurityManager::DoGetCertificatePrincipal ( const nsACString &  aCertFingerprint,
const nsACString &  aSubjectName,
const nsACString &  aPrettyName,
nsISupports *  aCertificate,
nsIURI aURI,
PRBool  aModifyTable,
nsIPrincipal **  result 
) [private]

Definition at line 1901 of file nsScriptSecurityManager.cpp.

{
    NS_ENSURE_ARG(!aCertFingerprint.IsEmpty());
    
    // Create a certificate principal out of the certificate ID
    // and URI given to us.  We will use this principal to test
    // equality when doing our hashtable lookups below.
    nsRefPtr<nsPrincipal> certificate = new nsPrincipal();
    if (!certificate)
        return NS_ERROR_OUT_OF_MEMORY;

    nsresult rv = certificate->Init(aCertFingerprint, aSubjectName,
                                    aPrettyName, aCertificate, aURI);
    NS_ENSURE_SUCCESS(rv, rv);

    // Check to see if we already have this principal.
    nsCOMPtr<nsIPrincipal> fromTable;
    mPrincipals.Get(certificate, getter_AddRefs(fromTable));
    if (fromTable) {
        // Bingo.  We found the certificate in the table, which means
        // that it has escalated privileges.

        if (aModifyTable) {
            // Make sure this principal has names, so if we ever go to save it
            // we'll save them.  If we get a name mismatch here we'll throw,
            // but that's desirable.
            rv = NS_STATIC_CAST(nsPrincipal*,
                                NS_STATIC_CAST(nsIPrincipal*, fromTable))
                ->EnsureCertData(aSubjectName, aPrettyName, aCertificate);
            if (NS_FAILED(rv)) {
                // We have a subject name mismatch for the same cert id.
                // Hand back the |certificate| object we created and don't give
                // it any rights from the table.
                NS_ADDREF(*result = certificate);
                return NS_OK;
            }                
        }
        
        if (!aURI) {
            // We were asked to just get the base certificate, so output
            // what we have in the table.
            certificate = NS_STATIC_CAST(nsPrincipal*,
                                         NS_STATIC_CAST(nsIPrincipal*,
                                                        fromTable));
        } else {
            // We found a certificate and now need to install a codebase
            // on it.  We don't want to modify the principal in the hash
            // table, so create a new principal and clone the pertinent
            // things.
            nsXPIDLCString prefName;
            nsXPIDLCString id;
            nsXPIDLCString subjectName;
            nsXPIDLCString granted;
            nsXPIDLCString denied;
            rv = fromTable->GetPreferences(getter_Copies(prefName),
                                           getter_Copies(id),
                                           getter_Copies(subjectName),
                                           getter_Copies(granted),
                                           getter_Copies(denied));
            // XXXbz assert something about subjectName and aSubjectName here?
            if (NS_SUCCEEDED(rv)) {
                certificate = new nsPrincipal();
                if (!certificate)
                    return NS_ERROR_OUT_OF_MEMORY;

                rv = certificate->InitFromPersistent(prefName, id,
                                                     subjectName, aPrettyName,
                                                     granted, denied,
                                                     aCertificate,
                                                     PR_TRUE, PR_FALSE);
                if (NS_SUCCEEDED(rv))
                    certificate->SetURI(aURI);
            }
        }
    }

    NS_ADDREF(*result = certificate);

    return rv;
}

Here is the call graph for this function:

Definition at line 2250 of file nsScriptSecurityManager.cpp.

{
    NS_ASSERTION(aCx && aObj, "Bad call to doGetObjectPrincipal()!");
    nsIPrincipal* result = nsnull;

    do
    {
        const JSClass *jsClass = JS_GetClass(aCx, aObj);

        if (jsClass && !(~jsClass->flags & (JSCLASS_HAS_PRIVATE |
                                            JSCLASS_PRIVATE_IS_NSISUPPORTS)))
        {
            // No need to refcount |priv| here.
            nsISupports *priv = (nsISupports *)JS_GetPrivate(aCx, aObj);
            nsCOMPtr<nsIScriptObjectPrincipal> objPrin;

            /*
             * If it's a wrapped native (as most
             * JSCLASS_PRIVATE_IS_NSISUPPORTS objects are in mozilla),
             * check the underlying native instead.
             */
            nsCOMPtr<nsIXPConnectWrappedNative> xpcWrapper =
                do_QueryInterface(priv);

            if (xpcWrapper)
            {
                objPrin = do_QueryWrappedNative(xpcWrapper);
            }
            else
            {
                objPrin = do_QueryInterface(priv);
            }

            if (objPrin && (result = objPrin->GetPrincipal()))
            {
                break;
            }
        }

        aObj = JS_GetParent(aCx, aObj);
    } while (aObj);

    return result;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 1823 of file nsScriptSecurityManager.cpp.

{
    NS_PRECONDITION(rv, "Null out param");
    JSContext *cx = GetCurrentJSContext();
    if (!cx)
    {
        *rv = NS_OK;
        return nsnull;
    }
    return GetSubjectPrincipal(cx, rv);
}

Here is the call graph for this function:

Here is the caller graph for this function:

Enable 'capability' in the innermost frame of the currently executing script.

void nsScriptSecurityManager::FormatCapabilityString ( nsAString &  aCapability) [static, private]

Definition at line 2414 of file nsScriptSecurityManager.cpp.

{
    nsAutoString newcaps;
    nsAutoString rawcap;
    NS_NAMED_LITERAL_STRING(capdesc, "capdesc.");
    PRInt32 pos;
    PRInt32 index = kNotFound;
    nsresult rv;

    NS_ASSERTION(kNotFound == -1, "Basic constant changed, algorithm broken!");

    do {
        pos = index+1;
        index = aCapability.FindChar(' ', pos);
        rawcap = Substring(aCapability, pos,
                           (index == kNotFound) ? index : index - pos);

        nsXPIDLString capstr;
        rv = sStrBundle->GetStringFromName(
                            nsPromiseFlatString(capdesc+rawcap).get(),
                            getter_Copies(capstr));
        if (NS_SUCCEEDED(rv))
            newcaps += capstr;
        else
        {
            nsXPIDLString extensionCap;
            const PRUnichar* formatArgs[] = { rawcap.get() };
            rv = sStrBundle->FormatStringFromName(
                                NS_LITERAL_STRING("ExtensionCapability").get(),
                                formatArgs,
                                NS_ARRAY_LENGTH(formatArgs),
                                getter_Copies(extensionCap));
            if (NS_SUCCEEDED(rv))
                newcaps += extensionCap;
            else
                newcaps += rawcap;
        }

        newcaps += NS_LITERAL_STRING("\n");
    } while (index != kNotFound);

    aCapability = newcaps;
}

Here is the call graph for this function:

Here is the caller graph for this function:

nsresult nsScriptSecurityManager::GetBaseURIScheme ( nsIURI aURI,
nsCString aScheme 
) [static, private]

Definition at line 1251 of file nsScriptSecurityManager.cpp.

{
    if (!aURI)
       return NS_ERROR_FAILURE;

    nsresult rv;

    //-- get the source scheme
    rv = aURI->GetScheme(aScheme);
    if (NS_FAILED(rv)) return rv;

    //-- If aURI is a view-source URI, drill down to the base URI
    if (aScheme.EqualsLiteral("view-source"))
    {
        nsCAutoString path;
        rv = aURI->GetPath(path);
        if (NS_FAILED(rv)) return rv;
        nsCOMPtr<nsIURI> innerURI;
        rv = NS_NewURI(getter_AddRefs(innerURI), path, nsnull, nsnull,
                       sIOService);
        if (NS_FAILED(rv)) return rv;
        return nsScriptSecurityManager::GetBaseURIScheme(innerURI, aScheme);
    }

    //-- If aURI is a jar URI, drill down again
    nsCOMPtr<nsIJARURI> jarURI = do_QueryInterface(aURI);
    if (jarURI)
    {
        nsCOMPtr<nsIURI> innerURI;
        jarURI->GetJARFile(getter_AddRefs(innerURI));
        if (!innerURI) return NS_ERROR_FAILURE;
        return nsScriptSecurityManager::GetBaseURIScheme(innerURI, aScheme);
    }

    //-- if aURI is an about uri, distinguish 'safe' and 'unsafe' about URIs
    if(aScheme.EqualsLiteral("about"))
    {
        nsCAutoString path;
        rv = NS_GetAboutModuleName(aURI, path);
        NS_ENSURE_SUCCESS(rv, rv);
        if (path.EqualsLiteral("blank")   ||
            path.EqualsLiteral("mozilla") ||
            path.EqualsLiteral("logo")    ||
            path.EqualsLiteral("license") ||
            path.EqualsLiteral("licence") ||
            path.EqualsLiteral("credits") ||
            path.EqualsLiteral("neterror") ||
            path.EqualsLiteral("feeds")) // FIXME: make this list extendable
        {
            aScheme = NS_LITERAL_CSTRING("about safe");
            return NS_OK;
        }
    }

    return NS_OK;
}

Here is the call graph for this function:

nsIPrincipal nsIScriptSecurityManager::getCertificatePrincipal ( in AUTF8String  aCertFingerprint,
in AUTF8String  aSubjectName,
in AUTF8String  aPrettyName,
in nsISupports  aCert,
in nsIURI  aURI 
) [inherited]

Return a principal with the specified certificate fingerprint, subject name (the full name or concatenated set of names of the entity represented by the certificate), pretty name, certificate, and codebase URI.

The certificate fingerprint and subject name MUST be nonempty; otherwise an error will be thrown. Similarly, aCert must not be null.

Return a principal that has the same origin as aURI.

Definition at line 212 of file nsScriptSecurityManager.cpp.

{
    // Get JSContext from stack.
    if (!mJSContextStack)
    {
        mJSContextStack = do_GetService("@mozilla.org/js/xpc/ContextStack;1");
        if (!mJSContextStack)
            return nsnull;
    }
    JSContext *cx;
    if (NS_FAILED(mJSContextStack->Peek(&cx)))
        return nsnull;
    return cx;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 2148 of file nsScriptSecurityManager.cpp.

{
    NS_PRECONDITION(rv, "Null out param");
    JSObject *obj = JS_GetFrameFunctionObject(cx, fp);
    if (!obj)
    {
        // Must be in a top-level script. Get principal from the script.
        JSScript *script = JS_GetFrameScript(cx, fp);
        return GetScriptPrincipal(cx, script, rv);
    }

    nsIPrincipal* result = GetFunctionObjectPrincipal(cx, obj, fp, rv);

#ifdef DEBUG
    if (NS_SUCCEEDED(*rv) && !result)
    {
        JSFunction *fun = (JSFunction *)JS_GetPrivate(cx, obj);
        JSScript *script = JS_GetFunctionScript(cx, fun);

        NS_ASSERTION(!script, "Null principal for non-native function!");
    }
#endif

    return result;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 2091 of file nsScriptSecurityManager.cpp.

{
    NS_PRECONDITION(rv, "Null out param");
    JSFunction *fun = (JSFunction *) JS_GetPrivate(cx, obj);
    JSScript *script = JS_GetFunctionScript(cx, fun);

    *rv = NS_OK;

    if (!script)
    {
        // A native function: skip it in order to find its scripted caller.
        return nsnull;
    }

    JSScript *frameScript = fp ? JS_GetFrameScript(cx, fp) : nsnull;

    if (frameScript && frameScript != script)
    {
        // There is a frame script, and it's different from the
        // function script. In this case we're dealing with either
        // an eval or a Script object, and in these cases the
        // principal we want is in the frame's script, not in the
        // function's script. The function's script is where the
        // eval-calling code came from, not where the eval or new
        // Script object came from, and we want the principal of
        // the eval function object or new Script object.

        script = frameScript;
    }
    else if (JS_GetFunctionObject(fun) != obj)
    {
        // Here, obj is a cloned function object.  In this case, the
        // clone's prototype may have been precompiled from brutally
        // shared chrome, or else it is a lambda or nested function.
        // The general case here is a function compiled against a
        // different scope than the one it is parented by at runtime,
        // hence the creation of a clone to carry the correct scope
        // chain linkage.
        //
        // Since principals follow scope, we must get the object
        // principal from the clone's scope chain. There are no
        // reliable principals compiled into the function itself.

        nsIPrincipal *result = doGetObjectPrincipal(cx, obj);
        if (!result)
            *rv = NS_ERROR_FAILURE;
        return result;
    }

    return GetScriptPrincipal(cx, script, rv);
}

Here is the call graph for this function:

Here is the caller graph for this function:

Return the principal of the specified object in the specified context.

nsIPrincipal * nsScriptSecurityManager::GetPrincipalAndFrame ( JSContext cx,
JSStackFrame **  frameResult,
nsresult rv 
) [static, private]

Definition at line 2178 of file nsScriptSecurityManager.cpp.

{
    NS_PRECONDITION(rv, "Null out param");    
    //-- If there's no principal on the stack, look at the global object
    //   and return the innermost frame for annotations.
    *rv = NS_OK;
    if (cx)
    {
        // Get principals from innermost frame of JavaScript or Java.
        JSStackFrame *fp = nsnull; // tell JS_FrameIterator to start at innermost
        for (fp = JS_FrameIterator(cx, &fp); fp; fp = JS_FrameIterator(cx, &fp))
        {
            nsIPrincipal* result = GetFramePrincipal(cx, fp, rv);
            if (result)
            {
                NS_ASSERTION(NS_SUCCEEDED(*rv), "Weird return");
                *frameResult = fp;
                return result;
            }
        }

        nsIScriptContext *scriptContext = GetScriptContext(cx);
        if (scriptContext)
        {
            nsCOMPtr<nsIScriptObjectPrincipal> globalData =
                do_QueryInterface(scriptContext->GetGlobalObject());
            if (!globalData)
            {
                *rv = NS_ERROR_FAILURE;
                return nsnull;
            }

            // Note that we're not in a loop or anything, and nothing comes
            // after this point in the function, so we can just return here.
            nsIPrincipal* result = globalData->GetPrincipal();
            if (result)
            {
                JSStackFrame *inner = nsnull;
                *frameResult = JS_FrameIterator(cx, &inner);
                return result;
            }
        }
    }

    return nsnull;
}

Here is the call graph for this function:

Returns the principal of the global object of the given context, or null if no global or no principal.

nsresult nsScriptSecurityManager::GetPrincipalPrefNames ( const char *  prefBase,
nsCString grantedPref,
nsCString deniedPref,
nsCString subjectNamePref 
) [static, private]

Definition at line 3528 of file nsScriptSecurityManager.cpp.

{
    char* lastDot = PL_strrchr(prefBase, '.');
    if (!lastDot) return NS_ERROR_FAILURE;
    PRInt32 prefLen = lastDot - prefBase + 1;

    grantedPref.Assign(prefBase, prefLen);
    deniedPref.Assign(prefBase, prefLen);
    subjectNamePref.Assign(prefBase, prefLen);

#define GRANTED "granted"
#define DENIED "denied"
#define SUBJECTNAME "subjectName"

    grantedPref.AppendLiteral(GRANTED);
    if (grantedPref.Length() != prefLen + sizeof(GRANTED) - 1) {
        return NS_ERROR_OUT_OF_MEMORY;
    }

    deniedPref.AppendLiteral(DENIED);
    if (deniedPref.Length() != prefLen + sizeof(DENIED) - 1) {
        return NS_ERROR_OUT_OF_MEMORY;
    }

    subjectNamePref.AppendLiteral(SUBJECTNAME);
    if (subjectNamePref.Length() != prefLen + sizeof(SUBJECTNAME) - 1) {
        return NS_ERROR_OUT_OF_MEMORY;
    }

#undef SUBJECTNAME
#undef DENIED
#undef GRANTED
    
    return NS_OK;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 1676 of file nsScriptSecurityManager.cpp.

{
    nsresult rv;
    *result = nsnull;
    nsIScriptContext *scriptContext = GetScriptContext(cx);
    if (!scriptContext)
        return NS_ERROR_FAILURE;

    nsIScriptGlobalObject *globalObject = scriptContext->GetGlobalObject();
    if (!globalObject)
        return NS_ERROR_FAILURE;

    nsCOMPtr<nsIDocShellTreeItem> docshellTreeItem =
        do_QueryInterface(globalObject->GetDocShell(), &rv);
    if (NS_FAILED(rv)) return rv;

    nsCOMPtr<nsIDocShellTreeItem> rootItem;
    rv = docshellTreeItem->GetRootTreeItem(getter_AddRefs(rootItem));
    if (NS_FAILED(rv)) return rv;

    return rootItem->QueryInterface(NS_GET_IID(nsIDocShell), (void**)result);
}

Here is the call graph for this function:

Definition at line 228 of file nsScriptSecurityManager.cpp.

{
    // Get JSContext from stack.
    if (!mJSContextStack) {
        mJSContextStack = do_GetService("@mozilla.org/js/xpc/ContextStack;1");
        if (!mJSContextStack)
            return nsnull;
    }

    JSContext *cx;
    if (NS_FAILED(mJSContextStack->GetSafeJSContext(&cx)))
        return nsnull;
    return cx;
}

Here is the call graph for this function:

Here is the caller graph for this function:

nsIPrincipal * nsScriptSecurityManager::GetScriptPrincipal ( JSContext cx,
JSScript script,
nsresult rv 
) [static, private]

Definition at line 2066 of file nsScriptSecurityManager.cpp.

{
    NS_PRECONDITION(rv, "Null out param");
    *rv = NS_OK;
    if (!script)
    {
        return nsnull;
    }
    JSPrincipals *jsp = JS_GetScriptPrincipals(cx, script);
    if (!jsp) {
        *rv = NS_ERROR_FAILURE;
        // Script didn't have principals -- shouldn't happen.
        return nsnull;
    }
    nsJSPrincipals *nsJSPrin = NS_STATIC_CAST(nsJSPrincipals *, jsp);
    nsIPrincipal* result = nsJSPrin->nsIPrincipalPtr;
    if (!result)
        *rv = NS_ERROR_FAILURE;
    return result;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 3175 of file nsScriptSecurityManager.cpp.

{
    if (!gScriptSecMan)
    {
        nsScriptSecurityManager* ssManager = new nsScriptSecurityManager();
        if (!ssManager)
            return nsnull;
        nsresult rv;
        rv = ssManager->Init();
        NS_ASSERTION(NS_SUCCEEDED(rv), "Failed to initialize nsScriptSecurityManager");
        if (NS_FAILED(rv)) {
            delete ssManager;
            return nsnull;
        }
 
        rv = nsJSPrincipals::Startup();
        if (NS_FAILED(rv)) {
            NS_WARNING("can't initialize JS engine security protocol glue!");
            delete ssManager;
            return nsnull;
        }
 
        rv = sXPConnect->SetDefaultSecurityManager(ssManager,
                                                   nsIXPCSecurityManager::HOOK_ALL);
        if (NS_FAILED(rv)) {
            NS_WARNING("Failed to install xpconnect security manager!");
            delete ssManager;
            return nsnull;
        }

        gScriptSecMan = ssManager;
    }
    return gScriptSecMan;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Return the principal of the innermost frame of the currently executing script.

Will return null if there is no script currently executing.

Definition at line 1813 of file nsScriptSecurityManager.cpp.

{
    nsresult rv;
    *aSubjectPrincipal = doGetSubjectPrincipal(&rv);
    if (NS_SUCCEEDED(rv))
        NS_IF_ADDREF(*aSubjectPrincipal);
    return rv;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Return the all-powerful system principal.

Definition at line 3099 of file nsScriptSecurityManager.cpp.

{
    JSContext* cx = GetSafeJSContext();
    if (!cx) return NS_ERROR_FAILURE;   // this can happen of xpt loading fails
    
    ::JS_BeginRequest(cx);
    if (sEnabledID == JSVAL_VOID)
        sEnabledID = STRING_TO_JSVAL(::JS_InternString(cx, "enabled"));
    ::JS_EndRequest(cx);

    nsresult rv = InitPrefs();
    NS_ENSURE_SUCCESS(rv, rv);

    rv = CallGetService(NS_IOSERVICE_CONTRACTID, &sIOService);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = CallGetService(nsIXPConnect::GetCID(), &sXPConnect);
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIStringBundleService> bundleService = do_GetService(NS_STRINGBUNDLE_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = bundleService->CreateBundle("chrome://global/locale/security/caps.properties", &sStrBundle);
    NS_ENSURE_SUCCESS(rv, rv);

    //-- Register security check callback in the JS engine
    //   Currently this is used to control access to function.caller
    nsCOMPtr<nsIJSRuntimeService> runtimeService =
        do_GetService("@mozilla.org/js/xpc/RuntimeService;1", &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = runtimeService->GetRuntime(&sRuntime);
    NS_ENSURE_SUCCESS(rv, rv);

#ifdef DEBUG
    JSCheckAccessOp oldCallback =
#endif
        JS_SetCheckObjectAccessCallback(sRuntime, CheckObjectAccess);

    // For now, assert that no callback was set previously
    NS_ASSERTION(!oldCallback, "Someone already set a JS CheckObjectAccess callback");
    return NS_OK;
}

Here is the call graph for this function:

Here is the caller graph for this function:

nsresult nsScriptSecurityManager::InitDomainPolicy ( JSContext cx,
const char *  aPolicyName,
DomainPolicy aDomainPolicy 
) [private]

Definition at line 3399 of file nsScriptSecurityManager.cpp.

{
    nsresult rv;
    nsCAutoString policyPrefix(NS_LITERAL_CSTRING(sPolicyPrefix) +
                               nsDependentCString(aPolicyName) +
                               NS_LITERAL_CSTRING("."));
    PRUint32 prefixLength = policyPrefix.Length() - 1; // subtract the '.'

    PRUint32 prefCount;
    char** prefNames;
    rv = mPrefBranch->GetChildList(policyPrefix.get(),
                                   &prefCount, &prefNames);
    if (NS_FAILED(rv)) return rv;
    if (prefCount == 0)
        return NS_OK;

    //-- Populate the policy
    PRUint32 currentPref = 0;
    for (; currentPref < prefCount; currentPref++)
    {
        // Get the class name
        const char* start = prefNames[currentPref] + prefixLength + 1;
        char* end = PL_strchr(start, '.');
        if (!end) // malformed pref, bail on this one
            continue;
        static const char sitesStr[] = "sites";

        // We dealt with "sites" in InitPolicies(), so no need to do
        // that again...
        if (PL_strncmp(start, sitesStr, sizeof(sitesStr)-1) == 0)
            continue;

        // Get the pref value
        nsXPIDLCString prefValue;
        rv = mSecurityPref->SecurityGetCharPref(prefNames[currentPref],
                                                getter_Copies(prefValue));
        if (NS_FAILED(rv) || !prefValue)
            continue;

        SecurityLevel secLevel;
        if (PL_strcasecmp(prefValue, "noAccess") == 0)
            secLevel.level = SCRIPT_SECURITY_NO_ACCESS;
        else if (PL_strcasecmp(prefValue, "allAccess") == 0)
            secLevel.level = SCRIPT_SECURITY_ALL_ACCESS;
        else if (PL_strcasecmp(prefValue, "sameOrigin") == 0)
            secLevel.level = SCRIPT_SECURITY_SAME_ORIGIN_ACCESS;
        else 
        {  //-- pref value is the name of a capability
            nsCStringKey secLevelKey(prefValue);
            secLevel.capability =
                NS_REINTERPRET_CAST(char*, mCapabilities->Get(&secLevelKey));
            if (!secLevel.capability)
            {
                secLevel.capability = nsCRT::strdup(prefValue);
                if (!secLevel.capability)
                    break;
                mCapabilities->Put(&secLevelKey, 
                                   secLevel.capability);
            }
        }

        *end = '\0';
        // Find or store this class in the classes table
        ClassPolicy* cpolicy = 
          NS_STATIC_CAST(ClassPolicy*,
                         PL_DHashTableOperate(aDomainPolicy, start,
                                              PL_DHASH_ADD));
        if (!cpolicy)
            break;

        // If this is the wildcard class (class '*'), save it in mWildcardPolicy
        // (we leave it stored in the hashtable too to take care of the cleanup)
        if ((*start == '*') && (end == start + 1)) {
            aDomainPolicy->mWildcardPolicy = cpolicy;

            // Make sure that cpolicy knows about aDomainPolicy so it can reset
            // the mWildcardPolicy pointer as needed if it gets moved in the
            // hashtable.
            cpolicy->mDomainWeAreWildcardFor = aDomainPolicy;
        }

        // Get the property name
        start = end + 1;
        end = PL_strchr(start, '.');
        if (end)
            *end = '\0';

        JSString* propertyKey = ::JS_InternString(cx, start);
        if (!propertyKey)
            return NS_ERROR_OUT_OF_MEMORY;

        // Store this property in the class policy
        const void* ppkey =
          NS_REINTERPRET_CAST(const void*, STRING_TO_JSVAL(propertyKey));
        PropertyPolicy* ppolicy = 
          NS_STATIC_CAST(PropertyPolicy*,
                         PL_DHashTableOperate(cpolicy->mPolicy, ppkey,
                                              PL_DHASH_ADD));
        if (!ppolicy)
            break;

        if (end) // The pref specifies an access mode
        {
            start = end + 1;
            if (PL_strcasecmp(start, "set") == 0)
                ppolicy->mSet = secLevel;
            else
                ppolicy->mGet = secLevel;
        }
        else
        {
            if (ppolicy->mGet.level == SCRIPT_SECURITY_UNDEFINED_ACCESS)
                ppolicy->mGet = secLevel;
            if (ppolicy->mSet.level == SCRIPT_SECURITY_UNDEFINED_ACCESS)
                ppolicy->mSet = secLevel;
        }
    }

    NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(prefCount, prefNames);
    if (currentPref < prefCount) // Loop exited early because of out-of-memory error
        return NS_ERROR_OUT_OF_MEMORY;
    return NS_OK;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 3223 of file nsScriptSecurityManager.cpp.

{
    // Clear any policies cached on XPConnect wrappers
    NS_ENSURE_STATE(sXPConnect);
    nsresult rv = sXPConnect->ClearAllWrappedNativeSecurityPolicies();
    if (NS_FAILED(rv)) return rv;

    //-- Clear mOriginToPolicyMap: delete mapped DomainEntry items,
    //-- whose dtor decrements refcount of stored DomainPolicy object
    delete mOriginToPolicyMap;
    
    //-- Marks all the survivor DomainPolicy objects (those cached
    //-- by nsPrincipal objects) as invalid: they will be released
    //-- on first nsPrincipal::GetSecurityPolicy() attempt.
    DomainPolicy::InvalidateAll();
    
    //-- Release old default policy
    if(mDefaultPolicy) {
        mDefaultPolicy->Drop();
        mDefaultPolicy = nsnull;
    }
    
    //-- Initialize a new mOriginToPolicyMap
    mOriginToPolicyMap =
      new nsObjectHashtable(nsnull, nsnull, DeleteDomainEntry, nsnull);
    if (!mOriginToPolicyMap)
        return NS_ERROR_OUT_OF_MEMORY;

    //-- Create, refcount and initialize a new default policy 
    mDefaultPolicy = new DomainPolicy();
    if (!mDefaultPolicy)
        return NS_ERROR_OUT_OF_MEMORY;

    mDefaultPolicy->Hold();
    if (!mDefaultPolicy->Init())
        return NS_ERROR_UNEXPECTED;

    //-- Initialize the table of security levels
    if (!mCapabilities)
    {
        mCapabilities = 
          new nsObjectHashtable(nsnull, nsnull, DeleteCapability, nsnull);
        if (!mCapabilities)
            return NS_ERROR_OUT_OF_MEMORY;
    }

    // Get a JS context - we need it to create internalized strings later.
    JSContext* cx = GetSafeJSContext();
    NS_ASSERTION(cx, "failed to get JS context");
    rv = InitDomainPolicy(cx, "default", mDefaultPolicy);
    NS_ENSURE_SUCCESS(rv, rv);

    nsXPIDLCString policyNames;
    rv = mSecurityPref->SecurityGetCharPref("capability.policy.policynames",
                                            getter_Copies(policyNames));

    nsXPIDLCString defaultPolicyNames;
    rv = mSecurityPref->SecurityGetCharPref("capability.policy.default_policynames",
                                            getter_Copies(defaultPolicyNames));
    policyNames += NS_LITERAL_CSTRING(" ") + defaultPolicyNames;

    //-- Initialize domain policies
    char* policyCurrent = policyNames.BeginWriting();
    PRBool morePolicies = PR_TRUE;
    while (morePolicies)
    {
        while(*policyCurrent == ' ' || *policyCurrent == ',')
            policyCurrent++;
        if (*policyCurrent == '\0')
            break;
        char* nameBegin = policyCurrent;

        while(*policyCurrent != '\0' && *policyCurrent != ' ' && *policyCurrent != ',')
            policyCurrent++;

        morePolicies = (*policyCurrent != '\0');
        *policyCurrent = '\0';
        policyCurrent++;

        nsCAutoString sitesPrefName(
            NS_LITERAL_CSTRING(sPolicyPrefix) +
                                nsDependentCString(nameBegin) +
                                NS_LITERAL_CSTRING(".sites"));
        nsXPIDLCString domainList;
        rv = mSecurityPref->SecurityGetCharPref(sitesPrefName.get(),
                                                getter_Copies(domainList));
        if (NS_FAILED(rv))
            continue;

        DomainPolicy* domainPolicy = new DomainPolicy();
        if (!domainPolicy)
            return NS_ERROR_OUT_OF_MEMORY;

        if (!domainPolicy->Init())
        {
            delete domainPolicy;
            return NS_ERROR_UNEXPECTED;
        }
        domainPolicy->Hold();
        //-- Parse list of sites and create an entry in mOriginToPolicyMap for each
        char* domainStart = domainList.BeginWriting();
        char* domainCurrent = domainStart;
        char* lastDot = nsnull;
        char* nextToLastDot = nsnull;
        PRBool moreDomains = PR_TRUE;
        while (moreDomains)
        {
            if (*domainCurrent == ' ' || *domainCurrent == '\0')
            {
                moreDomains = (*domainCurrent != '\0');
                *domainCurrent = '\0';
                nsCStringKey key(nextToLastDot ? nextToLastDot+1 : domainStart);
                DomainEntry *newEntry = new DomainEntry(domainStart, domainPolicy);
                if (!newEntry)
                {
                    domainPolicy->Drop();
                    return NS_ERROR_OUT_OF_MEMORY;
                }
#ifdef DEBUG
                newEntry->mPolicyName_DEBUG = nameBegin;
#endif
                DomainEntry *existingEntry = (DomainEntry *)
                    mOriginToPolicyMap->Get(&key);
                if (!existingEntry)
                    mOriginToPolicyMap->Put(&key, newEntry);
                else
                {
                    if (existingEntry->Matches(domainStart))
                    {
                        newEntry->mNext = existingEntry;
                        mOriginToPolicyMap->Put(&key, newEntry);
                    }
                    else
                    {
                        while (existingEntry->mNext)
                        {
                            if (existingEntry->mNext->Matches(domainStart))
                            {
                                newEntry->mNext = existingEntry->mNext;
                                existingEntry->mNext = newEntry;
                                break;
                            }
                            existingEntry = existingEntry->mNext;
                        }
                        if (!existingEntry->mNext)
                            existingEntry->mNext = newEntry;
                    }
                }
                domainStart = domainCurrent + 1;
                lastDot = nextToLastDot = nsnull;
            }
            else if (*domainCurrent == '.')
            {
                nextToLastDot = lastDot;
                lastDot = domainCurrent;
            }
            domainCurrent++;
        }

        rv = InitDomainPolicy(cx, nameBegin, domainPolicy);
        domainPolicy->Drop();
        if (NS_FAILED(rv))
            return rv;
    }

    // Reset the "dirty" flag
    mPolicyPrefsChanged = PR_FALSE;

#ifdef DEBUG_CAPS_HACKER
    PrintPolicyDB();
#endif
    return NS_OK;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 3695 of file nsScriptSecurityManager.cpp.

{
    nsresult rv;
    nsCOMPtr<nsIPrefService> prefService(do_GetService(NS_PREFSERVICE_CONTRACTID, &rv));
    NS_ENSURE_SUCCESS(rv, rv);
    rv = prefService->GetBranch(nsnull, getter_AddRefs(mPrefBranch));
    NS_ENSURE_SUCCESS(rv, rv);
    nsCOMPtr<nsIPrefBranch2> prefBranchInternal(do_QueryInterface(mPrefBranch, &rv));
    NS_ENSURE_SUCCESS(rv, rv);
    mSecurityPref = do_QueryInterface(mPrefBranch, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    // Set the initial value of the "javascript.enabled" prefs
    JSEnabledPrefChanged(mSecurityPref);
    // set observer callbacks in case the value of the prefs change
    prefBranchInternal->AddObserver(sJSEnabledPrefName, this, PR_FALSE);
    prefBranchInternal->AddObserver(sJSMailEnabledPrefName, this, PR_FALSE);
#ifdef XPC_IDISPATCH_SUPPORT
    prefBranchInternal->AddObserver(sXPCDefaultGrantAllName, this, PR_FALSE);
#endif
    PRUint32 prefCount;
    char** prefNames;

    // Set a callback for policy pref changes
    prefBranchInternal->AddObserver(sPolicyPrefix, this, PR_FALSE);

    //-- Initialize the principals database from prefs
    rv = mPrefBranch->GetChildList(sPrincipalPrefix, &prefCount, &prefNames);
    if (NS_SUCCEEDED(rv) && prefCount > 0)
    {
        rv = InitPrincipals(prefCount, (const char**)prefNames, mSecurityPref);
        NS_ENSURE_SUCCESS(rv, rv);
        NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(prefCount, prefNames);
    }
    //-- Set a callback for principal changes
    prefBranchInternal->AddObserver(sPrincipalPrefix, this, PR_FALSE);

    return NS_OK;
}

Here is the call graph for this function:

Here is the caller graph for this function:

nsresult nsScriptSecurityManager::InitPrincipals ( PRUint32  prefCount,
const char **  prefNames,
nsISecurityPref securityPref 
) [private]

Definition at line 3568 of file nsScriptSecurityManager.cpp.

{
    /* This is the principal preference syntax:
     * capability.principal.[codebase|codebaseTrusted|certificate].<name>.[id|granted|denied]
     * For example:
     * user_pref("capability.principal.certificate.p1.id","12:34:AB:CD");
     * user_pref("capability.principal.certificate.p1.granted","Capability1 Capability2");
     * user_pref("capability.principal.certificate.p1.denied","Capability3");
     */

    /* codebaseTrusted means a codebase principal that can enable capabilities even if
     * codebase principals are disabled. Don't use trustedCodebase except with unspoofable
     * URLs such as HTTPS URLs.
     */

    static const char idSuffix[] = ".id";
    for (PRUint32 c = 0; c < aPrefCount; c++)
    {
        PRInt32 prefNameLen = PL_strlen(aPrefNames[c]) - 
            (NS_ARRAY_LENGTH(idSuffix) - 1);
        if (PL_strcasecmp(aPrefNames[c] + prefNameLen, idSuffix) != 0)
            continue;

        nsXPIDLCString id;
        if (NS_FAILED(mSecurityPref->SecurityGetCharPref(aPrefNames[c], getter_Copies(id))))
            return NS_ERROR_FAILURE;

        nsCAutoString grantedPrefName;
        nsCAutoString deniedPrefName;
        nsCAutoString subjectNamePrefName;
        nsresult rv = GetPrincipalPrefNames(aPrefNames[c],
                                            grantedPrefName,
                                            deniedPrefName,
                                            subjectNamePrefName);
        if (rv == NS_ERROR_OUT_OF_MEMORY)
            return rv;
        if (NS_FAILED(rv))
            continue;

        nsXPIDLCString grantedList;
        mSecurityPref->SecurityGetCharPref(grantedPrefName.get(),
                                           getter_Copies(grantedList));
        nsXPIDLCString deniedList;
        mSecurityPref->SecurityGetCharPref(deniedPrefName.get(),
                                           getter_Copies(deniedList));
        nsXPIDLCString subjectName;
        mSecurityPref->SecurityGetCharPref(subjectNamePrefName.get(),
                                           getter_Copies(subjectName));

        //-- Delete prefs if their value is the empty string
        if (id.IsEmpty() || (grantedList.IsEmpty() && deniedList.IsEmpty()))
        {
            mSecurityPref->SecurityClearUserPref(aPrefNames[c]);
            mSecurityPref->SecurityClearUserPref(grantedPrefName.get());
            mSecurityPref->SecurityClearUserPref(deniedPrefName.get());
            mSecurityPref->SecurityClearUserPref(subjectNamePrefName.get());
            continue;
        }

        //-- Create a principal based on the prefs
        static const char certificateName[] = "capability.principal.certificate";
        static const char codebaseName[] = "capability.principal.codebase";
        static const char codebaseTrustedName[] = "capability.principal.codebaseTrusted";

        PRBool isCert = PR_FALSE;
        PRBool isTrusted = PR_FALSE;
        
        if (PL_strncmp(aPrefNames[c], certificateName,
                       sizeof(certificateName) - 1) == 0)
        {
            isCert = PR_TRUE;
        }
        else if (PL_strncmp(aPrefNames[c], codebaseName,
                            sizeof(codebaseName) - 1) == 0)
        {
            isTrusted = (PL_strncmp(aPrefNames[c], codebaseTrustedName,
                                    sizeof(codebaseTrustedName) - 1) == 0);
        }
        else
        {
          NS_ERROR("Not a codebase or a certificate?!");
        }

        nsRefPtr<nsPrincipal> newPrincipal = new nsPrincipal();
        if (!newPrincipal)
            return NS_ERROR_OUT_OF_MEMORY;

        rv = newPrincipal->InitFromPersistent(aPrefNames[c], id, subjectName,
                                              EmptyCString(),
                                              grantedList, deniedList, nsnull, 
                                              isCert, isTrusted);
        if (NS_SUCCEEDED(rv))
            mPrincipals.Put(newPrincipal, newPrincipal);
    }
    return NS_OK;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Return true if the currently executing script has 'capability' enabled.

void nsScriptSecurityManager::JSEnabledPrefChanged ( nsISecurityPref aSecurityPref) [inline, private]

Definition at line 3676 of file nsScriptSecurityManager.cpp.

{
    PRBool temp;
    nsresult rv = mSecurityPref->SecurityGetBoolPref(sJSEnabledPrefName, &temp);
    // JavaScript defaults to enabled in failure cases.
    mIsJavaScriptEnabled = NS_FAILED(rv) || temp;

    rv = mSecurityPref->SecurityGetBoolPref(sJSMailEnabledPrefName, &temp);
    // JavaScript in Mail defaults to enabled in failure cases.
    mIsMailJavaScriptEnabled = NS_FAILED(rv) || temp;

#ifdef XPC_IDISPATCH_SUPPORT
    rv = mSecurityPref->SecurityGetBoolPref(sXPCDefaultGrantAllName, &temp);
    // Granting XPC Priveleges defaults to disabled in failure cases.
    mXPCDefaultGrantAll = NS_SUCCEEDED(rv) && temp;
#endif
}

Here is the caller graph for this function:

nsresult nsScriptSecurityManager::LookupPolicy ( nsIPrincipal principal,
const char *  aClassName,
jsval  aProperty,
PRUint32  aAction,
ClassPolicy **  aCachedClassPolicy,
SecurityLevel result 
) [private]

Definition at line 1022 of file nsScriptSecurityManager.cpp.

{
    nsresult rv;
    result->level = SCRIPT_SECURITY_UNDEFINED_ACCESS;

    DomainPolicy* dpolicy = nsnull;
    //-- Initialize policies if necessary
    if (mPolicyPrefsChanged)
    {
        rv = InitPolicies();
        if (NS_FAILED(rv))
            return rv;
    }
    else
    {
        aPrincipal->GetSecurityPolicy((void**)&dpolicy);
    }

    if (!dpolicy && mOriginToPolicyMap)
    {
        //-- Look up the relevant domain policy, if any
#ifdef DEBUG_CAPS_LookupPolicy
        printf("DomainLookup ");
#endif

        nsCAutoString origin;
        rv = GetPrincipalDomainOrigin(aPrincipal, origin);
        NS_ENSURE_SUCCESS(rv, rv);
 
        char *start = origin.BeginWriting();
        const char *nextToLastDot = nsnull;
        const char *lastDot = nsnull;
        const char *colon = nsnull;
        char *p = start;

        //-- search domain (stop at the end of the string or at the 3rd slash)
        for (PRUint32 slashes=0; *p; p++)
        {
            if (*p == '/' && ++slashes == 3) 
            {
                *p = '\0'; // truncate at 3rd slash
                break;
            }
            if (*p == '.')
            {
                nextToLastDot = lastDot;
                lastDot = p;
            } 
            else if (!colon && *p == ':')
                colon = p;
        }

        nsCStringKey key(nextToLastDot ? nextToLastDot+1 : start);
        DomainEntry *de = (DomainEntry*) mOriginToPolicyMap->Get(&key);
        if (!de)
        {
            nsCAutoString scheme(start, colon-start+1);
            nsCStringKey schemeKey(scheme);
            de = (DomainEntry*) mOriginToPolicyMap->Get(&schemeKey);
        }

        while (de)
        {
            if (de->Matches(start))
            {
                dpolicy = de->mDomainPolicy;
                break;
            }
            de = de->mNext;
        }

        if (!dpolicy)
            dpolicy = mDefaultPolicy;

        aPrincipal->SetSecurityPolicy((void*)dpolicy);
    }

    ClassPolicy* cpolicy = nsnull;

    if ((dpolicy == mDefaultPolicy) && aCachedClassPolicy)
    {
        // No per-domain policy for this principal (the more common case)
        // so look for a cached class policy from the object wrapper
        cpolicy = *aCachedClassPolicy;
    }

    if (!cpolicy)
    { //-- No cached policy for this class, need to look it up
#ifdef DEBUG_CAPS_LookupPolicy
        printf("ClassLookup ");
#endif

        cpolicy = NS_STATIC_CAST(ClassPolicy*,
                                 PL_DHashTableOperate(dpolicy,
                                                      aClassName,
                                                      PL_DHASH_LOOKUP));

        if (PL_DHASH_ENTRY_IS_FREE(cpolicy))
            cpolicy = NO_POLICY_FOR_CLASS;

        if ((dpolicy == mDefaultPolicy) && aCachedClassPolicy)
            *aCachedClassPolicy = cpolicy;
    }

    // We look for a PropertyPolicy in the following places:
    // 1)  The ClassPolicy for our class we got from our DomainPolicy
    // 2)  The mWildcardPolicy of our DomainPolicy
    // 3)  The ClassPolicy for our class we got from mDefaultPolicy
    // 4)  The mWildcardPolicy of our mDefaultPolicy
    PropertyPolicy* ppolicy = nsnull;
    if (cpolicy != NO_POLICY_FOR_CLASS)
    {
        ppolicy = NS_STATIC_CAST(PropertyPolicy*,
                                 PL_DHashTableOperate(cpolicy->mPolicy,
                                                      (void*)aProperty,
                                                      PL_DHASH_LOOKUP));
    }

    // If there is no class policy for this property, and we have a wildcard
    // policy, try that.
    if (dpolicy->mWildcardPolicy &&
        (!ppolicy || PL_DHASH_ENTRY_IS_FREE(ppolicy)))
    {
        ppolicy =
            NS_STATIC_CAST(PropertyPolicy*,
                           PL_DHashTableOperate(dpolicy->mWildcardPolicy->mPolicy,
                                                (void*)aProperty,
                                                PL_DHASH_LOOKUP));
    }

    // If dpolicy is not the defauly policy and there's no class or wildcard
    // policy for this property, check the default policy for this class and
    // the default wildcard policy
    if (dpolicy != mDefaultPolicy &&
        (!ppolicy || PL_DHASH_ENTRY_IS_FREE(ppolicy)))
    {
        cpolicy = NS_STATIC_CAST(ClassPolicy*,
                                 PL_DHashTableOperate(mDefaultPolicy,
                                                      aClassName,
                                                      PL_DHASH_LOOKUP));

        if (PL_DHASH_ENTRY_IS_BUSY(cpolicy))
        {
            ppolicy =
                NS_STATIC_CAST(PropertyPolicy*,
                               PL_DHashTableOperate(cpolicy->mPolicy,
                                                    (void*)aProperty,
                                                    PL_DHASH_LOOKUP));
        }

        if ((!ppolicy || PL_DHASH_ENTRY_IS_FREE(ppolicy)) &&
            mDefaultPolicy->mWildcardPolicy)
        {
            ppolicy =
              NS_STATIC_CAST(PropertyPolicy*,
                             PL_DHashTableOperate(mDefaultPolicy->mWildcardPolicy->mPolicy,
                                                  (void*)aProperty,
                                                  PL_DHASH_LOOKUP));
        }
    }

    if (!ppolicy || PL_DHASH_ENTRY_IS_FREE(ppolicy))
        return NS_OK;

    // Get the correct security level from the property policy
    if (aAction == nsIXPCSecurityManager::ACCESS_SET_PROPERTY)
        *result = ppolicy->mSet;
    else
        *result = ppolicy->mGet;

    return NS_OK;
}

Here is the call graph for this function:

Here is the caller graph for this function:

void nsIObserver::observe ( in nsISupports  aSubject,
in string  aTopic,
in wstring  aData 
) [inherited]

Observe will be called when there is a notification for the topic |aTopic|.

This assumes that the object implementing this interface has been registered with an observer service such as the nsIObserverService.

If you expect multiple topics/subjects, the impl is responsible for filtering.

You should not modify, add, remove, or enumerate notifications in the implemention of observe.

Parameters:
aSubject: Notification specific interface pointer.
aTopic: The notification topic or subject.
aData: Notification specific wide string. subject event.
nsresult nsScriptSecurityManager::ReportError ( JSContext cx,
const nsAString &  messageTag,
nsIURI aSource,
nsIURI aTarget 
) [static, private]

Definition at line 1516 of file nsScriptSecurityManager.cpp.

{
    nsresult rv;
    NS_ENSURE_TRUE(aSource && aTarget, NS_ERROR_NULL_POINTER);

    // Get the source URL spec
    nsCAutoString sourceSpec;
    rv = aSource->GetAsciiSpec(sourceSpec);
    NS_ENSURE_SUCCESS(rv, rv);

    // Get the target URL spec
    nsCAutoString targetSpec;
    rv = aTarget->GetAsciiSpec(targetSpec);
    NS_ENSURE_SUCCESS(rv, rv);

    // Localize the error message
    nsXPIDLString message;
    NS_ConvertASCIItoUCS2 ucsSourceSpec(sourceSpec);
    NS_ConvertASCIItoUCS2 ucsTargetSpec(targetSpec);
    const PRUnichar *formatStrings[] = { ucsSourceSpec.get(), ucsTargetSpec.get() };
    rv = sStrBundle->FormatStringFromName(PromiseFlatString(messageTag).get(),
                                          formatStrings,
                                          NS_ARRAY_LENGTH(formatStrings),
                                          getter_Copies(message));
    NS_ENSURE_SUCCESS(rv, rv);

    // If a JS context was passed in, set a JS exception.
    // Otherwise, print the error message directly to the JS console
    // and to standard output
    if (cx)
    {
        SetPendingException(cx, message.get());
        // Tell XPConnect that an exception was thrown, if appropriate
        if (sXPConnect)
        {
            nsCOMPtr<nsIXPCNativeCallContext> xpcCallContext;
            sXPConnect->GetCurrentNativeCallContext(getter_AddRefs(xpcCallContext));
             if (xpcCallContext)
                xpcCallContext->SetExceptionWasThrown(PR_TRUE);
        }
    }
    else // Print directly to the console
    {
        nsCOMPtr<nsIConsoleService> console(
            do_GetService("@mozilla.org/consoleservice;1"));
        NS_ENSURE_TRUE(console, NS_ERROR_FAILURE);

        console->LogStringMessage(message.get());
#ifdef DEBUG
        fprintf(stderr, "%s\n", NS_LossyConvertUCS2toASCII(message).get());
#endif
    }
    return NS_OK;
}

Here is the call graph for this function:

short nsIScriptSecurityManager::requestCapability ( in nsIPrincipal  principal,
in string  capability 
) [inherited]

Request that 'capability' can be enabled by scripts or applets running with 'principal'.

Will prompt user if necessary. Returns nsIPrincipal::ENABLE_GRANTED or nsIPrincipal::ENABLE_DENIED based on user's choice.

Remove 'capability' from the innermost frame of the currently executing script.

Any setting of 'capability' from enclosing frames thus comes into effect.

Definition at line 2296 of file nsScriptSecurityManager.cpp.

{
    //-- Save to mPrincipals
    mPrincipals.Put(aToSave, aToSave);

    //-- Save to prefs
    nsXPIDLCString idPrefName;
    nsXPIDLCString id;
    nsXPIDLCString subjectName;
    nsXPIDLCString grantedList;
    nsXPIDLCString deniedList;
    nsresult rv = aToSave->GetPreferences(getter_Copies(idPrefName),
                                          getter_Copies(id),
                                          getter_Copies(subjectName),
                                          getter_Copies(grantedList),
                                          getter_Copies(deniedList));
    if (NS_FAILED(rv)) return NS_ERROR_FAILURE;

    nsCAutoString grantedPrefName;
    nsCAutoString deniedPrefName;
    nsCAutoString subjectNamePrefName;
    rv = GetPrincipalPrefNames( idPrefName,
                                grantedPrefName,
                                deniedPrefName,
                                subjectNamePrefName );
    if (NS_FAILED(rv)) return NS_ERROR_FAILURE;

    mIsWritingPrefs = PR_TRUE;
    if (grantedList)
        mSecurityPref->SecuritySetCharPref(grantedPrefName.get(), grantedList);
    else
        mSecurityPref->SecurityClearUserPref(grantedPrefName.get());

    if (deniedList)
        mSecurityPref->SecuritySetCharPref(deniedPrefName.get(), deniedList);
    else
        mSecurityPref->SecurityClearUserPref(deniedPrefName.get());

    if (grantedList || deniedList) {
        mSecurityPref->SecuritySetCharPref(idPrefName, id);
        mSecurityPref->SecuritySetCharPref(subjectNamePrefName.get(),
                                           subjectName);
    }
    else {
        mSecurityPref->SecurityClearUserPref(idPrefName);
        mSecurityPref->SecurityClearUserPref(subjectNamePrefName.get());
    }

    mIsWritingPrefs = PR_FALSE;

    nsCOMPtr<nsIPrefService> prefService(do_GetService(NS_PREFSERVICE_CONTRACTID, &rv));
    NS_ENSURE_SUCCESS(rv, rv);
    return prefService->SavePrefFile(nsnull);
}

Here is the call graph for this function:

boolean nsIScriptSecurityManager::securityCompareURIs ( in nsIURI  aSubjectURI,
in nsIURI  aObjectURI 
) [inherited]

Utility method for comparing two URIs.

For security purposes, two URIs are equivalent if their schemes, hosts, and ports (if any) match. This method returns true if aSubjectURI and aObjectURI have the same origin, false otherwise.

PRBool nsScriptSecurityManager::SecurityCompareURIs ( nsIURI aSourceURI,
nsIURI aTargetURI 
) [static]

Utility method for comparing two URIs.

For security purposes, two URIs are equivalent if their schemes, hosts, and ports (if any) match. This method returns true if aSubjectURI and aObjectURI have the same origin, false otherwise.

Definition at line 264 of file nsScriptSecurityManager.cpp.

{
    *result = SecurityCompareURIs(aSourceURI, aTargetURI);

    return NS_OK;
}
void nsIScriptSecurityManager::setCanEnableCapability ( in AUTF8String  certificateFingerprint,
in string  capability,
in short  canEnable 
) [inherited]

Allow 'certificateID' to enable 'capability.

' Can only be performed by code signed by the system certificate.

Definition at line 3157 of file nsScriptSecurityManager.cpp.

{
    if (sRuntime) {
#ifdef DEBUG
        JSCheckAccessOp oldCallback =
#endif
            JS_SetCheckObjectAccessCallback(sRuntime, nsnull);
        NS_ASSERTION(oldCallback == CheckObjectAccess, "Oops, we just clobbered someone else, oh well.");
        sRuntime = nsnull;
    }
    sEnabledID = JSVAL_VOID;

    NS_IF_RELEASE(sIOService);
    NS_IF_RELEASE(sXPConnect);
    NS_IF_RELEASE(sStrBundle);
}

Here is the call graph for this function:

Here is the caller graph for this function:

Returns true if the principal of the currently running script is the system principal, false otherwise.

Definition at line 3214 of file nsScriptSecurityManager.cpp.

{
    nsIPrincipal *sysprin = nsnull;
    if (gScriptSecMan)
        gScriptSecMan->GetSystemPrincipal(&sysprin);
    return NS_STATIC_CAST(nsSystemPrincipal*, sysprin);
}

Member Data Documentation

Definition at line 98 of file nsIXPCSecurityManager.idl.

Definition at line 99 of file nsIXPCSecurityManager.idl.

Definition at line 100 of file nsIXPCSecurityManager.idl.

const unsigned long nsIScriptSecurityManager::ALLOW_CHROME = 1 << 1 [inherited]

Definition at line 86 of file nsIScriptSecurityManager.idl.

Definition at line 83 of file nsIScriptSecurityManager.idl.

const unsigned long nsIScriptSecurityManager::DISALLOW_SCRIPT = 1 << 3 [inherited]

Definition at line 94 of file nsIScriptSecurityManager.idl.

Definition at line 89 of file nsIScriptSecurityManager.idl.

Definition at line 64 of file nsIXPCSecurityManager.idl.

Definition at line 62 of file nsIXPCSecurityManager.idl.

These flags are used when calling nsIXPConnect::SetSecurityManager.

Definition at line 61 of file nsIXPCSecurityManager.idl.

Definition at line 65 of file nsIXPCSecurityManager.idl.

Definition at line 63 of file nsIXPCSecurityManager.idl.

Definition at line 66 of file nsIXPCSecurityManager.idl.

nsObjectHashtable* nsScriptSecurityManager::mCapabilities [private]

Definition at line 576 of file nsScriptSecurityManager.h.

Definition at line 575 of file nsScriptSecurityManager.h.

Definition at line 584 of file nsScriptSecurityManager.h.

Definition at line 585 of file nsScriptSecurityManager.h.

Definition at line 586 of file nsScriptSecurityManager.h.

Definition at line 583 of file nsScriptSecurityManager.h.

nsObjectHashtable* nsScriptSecurityManager::mOriginToPolicyMap [private]

Definition at line 574 of file nsScriptSecurityManager.h.

Definition at line 587 of file nsScriptSecurityManager.h.

Definition at line 578 of file nsScriptSecurityManager.h.

Definition at line 582 of file nsScriptSecurityManager.h.

Definition at line 579 of file nsScriptSecurityManager.h.

Definition at line 581 of file nsScriptSecurityManager.h.

Definition at line 580 of file nsScriptSecurityManager.h.

Definition at line 566 of file nsScriptSecurityManager.h.

Definition at line 593 of file nsScriptSecurityManager.h.

const char nsScriptSecurityManager::sJSEnabledPrefName = "javascript.enabled" [static, private]

Definition at line 571 of file nsScriptSecurityManager.h.

const char nsScriptSecurityManager::sJSMailEnabledPrefName = "javascript.allow.mailnews" [static, private]

Definition at line 572 of file nsScriptSecurityManager.h.

Definition at line 596 of file nsScriptSecurityManager.h.

Definition at line 595 of file nsScriptSecurityManager.h.

const unsigned long nsIScriptSecurityManager::STANDARD = 0 [inherited]

Default CheckLoadURI permissions.

Definition at line 80 of file nsIScriptSecurityManager.idl.

Definition at line 594 of file nsScriptSecurityManager.h.


The documentation for this class was generated from the following files: