background_http_request.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. Error.stackTraceLimit = Infinity;
  2. let urlPublicKeysMap = new Map();
  3. // Adapted code from https://stackoverflow.com/questions/36598638/generating-ecdh-keys-in-the-browser-through-webcryptoapi-instead-of-the-browseri
  4. const hex2Arr = str => {
  5. if (!str) {
  6. return new Uint8Array()
  7. }
  8. const arr = []
  9. for (let i = 0, len = str.length; i < len; i+=2) {
  10. arr.push(parseInt(str.substr(i, 2), 16))
  11. }
  12. return new Uint8Array(arr)
  13. }
  14. const buf2Hex = buf => {
  15. return Array.from(new Uint8Array(buf))
  16. .map(x => ('00' + x.toString(16)).slice(-2))
  17. .join('')
  18. }
  19. function doVerify(msg1, sigval, pubkey) {
  20. var curve = "secp256r1";
  21. let sigalg = "SHA256withECDSA";
  22. var sig = new KJUR.crypto.Signature({"alg": sigalg, "prov": "cryptojs/jsrsa"});
  23. sig.init({xy: pubkey, curve: curve});
  24. sig.updateHex(msg1); // updateHex for non-printable chars (updateString returns invalid signature); updateString if only printable chars.
  25. var result = sig.verify(sigval);
  26. return result;
  27. }
  28. async function generateOwnKeypairAndDeriveKey(dh_ga_x, dh_ga_y)
  29. {
  30. let alicePublicKey = hex2Arr('04' + dh_ga_x + dh_ga_y);
  31. try {
  32. const bobKey = await window.crypto.subtle.generateKey(
  33. { name: 'ECDH', namedCurve: 'P-256' },
  34. false, // no need to make Bob's private key exportable
  35. ['deriveKey', 'deriveBits']);
  36. const bobPublicKeyExported = await window.crypto.subtle.exportKey('raw', bobKey.publicKey);
  37. const bobPublicKeyHex = buf2Hex(bobPublicKeyExported);
  38. console.log(`Client's publicKey: ${bobPublicKeyHex}`);
  39. const aliceKeyImported = await window.crypto.subtle.importKey(
  40. 'raw',
  41. alicePublicKey,
  42. { name: 'ECDH', namedCurve: 'P-256'},
  43. true,
  44. []);
  45. const sharedSecret = await window.crypto.subtle.deriveBits(
  46. { name: 'ECDH', namedCurve: 'P-256', public: aliceKeyImported },
  47. bobKey.privateKey,
  48. 256);
  49. const sharedSecretHex = buf2Hex(sharedSecret);
  50. console.log(`sharedSecret: ${sharedSecretHex}`);
  51. const hashOfSharedSecret = await window.crypto.subtle.digest("SHA-256", sharedSecret);
  52. console.log("This is the hash" + buf2Hex(hashOfSharedSecret));
  53. const ownPublicKeyArray=Array.from(hex2Arr(bobPublicKeyHex).slice(1));
  54. const ownPublicKeyUnreadableString = ownPublicKeyArray.map(x => String.fromCharCode(x)).join('');
  55. const ownPublicKeyBase64=btoa(ownPublicKeyUnreadableString);
  56. return {mitigatorClientPublicKey: ownPublicKeyBase64, mitigatorDerivedKey: hashOfSharedSecret.slice(0, 16)};
  57. // console.log(aes_key_handle);
  58. // The code below is just for testing that indeed the hash was stored as the aes key. It will fail if the encryptable parameter in importKey (3rd one) is set to false.
  59. // const aes_key = await window.crypto.subtle.exportKey(raw, aes_key_handle);
  60. // console.log("This is the exported AES key: " + buf2Hex(aes_key));
  61. }
  62. catch (err) {
  63. console.log(err);
  64. return err;
  65. }
  66. }
  67. async function useDecryptorPublicKeyReturnOwnPublicKey(message) // sender
  68. {
  69. // TODO: Lol how d'ya check the URL of the sender (sender["url"]) is the corresponding background JS page?
  70. // Need to compare it to a URL that consists of the extension's ID..
  71. // Background script only ever calls this when this is true, but still checking it anyway.
  72. if(!("decryptorPublicKey" in message))
  73. return {error: "could not find decryptorPublicKey"};
  74. decryptorPublicKeyX=message["decryptorPublicKey"]["x"];
  75. decryptorPublicKeyY=message["decryptorPublicKey"]["y"];
  76. let returnValue = await generateOwnKeypairAndDeriveKey(decryptorPublicKeyX, decryptorPublicKeyY);
  77. if(!("mitigatorClientPublicKey" in returnValue) || !("mitigatorDerivedKey" in returnValue))
  78. return {error: "Oh no :( Could not generate the public key or the derived key"};
  79. console.log("And this is the derived key.");
  80. console.log(buf2Hex(returnValue.mitigatorDerivedKey));
  81. return {"ownPublicKeyBase64": returnValue.mitigatorClientPublicKey, "derivedKey": returnValue.mitigatorDerivedKey};
  82. }
  83. /*
  84. function recursiveIncrementIV(iv, byteCounter, minByteCounter)
  85. {
  86. if(iv[byteCounter] !== 0xff)
  87. {
  88. iv[byteCounter]++;
  89. return {iv: iv};
  90. }
  91. else
  92. {
  93. if(byteCounter === minByteCounter)
  94. return {error: "Reached maximum number of messages. Plz regenerate a new key."};
  95. else
  96. return recursiveIncrementIV(iv, byteCounter-1, minByteCounter);
  97. }
  98. }
  99. function incrementIV(iv)
  100. {
  101. return recursiveIncrementIV(iv, 11, 8);
  102. }
  103. */
  104. async function regenerateOwnPublicKey(input)
  105. {
  106. if(!input.decryptorPublicKeyObj && !input.url)
  107. {
  108. console.log("No decryptor public key or URL: dont know which website to regenerate own public key, derived key for");
  109. return {error: "No decryptor public key or URL: dont know which website to regenerate own public key, derived key for"};
  110. }
  111. let decryptorPublicKeyObj;
  112. if(input.url)
  113. {
  114. returnValue=getDecryptorPublicKeyForUrl(input.url);
  115. if(returnValue.error)
  116. return returnValue;
  117. decryptorPublicKeyObj=returnValue;
  118. }
  119. else
  120. decryptorPublicKeyObj=input.decryptorPublicKeyObj;
  121. returnValue=await useDecryptorPublicKeyReturnOwnPublicKey(decryptorPublicKeyObj);
  122. console.log(returnValue);
  123. if(!returnValue.ownPublicKeyBase64 || !returnValue.derivedKey)
  124. {
  125. let string3="Could not derive own public key or the derivedkey";
  126. console.log(string3 + returnValue);
  127. return {error: string3 + returnValue};
  128. }
  129. decryptorPublicKeyObj.ownPublicKey=returnValue.ownPublicKeyBase64;
  130. decryptorPublicKeyObj.derivedKey = returnValue.derivedKey;
  131. let iv=new Uint8Array(12);
  132. window.crypto.getRandomValues(iv);
  133. decryptorPublicKeyObj.iv = iv;
  134. urlPublicKeysMap.set(input.url, decryptorPublicKeyObj);
  135. return {success: "Successfully set own public key"};
  136. }
  137. async function processMitigatorPublicKeyHeader(e)
  138. {
  139. const headers=e.responseHeaders;
  140. const mitigatorHeader = headers.find(function(element) {
  141. return element.name === "Mitigator-Public-Key";
  142. });
  143. if(mitigatorHeader === undefined)
  144. {
  145. const string="Either Mitigator is not supported or this function is called on headers for other objects fetched along with the webpage.";
  146. console.log(string);
  147. return {log: string};
  148. }
  149. let url;
  150. if(e.documentUrl === undefined) // user opened a new tab.
  151. url=e.url;
  152. else
  153. url=e.documentUrl;
  154. url=url.split('/').slice(0, 3).join('/').concat('/');
  155. //urlPublicKeysMap.set(url, undefined);
  156. console.log("Here's the header value:");
  157. console.log(mitigatorHeader["value"]);
  158. let returnValue = verifyHeaderRetrieveDecryptorPublicKey(mitigatorHeader["value"]);
  159. if (!returnValue.decryptorPublicKey)
  160. {
  161. console.log("Could not find decryptor public key:");
  162. return {error: "Could not find decryptor public key:"};
  163. }
  164. const decryptorPublicKeyObj=returnValue;
  165. urlPublicKeysMap.set(url, decryptorPublicKeyObj);
  166. returnValue = await regenerateOwnPublicKey({decryptorPublicKeyObj: decryptorPublicKeyObj});
  167. console.log(returnValue);
  168. }
  169. async function encryptFieldsForUrl(url, fields_array)
  170. {
  171. let returnValue = getDerivedKeyIvForUrl(url);
  172. if(returnValue.error)
  173. {
  174. console.log(returnValue);
  175. return returnValue;
  176. }
  177. //console.log("Encrypting");
  178. const derivedKey=returnValue.derivedKey;
  179. let iv=returnValue.iv;
  180. let ciphertextArray = [];
  181. const algo = { name: "AES-GCM", iv: iv };
  182. const aes_key_handle = await window.crypto.subtle.importKey("raw", derivedKey,
  183. algo,
  184. false, // true, //whether the key is extractable (i.e. can be used in exportKey)
  185. ["encrypt"] //can "encrypt", "decrypt", "wrapKey", or "unwrapKey"
  186. );
  187. // TODO: Error catching here
  188. for (field of fields_array) {
  189. let fieldAscii = new Uint8Array(field.length);
  190. for (let i=0;i<field.length; i++)
  191. {
  192. fieldAscii[i] = field.charCodeAt(i);
  193. }
  194. console.log("About to encrypt this:");
  195. console.log(field);
  196. console.log("In ASCII:");
  197. console.log(fieldAscii.toString());
  198. try {
  199. const ciphertextAndTag = await crypto.subtle.encrypt(algo, aes_key_handle, fieldAscii);
  200. const ciphertextAndTagUint8 = new Uint8Array(ciphertextAndTag);
  201. let ciphertext = ciphertextAndTagUint8.slice(0,-16);
  202. let tag = ciphertextAndTagUint8.slice(-16);
  203. let ciphertextIVTag = Array.of(...ciphertext, ...iv, ...tag);
  204. console.log(ciphertextIVTag);
  205. let ciphertextIVTagBase64 = btoa(ciphertextIVTag.map(x => String.fromCharCode(x)).join(''));
  206. console.log(ciphertextIVTagBase64);
  207. ciphertextArray.push(ciphertextIVTagBase64);
  208. }
  209. catch(err)
  210. {
  211. console.log(err);
  212. console.log("Something went wrong when encrypting the fields.");
  213. return {error: "Something went wrong when encrypting the fields."};
  214. }
  215. // To change the IV for each field.
  216. window.crypto.getRandomValues(iv);
  217. returnValue.iv = iv;
  218. }
  219. return {ciphertextFields: ciphertextArray};
  220. }
  221. // TODO: PUT THE CODE BELOW INTO ANOTHER FUNCTION, CALL IT AND THEN CALL THE CONTENT SCRIPT TO SET
  222. // DERIVED KEY, OWN PUBLIC KEY, WHICH THEN CALLS BACK TO SET ITS OWN PUBLIC KEY OVER HERE.
  223. function verifyHeaderRetrieveDecryptorPublicKey(mitigatorHeaderValue) {
  224. console.log("Verifying header");
  225. let decryptorLongTermPublicKey = "04e2e1449dece8b8cf759b2f52541a9ff28eee70449cfb67807079b04f6d2a10e36dd1f3735ebfc95e1a7a4162c6eede07a8969bd1ff5850008614325002a882c3";
  226. //"04
  227. //950b235cda836f8660885a9aabe5816fc8142c4912bd44f65c278c1749081061
  228. //abad883ca934f8cc11c6c74205d2c9e55285a5696f075d1440a091e3bd6f0d81";
  229. // this function does **not** return an array of bytes. It returns a *string* of potentially non-printable characters- it converts the array of bytes into their ASCII representation.
  230. const decodedData = atob(mitigatorHeaderValue);
  231. // converting it into an array of strings of hex representation of bytes.
  232. const decodedDataArray = [];
  233. for (let i = 0; i < decodedData.length; i++) {
  234. decodedDataArray[i] = decodedData.charCodeAt(i).toString(16).padStart(2, '0');
  235. }
  236. const signature_r = decodedDataArray.slice(96,128).join('');
  237. const signature_s = decodedDataArray.slice(128).join('');
  238. let signature = "30440220";
  239. signature=signature + signature_r + "0220" + signature_s;
  240. const signature_data = decodedDataArray.slice(0,96).join('');
  241. const result = doVerify(signature_data, signature, decryptorLongTermPublicKey);
  242. if(result)
  243. console.log("Yay dude it works wtf");
  244. else
  245. {
  246. console.log("Damn, dude, it doesn't.");
  247. // return false;
  248. }
  249. const verifier_mrenclave = decodedDataArray.slice(64).join('');
  250. // TODO: Add verifier mrenclave checking code.
  251. // Extracting public key components in a hex string format.
  252. const public_key_x=decodedDataArray.slice(0,32).join('');
  253. const public_key_y=decodedDataArray.slice(32,64).join('');
  254. const urlDecryptorPublicKeyObject = {decryptorPublicKey: {x: public_key_x, y: public_key_y}};
  255. return urlDecryptorPublicKeyObject;
  256. }
  257. function setMitigatorClientPublicKeyHeader(e) {
  258. let headers = e.requestHeaders;
  259. let returnValue = getOwnPublicKeyForUrl(e.url);
  260. if(returnValue.ownPublicKey)
  261. {
  262. let clientHeaderObj={name: "mitigator-client-public-key", value:returnValue["ownPublicKey"] };
  263. headers.push(clientHeaderObj);
  264. console.log("Setting client's public key");
  265. }
  266. else
  267. console.log(returnValue);
  268. return {requestHeaders: headers};
  269. }
  270. function getDecryptorPublicKeyForUrl(url)
  271. {
  272. const searchUrl = url.split('/').slice(0, 3).join('/').concat('/');
  273. const hasSearchUrl = urlPublicKeysMap.has(searchUrl);
  274. let urlPublicKeyObj;
  275. if(hasSearchUrl)
  276. {
  277. urlPublicKeyObj= urlPublicKeysMap.get(searchUrl);
  278. return {decryptorPublicKey: urlPublicKeyObj["decryptorPublicKey"]};
  279. }
  280. else
  281. return {error: "Could not find this URL"};
  282. }
  283. /*
  284. function setOwnPublicKeyForUrl(url, ownPublicKeyBase64)
  285. {
  286. const searchUrl = url.split('/').slice(0, 3).join('/').concat('/');
  287. const hasSearchUrl = urlPublicKeysMap.has(searchUrl);
  288. if(hasSearchUrl)
  289. {
  290. let urlPublicKeyObj= urlPublicKeysMap.get(searchUrl);
  291. urlPublicKeyObj["ownPublicKey"]=ownPublicKeyBase64;
  292. urlPublicKeysMap.set(searchUrl, urlPublicKeyObj);
  293. return {success: "Successfully set own public key"};
  294. }
  295. else
  296. return { error: "Could not find this URL"};
  297. }
  298. */
  299. function getOwnPublicKeyForUrl(url)
  300. {
  301. const searchUrl = url.split('/').slice(0, 3).join('/').concat('/');
  302. const hasSearchUrl = urlPublicKeysMap.has(searchUrl);
  303. let returnValue;
  304. if(hasSearchUrl)
  305. {
  306. returnValue=urlPublicKeysMap.get(searchUrl);
  307. if(returnValue.ownPublicKey)
  308. return {ownPublicKey:returnValue["ownPublicKey"]};
  309. else {
  310. return {error: "Own public key has not been set by content script yet."}
  311. }
  312. }
  313. else
  314. return {error: "Could not find this URL"};
  315. }
  316. function getDerivedKeyIvForUrl(url)
  317. {
  318. const searchUrl = url.split('/').slice(0, 3).join('/').concat('/');
  319. const hasSearchUrl = urlPublicKeysMap.has(searchUrl);
  320. let returnValue;
  321. if(hasSearchUrl)
  322. {
  323. returnValue=urlPublicKeysMap.get(searchUrl);
  324. if(returnValue.derivedKey && returnValue.iv)
  325. return {derivedKey:returnValue.derivedKey, iv:returnValue.iv};
  326. else {
  327. return {error: "Derived key, IV have not been set by content script yet."}
  328. }
  329. }
  330. else
  331. return {error: "Could not find this URL"};
  332. }
  333. // from the content script and reply back with the decryptor's public key or to set own public key.
  334. async function backgroundListener(message)
  335. {
  336. // if("getDecryptorPublicKey" in message)
  337. // return returnValue= getDecryptorPublicKeyForUrl(message["url"]);
  338. // if("setOwnPublicKey" in message)
  339. // return setOwnPublicKeyForUrl(message["url"], message["setOwnPublicKey"]);
  340. let returnValue; let ownPublicKey;
  341. if(!message.url)
  342. {
  343. returnValue={error: "No URL sent: cant check if Mitigator is supported on the content script site."};
  344. console.log(returnValue.error);
  345. return returnValue;
  346. }
  347. if(message.regenerateOwnPublicKey) // TODO: Set a home_url property in the url object and if the sent_url and home_url are different, then regenerate.
  348. {
  349. returnValue = await regenerateOwnPublicKey({url: message.url});
  350. console.log(returnValue);
  351. if(returnValue.error)
  352. return returnValue;
  353. }
  354. if(message.fields)
  355. returnValue=await encryptFieldsForUrl(message.url, message.fields);
  356. if(message.getOwnPublicKey)
  357. {
  358. ownPublicKey=getOwnPublicKeyForUrl(message.url);
  359. returnValue.ownPublicKey=ownPublicKey;
  360. }
  361. return returnValue;
  362. }
  363. browser.webRequest.onHeadersReceived.addListener(
  364. processMitigatorPublicKeyHeader,
  365. {urls: ["http://*/*"]},
  366. ["responseHeaders"]
  367. );
  368. browser.webRequest.onBeforeSendHeaders.addListener(
  369. setMitigatorClientPublicKeyHeader,
  370. {urls: ["http://*/*"]},
  371. ["blocking", "requestHeaders"]
  372. );
  373. browser.runtime.onMessage.addListener(backgroundListener);