Several weeks ago, this blog was hacked by a mad (but smart) guy. He injected javascript code to my post comments that displayed ugly messages when the page is loaded. It didn't harm my data at all, but still that was something you don't want to see in your site!
My mistake was I didn't validate the incoming data at all. All data was immediately inserted to the database, with no check whether it contains illegal code or something not usual. To make things worse, the new inserted comment was immediately displayed in the page.
The form and the PHP code look like this:
Listing 1: page.php
This guy added his comment like this:
Name : FisherSQ7@w.cn
Email : sq7@w.cn
Website: http://w.cn
Comment: <script>alert("Hacked By Fisher762")</script> Go To hell
With my PHP script above, the SQL string would be:
INSERT INTO comments
VALUES(
'FisherSQ7@w.cn',
'sq7@w.cn',
'http://w.cn',
'<script>alert("Hacked By Fisher762")</script>Go To hell'
);
which then inserted to the database successfully with no error. The problem arise when the comment is loaded. The HTML:
Listing 2: The HTML output
He successfully inserted illegal code to the page, and displayed an ugly message 'Hacked By Fisher762' everytime the page loaded. No clue where the popup is coming from, until I read the HTML source carefully. very clever.
After the accident, I realize that I have to check every input that comes from clients. Like they say, never trust user's data. So I write a function to check incoming data for illegal code or even something not usual.
Listing 3: A much better code
pening on Jul 9, 2008:
Nash on Jul 10, 2008:
fisher762 on Jul 31, 2008:
test your fixed on Oct 10, 2008:
Berry on Feb 13, 2009:
Anonymous on May 9, 2010:
Nash on May 10, 2010:
| Tel. | +62 31 8662872 +62 856 338 6017 |
| ICQ | 489571630 |
| Skype | dede_bl4ckheart |
| Yahoo | dede_bl4ckheart |
| nashruddin.amin |
Darren on Jun 12, 2008:
Thanks for this post am adding a self coded user input form to my site and wanted to know how to stop people doing nasty stuff .
Coding is not that hard well it is and a noble art but a guy wanted to charge me $100 for what is free from you.THX