Web Development - Don't Let Your Query String Design Turn Your Site Into A Hacker's Playground
In a previous tip, a reader recommended a useful way to architect a site for showing photos embedded within web pages for fuller functionality. His solution was to pass in the photo name with a query string, like so:
- (Put < in front of a) a href="picture.html?photo=photoA.jpg">img src="th_photoA.jpg" alt="Thumbnail of photo A">/a>
Then, in picture.html, at the place where you want to display the photo, you could write something like this:
- // Get the value of the "photo" query item
- var photoFile = window.location.search.substring(1).split("=");
- // Use that to write out the img> tag document.write('img src="' + photoFile + '">'); /script>
While this simple example demonstrates a good design for avoiding creating a zillion web pages (one for each photo), you'd need to adapt it a bit for security purposes to use it in a real site. In the example, we simply write information from the query string from the page, all with client-side code. This enables us to demonstrate the technique without getting into server-side code, etc. But in a real-life situation, you'd need to validate the data from the query string against known, valid choices, or at least encode it properly.
Here's why: If you use query string data to compose your page on the fly, you now run the risk of somebody composing a malicious link to your site and sending it to other users to click on with potentially disastrous results. An email that originally said "Check out this sweater, I think it'll go great with my hot pink leather pants" and a link along the lines of
could easily be changed by a bad guy so the link is:
This new link will show questionableImage.jpg from evilhacker.com. Or the bad guy could change the link to the following:
The URL is from your site, but will cause your page to redirect users to evilhacker.com/lookslikeyoursite.html. Any script could work here, including one that sends your cookies to evilhacker.com for collection. There are a ton of evil things somebody could do with this type of setup (session riding, cross-site scripting, and others). So if you want to use the query string, first validate/sanitize the data before using it to render the page.