Safe PHP expressions in templates

In regards to my PHP in Templates MyBB plugin, I’ve been thinking of the possibility of using “safe expressions”, that is, allowing <if> conditionals without allowing admins to enter in “undesirable” PHP.

I came up with an idea yesterday, which I’m giving a shot at.

Basically, there’s probably only two main types of undesirable code:

  • arbitrary modifications of any kind
  • retrieving restricted information

So, any arbitrary PHP code which does neither of the above should be considered “safe”, although I admit that I feel a little edgy over this assumption.

For the first point, there’s only really three ways to perform any modifications in PHP:

  • Assignment operations (=, +=, |=, ++ etc) – this can easily be blocked by finding them in the code (after removing strings); interestingly, PHP doesn’t allow expressions such as $a--$b, instead, they need to be written (IMO properly) as $a-(-$b)
  • Functions/statements (unset, fopen, mysql_query etc) – a whitelist of allowable functions could feasibly block this, although there’d need to be a huge list of allowable functions >_>
  • Executing processes (backtick operator, eg `ls -a`) – just simply block this operator

For the second point, the MyBB template system already allows some information gathering by printing variables (eg $_SERVER[...]) so I won’t consider this to be an issue, instead, I’ll block some constants, such as __FILE__ and PHP_OS, which don’t seem to be easily printable through the MyBB templates system.  The other thing is through functions/statements, which we’re already going to whitelist, so shouldn’t be an issue.

After all that, we just have to consider a few “backdoors”:

  • Executing code within PHP strings, eg "{${phpinfo()}}"
  • Variable function calls, eg $func()

Hopefully, this catches all the bad expressions.

I’m planning on releasing a separate version of the plugin which will not accept these bad expressions.

Leave a Reply