Ganesh
Ganesh

Reputation: 129

How can you prevent XSS that is sent as part of URL field

Currently I am displaying a link on a specific webpage with the URL set by a user through a POST request. The website is shown to a second user (user 2) which displays that link. When the link is clicked, it will go back to user 1's webpage (or that's what it is intended to be). But this came up recently where if the URL is modified or if the user 1 is a bad user, it sets the URL as Javascript://%0Aalert(document.domain)//, when the link is clicked it will execute the script.

How can this URL be validated in Java and prevent the user 1 from setting this as the URI instead right when the POST request comes in?

Upvotes: 1

Views: 1019

Answers (1)

Ilmari Karonen
Ilmari Karonen

Reputation: 50368

There are (at least) two ways to solve this problem, which you can use together or separately:

  1. Parse the received URL and check that all of its component parts (scheme, hostname, port, path, query string, etc.) contain reasonable values that your app would normally generate and that you trust to be harmless.

    In particular, just checking that the scheme is http and/or https would be sufficient to stop the specific attack mentioned in your question, although you almost certainly should do a bit more validation than just that.

  2. When originally generating the URL, calculate a cryptographic message authentication code of it (using a secret key stored on your server and never sent to the client) and send it alongside the URL. When you receive the URL back from the client, verify that the MAC still matches.

    This is a general technique for making sure that values that should be relayed unchanged by the client back to the server aren't tampered with. If you have several such values, instead of just a single URL, you can encode them all into a single string and calculate a single MAC on all of them. Just make sure that the encoding is deterministic, so that you can repeat it exactly when verifying the MAC. Also, you may want to combine additional metadata such as the user's ID and/or a timestamp into the MAC input in order to protect against replay attacks.

Upvotes: 1

Related Questions