在内容脚本之前注入javascript变量

时间:2017-07-14 12:02:08

标签: javascript google-chrome-extension

使用我的后台脚本background.js,我需要在将另一个文件inject.js作为内容脚本注入之前将动态变量注入内容脚本。 Inject.js需要访问此变量并在页面上的任何脚本运行之前运行它的代码。我无法从inject.js内容脚本访问动态变量。

的manifest.json

{
"name": "Shape Shifter",
"version": "1.0",
"description": "Anti browser fingerprinting web extension. Generates randomised values for HTTP request headers, javascript property values and javascript method return types.",
"manifest_version": 2,
"icons": {
    "32": "icons/person-32.png",
    "48": "icons/person-48.png"
},
"background": {
    "persistent": true,
    "scripts": ["js/ua.js", "js/words.js", "js/lib/seedrandom.min.js", "js/random.js", "js/background.js"]
},
"browser_action": {
    "default_title": "Shape Shifter",
    "default_icon": "icons/person-32.png",
    "default_popup": "html/popup.html"
},
"content_scripts": [
  {
    "run_at": "document_end",
    "matches": ["<all_urls>"],
    "js": ["js/inject.js"] 
  }
],
"permissions": [
    "webRequest",
    "webRequestBlocking",
    "webNavigation",
    "tabs",
    "activeTab",
    "storage",
    "<all_urls>"
],
"web_accessible_resources": [
    "js/ua.js",
    "js/words.js",
    "js/lib/seedrandom.min.js",
    "js/random.js",
    "js/api/document.js",
    "js/api/navigator.js",
    "js/api/canvas.js",
    "js/api/history.js",
    "js/api/battery.js",
    "js/api/audio.js",
    "js/api/element.js"
]

}

background.js

"use strict";

console.log("Background Script Running ...");

function getSeed(origin) {
    // Get a Storage object
    var storage = window.localStorage;

    // Do we already have a seed in storage for this origin or not?
    var seed = storage.getItem(origin);

    if (seed === null) {
        // Initialise a 32 byte buffer
        seed = new Uint8Array(32);

        // Fill it with cryptographically random values
        window.crypto.getRandomValues(seed);

        // Save it to storage
        storage.setItem(origin, seed);
    }

    return seed;
}

// Methods to get HTTP headers
function getAcceptHeader(seed) {
    return "NotYetImplemented";
}
function getAcceptCharsetHeader(seed) {
    return "NotYetImplemented";
}
function getAcceptEncodingHeader(seed) {
    return "NotYetImplemented";
}
function getAcceptLanguageHeader() {
    // NOTE: TOR Browser uses American English
    return "en-US,en;q=0.5";
}
function getAuthorizationHeader(seed) {
    return "NotYetImplemented";
}
function getExpectHeader(seed) {
    return "NotYetImplemented";
}
function getFromHeader(seed) {
    return "NotYetImplemented";
}
function getHostHeader(seed) {
    return "NotYetImplemented";
}
function getIfMatchHeader(seed) {
    return "NotYetImplemented";
}
function getIfModifiedSinceHeader(seed) {
    return "NotYetImplemented";
}
function getIfNoneMatchHeader(seed) {
    return "NotYetImplemented";
}
function getIfRangeHeader(seed) {
    return "NotYetImplemented";
}
function getIfUnmodifiedSinceHeader(seed) {
    return "NotYetImplemented";
}
function getMaxForwardsHeader(seed) {
    return "NotYetImplemented";
}
function getProxyAuthorizationHeader(seed) {
    return "NotYetImplemented";
}
function getRangeHeader(seed) {
    return "NotYetImplemented";
}
function getRefererHeader() {
    // NOTE: From https://developer.mozilla.org/en-US/docs/Web/API/Document/referrer
    // NOTE: The value is an empty string if the user navigated to the page directly (not through a link, but, for example, via a bookmark).
    // NOTE: Since this property returns only a string, it does not give you DOM access to the referring page.

    // NOTE: Make websites think we always go to them directly rather than being referred.
    return "";
}
function getTEHeader(seed) {
    return "NotYetImplemented";
}
function getUserAgentHeader(seed) {
    Math.seedrandom(seed);

    return userAgents[randomNumber(0, userAgents.length)];
}

