Example #1
0
void WorkerDebuggerGlobalScope::ReportError(JSContext* aCx,
                                            const nsAString& aMessage) {
  JS::AutoFilename chars;
  uint32_t lineno = 0;
  JS::DescribeScriptedCaller(aCx, &chars, &lineno);
  nsString filename(NS_ConvertUTF8toUTF16(chars.get()));
  mWorkerPrivate->ReportErrorToDebugger(filename, lineno, aMessage);
}
Example #2
0
static bool
GetFilenameAndLineNumber(JSContext *cx, nsACString &filename, unsigned &lineno)
{
    JS::AutoFilename scriptFilename;
    if (JS::DescribeScriptedCaller(cx, &scriptFilename, &lineno)) {
        if (const char *cfilename = scriptFilename.get()) {
            filename.Assign(nsDependentCString(cfilename));
            return true;
        }
    }
    return false;
}
Example #3
0
bool
nsJSUtils::GetCallingLocation(JSContext* aContext, nsAString& aFilename,
                              uint32_t* aLineno, uint32_t* aColumn)
{
  JS::AutoFilename filename;
  if (!JS::DescribeScriptedCaller(aContext, &filename, aLineno, aColumn)) {
    return false;
  }

  aFilename.Assign(NS_ConvertUTF8toUTF16(filename.get()));
  return true;
}
Example #4
0
bool
nsJSUtils::GetCallingLocation(JSContext* aContext, nsACString& aFilename,
                              uint32_t* aLineno)
{
  JS::AutoFilename filename;
  if (!JS::DescribeScriptedCaller(aContext, &filename, aLineno)) {
    return false;
  }

  aFilename.Assign(filename.get());
  return true;
}
Example #5
0
bool
nsJSUtils::GetCallingLocation(JSContext* aContext, const char* *aFilename,
                              uint32_t* aLineno)
{
  JS::AutoFilename filename;
  unsigned lineno = 0;

  if (!JS::DescribeScriptedCaller(aContext, &filename, &lineno)) {
    return false;
  }

  *aFilename = filename.get();
  *aLineno = lineno;

  return true;
}
bool
nsScriptSecurityManager::ContentSecurityPolicyPermitsJSAction(JSContext *cx)
{
    MOZ_ASSERT(cx == nsContentUtils::GetCurrentJSContext());
    nsCOMPtr<nsIPrincipal> subjectPrincipal = nsContentUtils::SubjectPrincipal();
    nsCOMPtr<nsIContentSecurityPolicy> csp;
    nsresult 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::AutoFilename scriptFilename;
        if (JS::DescribeScriptedCaller(cx, &scriptFilename, &lineNum)) {
            if (const char *file = scriptFilename.get()) {
                CopyUTF8toUTF16(nsDependentCString(file), fileName);
            }
        }
        csp->LogViolationDetails(nsIContentSecurityPolicy::VIOLATION_TYPE_EVAL,
                                 fileName,
                                 scriptSample,
                                 lineNum,
                                 EmptyString(),
                                 EmptyString());
    }

    return evalOK;
}
Example #7
0
bool IsImageExtractionAllowed(nsIDocument *aDocument, JSContext *aCx)
{
    // Do the rest of the checks only if privacy.resistFingerprinting is on.
    if (!nsContentUtils::ShouldResistFingerprinting()) {
        return true;
    }

    // Don't proceed if we don't have a document or JavaScript context.
    if (!aDocument || !aCx) {
        return false;
    }

    // Documents with system principal can always extract canvas data.
    nsPIDOMWindowOuter *win = aDocument->GetWindow();
    nsCOMPtr<nsIScriptObjectPrincipal> sop(do_QueryInterface(win));
    if (sop && nsContentUtils::IsSystemPrincipal(sop->GetPrincipal())) {
        return true;
    }

    // Always give permission to chrome scripts (e.g. Page Inspector).
    if (nsContentUtils::ThreadsafeIsCallerChrome()) {
        return true;
    }

    // Get the document URI and its spec.
    nsIURI *docURI = aDocument->GetDocumentURI();
    nsCString docURISpec;
    docURI->GetSpec(docURISpec);

    // Allow local files to extract canvas data.
    bool isFileURL;
    (void) docURI->SchemeIs("file", &isFileURL);
    if (isFileURL) {
        return true;
    }

    // Get calling script file and line for logging.
    JS::AutoFilename scriptFile;
    unsigned scriptLine = 0;
    bool isScriptKnown = false;
    if (JS::DescribeScriptedCaller(aCx, &scriptFile, &scriptLine)) {
        isScriptKnown = true;
        // Don't show canvas prompt for PDF.js
        if (scriptFile.get() &&
                strcmp(scriptFile.get(), "resource://pdf.js/build/pdf.js") == 0) {
            return true;
        }
    }

    nsIDocument* topLevelDocument = aDocument->GetTopLevelContentDocument();
    nsIURI *topLevelDocURI = topLevelDocument ? topLevelDocument->GetDocumentURI() : nullptr;
    nsCString topLevelDocURISpec;
    if (topLevelDocURI) {
        topLevelDocURI->GetSpec(topLevelDocURISpec);
    }

    // Load Third Party Util service.
    nsresult rv;
    nsCOMPtr<mozIThirdPartyUtil> thirdPartyUtil =
        do_GetService(THIRDPARTYUTIL_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv, false);

    // Block all third-party attempts to extract canvas.
    bool isThirdParty = true;
    rv = thirdPartyUtil->IsThirdPartyURI(topLevelDocURI, docURI, &isThirdParty);
    NS_ENSURE_SUCCESS(rv, false);
    if (isThirdParty) {
        nsAutoCString message;
        message.AppendPrintf("Blocked third party %s in page %s from extracting canvas data.",
                             docURISpec.get(), topLevelDocURISpec.get());
        if (isScriptKnown) {
            message.AppendPrintf(" %s:%u.", scriptFile.get(), scriptLine);
        }
        nsContentUtils::LogMessageToConsole(message.get());
        return false;
    }

    // Load Permission Manager service.
    nsCOMPtr<nsIPermissionManager> permissionManager =
        do_GetService(NS_PERMISSIONMANAGER_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv, false);

    // Check if the site has permission to extract canvas data.
    // Either permit or block extraction if a stored permission setting exists.
    uint32_t permission;
    rv = permissionManager->TestPermission(topLevelDocURI,
                                           PERMISSION_CANVAS_EXTRACT_DATA,
                                           &permission);
    NS_ENSURE_SUCCESS(rv, false);
    switch (permission) {
    case nsIPermissionManager::ALLOW_ACTION:
        return true;
    case nsIPermissionManager::DENY_ACTION:
        return false;
    default:
        break;
    }

    // At this point, permission is unknown (nsIPermissionManager::UNKNOWN_ACTION).
    nsAutoCString message;
    message.AppendPrintf("Blocked %s in page %s from extracting canvas data.",
                         docURISpec.get(), topLevelDocURISpec.get());
    if (isScriptKnown) {
        message.AppendPrintf(" %s:%u.", scriptFile.get(), scriptLine);
    }
    nsContentUtils::LogMessageToConsole(message.get());

    // Prompt the user (asynchronous).
    if (XRE_IsContentProcess()) {
        TabChild* tabChild = TabChild::GetFrom(win);
        if (tabChild) {
            tabChild->SendShowCanvasPermissionPrompt(topLevelDocURISpec);
        }
    } else {
        nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
        if (obs) {
            obs->NotifyObservers(win, TOPIC_CANVAS_PERMISSIONS_PROMPT,
                                 NS_ConvertUTF8toUTF16(topLevelDocURISpec).get());
        }
    }

    // We don't extract the image for now -- user may override at prompt.
    return false;
}
Example #8
0
static bool
GetLocationProperty(JSContext* cx, unsigned argc, Value* vp)
{
    CallArgs args = CallArgsFromVp(argc, vp);
    if (!args.thisv().isObject()) {
        JS_ReportError(cx, "Unexpected this value for GetLocationProperty");
        return false;
    }
#if !defined(XP_WIN) && !defined(XP_UNIX)
    //XXX: your platform should really implement this
    return false;
#else
    JS::AutoFilename filename;
    if (JS::DescribeScriptedCaller(cx, &filename) && filename.get()) {
        nsresult rv;
        nsCOMPtr<nsIXPConnect> xpc =
            do_GetService(kXPConnectServiceContractID, &rv);

#if defined(XP_WIN)
        // convert from the system codepage to UTF-16
        int bufferSize = MultiByteToWideChar(CP_ACP, 0, filename.get(),
                                             -1, nullptr, 0);
        nsAutoString filenameString;
        filenameString.SetLength(bufferSize);
        MultiByteToWideChar(CP_ACP, 0, filename.get(),
                            -1, (LPWSTR)filenameString.BeginWriting(),
                            filenameString.Length());
        // remove the null terminator
        filenameString.SetLength(bufferSize - 1);

        // replace forward slashes with backslashes,
        // since nsLocalFileWin chokes on them
        char16_t* start = filenameString.BeginWriting();
        char16_t* end = filenameString.EndWriting();

        while (start != end) {
            if (*start == L'/')
                *start = L'\\';
            start++;
        }
#elif defined(XP_UNIX)
        NS_ConvertUTF8toUTF16 filenameString(filename.get());
#endif

        nsCOMPtr<nsIFile> location;
        if (NS_SUCCEEDED(rv)) {
            rv = NS_NewLocalFile(filenameString,
                                 false, getter_AddRefs(location));
        }

        if (!location && gWorkingDirectory) {
            // could be a relative path, try appending it to the cwd
            // and then normalize
            nsAutoString absolutePath(*gWorkingDirectory);
            absolutePath.Append(filenameString);

            rv = NS_NewLocalFile(absolutePath,
                                 false, getter_AddRefs(location));
        }

        if (location) {
            nsCOMPtr<nsIXPConnectJSObjectHolder> locationHolder;

            bool symlink;
            // don't normalize symlinks, because that's kind of confusing
            if (NS_SUCCEEDED(location->IsSymlink(&symlink)) &&
                !symlink)
                location->Normalize();
            rv = xpc->WrapNative(cx, &args.thisv().toObject(), location,
                                 NS_GET_IID(nsIFile),
                                 getter_AddRefs(locationHolder));

            if (NS_SUCCEEDED(rv) &&
                locationHolder->GetJSObject()) {
                args.rval().setObject(*locationHolder->GetJSObject());
            }
        }
    }

    return true;
#endif
}
Example #9
0
bool IsImageExtractionAllowed(Document* aDocument, JSContext* aCx,
                              nsIPrincipal& aPrincipal) {
  // Do the rest of the checks only if privacy.resistFingerprinting is on.
  if (!nsContentUtils::ShouldResistFingerprinting(aDocument)) {
    return true;
  }

  // Don't proceed if we don't have a document or JavaScript context.
  if (!aDocument || !aCx) {
    return false;
  }

  // The system principal can always extract canvas data.
  if (nsContentUtils::IsSystemPrincipal(&aPrincipal)) {
    return true;
  }

  // Allow extension principals.
  auto principal = BasePrincipal::Cast(&aPrincipal);
  if (principal->AddonPolicy() || principal->ContentScriptAddonPolicy()) {
    return true;
  }

  // Get the document URI and its spec.
  nsIURI* docURI = aDocument->GetDocumentURI();
  nsCString docURISpec;
  docURI->GetSpec(docURISpec);

  // Allow local files to extract canvas data.
  bool isFileURL;
  if (NS_SUCCEEDED(docURI->SchemeIs("file", &isFileURL)) && isFileURL) {
    return true;
  }

  // Don't show canvas prompt for PDF.js
  JS::AutoFilename scriptFile;
  if (JS::DescribeScriptedCaller(aCx, &scriptFile) && scriptFile.get() &&
      strcmp(scriptFile.get(), "resource://pdf.js/build/pdf.js") == 0) {
    return true;
  }

  Document* topLevelDocument = aDocument->GetTopLevelContentDocument();
  nsIURI* topLevelDocURI =
      topLevelDocument ? topLevelDocument->GetDocumentURI() : nullptr;
  nsCString topLevelDocURISpec;
  if (topLevelDocURI) {
    topLevelDocURI->GetSpec(topLevelDocURISpec);
  }

  // Load Third Party Util service.
  nsresult rv;
  nsCOMPtr<mozIThirdPartyUtil> thirdPartyUtil =
      do_GetService(THIRDPARTYUTIL_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, false);

  // Block all third-party attempts to extract canvas.
  bool isThirdParty = true;
  rv = thirdPartyUtil->IsThirdPartyURI(topLevelDocURI, docURI, &isThirdParty);
  NS_ENSURE_SUCCESS(rv, false);
  if (isThirdParty) {
    nsAutoString message;
    message.AppendPrintf("Blocked third party %s from extracting canvas data.",
                         docURISpec.get());
    nsContentUtils::ReportToConsoleNonLocalized(
        message, nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Security"),
        aDocument);
    return false;
  }

  // Load Permission Manager service.
  nsCOMPtr<nsIPermissionManager> permissionManager =
      do_GetService(NS_PERMISSIONMANAGER_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, false);

  // Check if the site has permission to extract canvas data.
  // Either permit or block extraction if a stored permission setting exists.
  uint32_t permission;
  rv = permissionManager->TestPermissionFromPrincipal(
      principal, PERMISSION_CANVAS_EXTRACT_DATA, &permission);
  NS_ENSURE_SUCCESS(rv, false);
  switch (permission) {
    case nsIPermissionManager::ALLOW_ACTION:
      return true;
    case nsIPermissionManager::DENY_ACTION:
      return false;
    default:
      break;
  }

  // At this point, permission is unknown
  // (nsIPermissionManager::UNKNOWN_ACTION).

  // Check if the request is in response to user input
  bool isAutoBlockCanvas =
      StaticPrefs::
          privacy_resistFingerprinting_autoDeclineNoUserInputCanvasPrompts() &&
      !EventStateManager::IsHandlingUserInput();

  if (isAutoBlockCanvas) {
    nsAutoString message;
    message.AppendPrintf(
        "Blocked %s from extracting canvas data because no user input was "
        "detected.",
        docURISpec.get());
    nsContentUtils::ReportToConsoleNonLocalized(
        message, nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Security"),
        aDocument);
  } else {
    // It was in response to user input, so log and display the prompt.
    nsAutoString message;
    message.AppendPrintf(
        "Blocked %s from extracting canvas data, but prompting the user.",
        docURISpec.get());
    nsContentUtils::ReportToConsoleNonLocalized(
        message, nsIScriptError::warningFlag, NS_LITERAL_CSTRING("Security"),
        aDocument);
  }

  // Prompt the user (asynchronous).
  nsPIDOMWindowOuter* win = aDocument->GetWindow();
  nsAutoCString origin;
  rv = principal->GetOrigin(origin);
  NS_ENSURE_SUCCESS(rv, false);

  if (XRE_IsContentProcess()) {
    BrowserChild* browserChild = BrowserChild::GetFrom(win);
    if (browserChild) {
      browserChild->SendShowCanvasPermissionPrompt(origin,
                                                   isAutoBlockCanvas);
    }
  } else {
    nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
    if (obs) {
      obs->NotifyObservers(win,
                           isAutoBlockCanvas
                               ? TOPIC_CANVAS_PERMISSIONS_PROMPT_HIDE_DOORHANGER
                               : TOPIC_CANVAS_PERMISSIONS_PROMPT,
                           NS_ConvertUTF8toUTF16(origin).get());
    }
  }

  // We don't extract the image for now -- user may override at prompt.
  return false;
}