0

I'm trying to keep my site more secure and detect script injections. Imagine that the browser injected (example: using extensions or console) the following event script into the page:

document.addEventListener("click", Maliciousfunction);
document.getElementById("demo").addEventListener("click", function(){
window.alert("Test");
});

Is there any function for the site to detect this? Example:

//Return: name of function "Maliciousfunction" or function code
document.getEventCode('onclick');
//Return: function code window.alert("Test");
document.getElementById("demo").getEventCode('onclick');
2
  • 2
    What if such function exists in your page but the first step of the malicious script would be to remove it? Commented May 5, 2019 at 20:13
  • That sounds like a re-iteration of the no right mouse click tricks websites used to do in order to keep their source from not being visible. There will always be a workaround
    – Icepickle
    Commented May 5, 2019 at 20:19

1 Answer 1

1

It's somewhat possible, but it's complicated and wouldn't be all that useful - in the end, it's the client's browser, so the client can run whatever code they want to.

The closest you can probably get is to overwrite all the native functions whose usage you want to prevent, for example:

(() => {
  // First extract the properties you want to be able to use here:
  const { addEventListener } = EventTarget;
  const { alert } = window;

  // in order to use them asynchronously (after they've been overwritten below), use `.call`:
  addEventListener.call(myElement, 'click', () => { alert('clicked!'); });

  // at the end of the IIFE, overwrite all of those functions:
  EventTarget.addEventListener = null;
  window.alert = null;
})();

The same sort of pattern can be used for extracting and overwriting any built-in function.

If your code runs before the injected code, the injected code will no longer be able to access alert or addEventListener. But if the injected code runs before your code, it may simply save the references to those functions, and use them without issues - even if you overwrite them later, the other script will already have a reference to them.

IMO, don't bother - it's the client's own machine, not yours, if they (or some other script) wants to do something, they can find a way to do it, regardless of your code.