function rewriteHttpHeaders(e) {
    // Create URL object from url string
    var serverUrl = new URL(e.url);

    console.log(e);

    // Get the origin (hostname)
    var origin = serverUrl.hostname;

    var seed = getSeed(origin);

    console.log("Background - Seed for origin " + origin + ": " + seed);

    for (var header of e.requestHeaders) {
        if (header.name.toLowerCase() === "accept") {
        }
        else if (header.name.toLowerCase() === "accept-charset") {
        }
        else if (header.name.toLowerCase() === "accept-encoding") {
        }
        else if (header.name.toLowerCase() === "accept-language") {
            header.value = getAcceptLanguageHeader();
        }
        else if (header.name.toLowerCase() === "authorization") {
        }
        else if (header.name.toLowerCase() === "expect") {
        }
        else if (header.name.toLowerCase() === "from") {
        }
        else if (header.name.toLowerCase() === "host") {
        }
        else if (header.name.toLowerCase() === "if-match") {
        }
        else if (header.name.toLowerCase() === "if-modified-since") {
        }
        else if (header.name.toLowerCase() === "if-none-match") {
        }
        else if (header.name.toLowerCase() === "if-range") {
        }
        else if (header.name.toLowerCase() === "if-unmodified-since") {
        }
        else if (header.name.toLowerCase() === "max-forwards") {
        }
        else if (header.name.toLowerCase() === "proxy-authorization") {
        }
        else if (header.name.toLowerCase() === "range") {
        }
        else if (header.name.toLowerCase() === "referer") {
            header.value = getRefererHeader();
        }
        else if (header.name.toLowerCase() === "te") {
        }
        else if (header.name.toLowerCase() === "user-agent") {
            header.value = getUserAgentHeader(seed);
        }
    }

    return {requestHeaders: e.requestHeaders};
}

chrome.webRequest.onBeforeSendHeaders.addListener(rewriteHttpHeaders, {urls: ["<all_urls>"]}, ["blocking", "requestHeaders"]);

chrome.webNavigation.onBeforeNavigate.addListener(function(details) {
    // Create URL object from url string
    var serverUrl = new URL(details.url);

    // Get the origin (hostname)
    var origin = serverUrl.hostname;

    var seed = "Some dynamic value";

    console.log("Injecting Value");
    chrome.tabs.executeScript(details.tabId, {code: "var seed = '" + seed + "';console.log(seed);", runAt: "document_start"}, function() {
        console.log("Value Injected");
    });
});

inject.js

(function() {
  function inject(filePath) {
    var script = document.createElement('script');
    script.src = chrome.extension.getURL(filePath);
    script.onload = function() {
      this.remove();
    };
    (document.head || document.documentElement).appendChild(script);
  }

  function injectText(text) {
    var script = document.createElement('script');
    script.textContent = text;
    script.onload = function() {
      this.remove();
    };
    (document.head || document.documentElement).appendChild(script);
  }

  console.log("CONTENT SCRIPT RUNNING");

  console.log(seed); // SEED IS NOT DEFINED HERE ???

  injectText("var seed = 'hello';");
  console.log("[INFO] Injected Seed ...");
  inject("js/ua.js");
  console.log("[INFO] Injected UA ...");
  inject("js/words.js");
  console.log("[INFO] Injected Words ...");
  inject("js/lib/seedrandom.min.js");
  console.log("[INFO] Injected Seed Random ...");
  inject("js/random.js");
  console.log("[INFO] Injected Random ...");
  inject("js/api/document.js");
  console.log("[INFO] Injected Document API ...");
  inject("js/api/navigator.js");
  console.log("[INFO] Injected Navigator API ...");
  inject("js/api/canvas.js");
  console.log("[INFO] Injected Canvas API ...");
  inject("js/api/history.js");
  console.log("[INFO] Injected History API ...");
  inject("js/api/battery.js");
  console.log("[INFO] Injected Battery API ...");
  inject("js/api/audio.js");
  console.log("[INFO] Injected Audio API ...");
  inject("js/api/element.js");
  console.log("[INFO] Injected Element API ...");
})();

