Is SQL injection possible in TypoScript objects?
Using GET/POST vars in SQL queries involves the risk of SQL injection if the parameter is not properly sanitized. There are lots of warnings and documents around in the web on how to prevent this in PHP scripts. But what about TypoScript?
The TypoScript object CONTENT allows you to build SQL queries without the use of PHP. Have a look at the following (nonsense) example:
page = PAGE
page.10 = CONTENT
page.10 {
table = tt_content
select {
pidInList = 123
where = deleted=0
andWhere.data = GP:my_test|uid
andWhere.wrap = uid=|
}
}
The content of page.10 is a content element of page 123. To choose a certain content element, you can use a GET/POST parameter as the uid.
See it working
To see the example working, add some content elements to a page. We use page 123 in this example. Then note the uid of one of these content elements. In the example we use 42. Go to the frontend page in your browser and query the page:
http: //yourdomain.tld/index.php?id=123&my_test[uid]=42
This will output the content element with uid 42 on any page.
See the SQL injection working
What's the matter with this? The GET variable my_test[uid] is used inside a SQL query without being sanitized, open for SQL injection! Just try this URL:
http: //yourdomain.tld/index.php?id=123&my_test[uid]=42 OR 1=1
You should now see ALL content elements of your website. This is because OR 1=1 is injected and processed in the SQL WHERE clause.
How to prevent this?
The GP parameter my_test[uid] should only accept integer values. In PHP one could use the function intval() to make sure the given value gets converted to type integer. Luckily, there is an equialent in TypoScript for that. select.andWhere has stdWrap properties, so we can use the intval property inside andWhere. The above TypoScript snippet would then look like this:
page = PAGE
page.10 = CONTENT
page.10 {
table = tt_content
select {
pidInList = 123
where = deleted=0
andWhere.data = GP:my_test|uid
andWhere.wrap = uid=|
andWhere.intval = 1
}
}
Be careful, whenever you create SQL queries which processes GET/POST parameters. Using TypoScript solely does not avoid the danger of SQL injection.