尝试将种子记录到控制台时出现错误:

inject.js:26 Uncaught ReferenceError: seed is not defined
    at inject.js:26
    at inject.js:52

有什么想法吗?

1 个答案:

答案 0 :(得分:5)

这将非常棘手。

让我们来看看你的要求。

  

Inject.js需要访问此变量并在页面上的任何脚本运行之前运行它的代码。

这不是您的代码目前的工作方式。您的inject.jsdocument_end处执行 - 在解析完整个DOM树之后发生,这意味着所有页面脚本都已运行(禁止异步)部分和async脚本加载)。

Chrome有一个解决方案 - 您可以将执行设置为document_start。然后你的代码将在其他所有之前真正运行,而DOM仍未被解析(因此document基本上是空的)。使用您的代码所做的事情,它不应该产生问题(它只依赖于document.documentElement,这将存在)。

问题是,您的所有代码必须同步仍然享有“先运行其他”属性。只要代码的同步部分运行,Chrome就会暂停DOM解析,但随后所有的赌注都会关闭,因为它会继续解析(并运行代码)文档。

例如,这会取消chrome.storage和Messaging的资格,因为对它的访问必然是异步的。

  

我需要在[页面加载]上注入一个动态变量

这意味着您无法事先将其存储在某些同步可用的存储中(例如,在localStorage或网站的Cookie中),如果您事先不知道域名,则会出现问题。

注意,特别是对于您的代码,这可能不是那么多因素;您的“动态”值实际上是每个域固定的。您仍然不知道将访问哪个域,但您至少可以保证在第二次加载时它将在那里。

  

使用我的后台脚本background.js,我需要在注入另一个文件之前将动态变量注入内容脚本 [仍然需要在页面上的其他所有内容之前运行]

那是棘手的部分。 事实上,如上所述,它根本不可能。您正试图从后台捕获提交导航之间的确切时刻,以便Chrome将页面切换到新域,并且执行document_start脚本。

那里没有可检测到的差距,也无法告诉Chrome等待。这是一个你无法解决的竞争条件。

您尝试使用webNavigation.onBeforeNavigate - 甚至在提交导航之前。所以你的injectScript可能甚至会转到上一页,使它变得毫无用处。如果你尝试其他一些事件,例如。 onCommitted,仍然无法确切知道何时会对injectScript进行处理。 之后可能

那么,如何解决这一切?

幸运的是,有一些同步存储可供内容脚本使用,您可以在最早的脚本执行之前将某些信息推送到

<强>缓存数据。

但是,使用chrome.cookies API无济于事。您需要在webRequest.onHeadersReceived上的请求中主动注入cookie值。

您必须准备好值同步以使用onHeadersReceived的阻止处理程序来处理它,但是您只需添加一个Set-Cookie标头并立即使用它在document.cookies中的inject.js

// background.js
function addSeedCookie(details) {
  seed = SomethingSynchronous();
  details.responseHeaders.push({
    name: "Set-Cookie",
    value: `seed_goes_here=${seed};`
  });
  return {
    responseHeaders: details.responseHeaders
  };
}

chrome.webRequest.onHeadersReceived.addListener(
  addSeedCookie, {urls: ["<all_urls>"]}, ["blocking", "responseHeaders"]
);

// inject.js
function getCookie(cookie) { // https://stackoverflow.com/a/19971550/934239
  return document.cookie.split(';').reduce(function(prev, c) {
    var arr = c.split('=');
    return (arr[0].trim() === cookie) ? arr[1] : prev;
  }, undefined);
}

var seed = getCookie("seed_goes_here");

注意:上面的代码未经测试,仅用于说明这个想法。