1

In my CakePHP blog, I want to enable users to make similar HTML additions as you can insert here on StackOverflow, i.e. line breaks, links, bold, lists etc. But I am a little unsure how I shall tackle this issue in terms of what is most practical whilst maintaining protection against malicious code in the posts users submit.

  • Practically is it the most convenient to save the post in a TEXT database field and allow some HTML in that?
  • If I allow some HTML code in the post, how do I ensure that I only allow non-malicious basic HTML code whilst cleaning out the rest?
  • Should I be using the CakePHP Sanitize class for that somehow?
  • Will the FormHelper clean out all HTML users input?
  • I assume I'll have to use JavaScript to help users generate the right code?
  • [This link](http://stackoverflow.com/questions/13182682/php-security-combining-functionality-of-strip-tags-htmlspecialchars) will give a few good hints as well for underlying thinking for this problem. –  Nov 02 '12 at 19:21

2 Answers2

0

Use a whitelist for what HTML tags you allow. First HTML encode everything, then decode the specific tags that you allow.

A basic example:

function encodeForOutput(s) {
  s = s.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/&/g, '&amp;');
  // allow <b>
  s = s.replace(/&lt;b&gt;(.*?)&lt;/b&gt;/$, '$1');
  return s;
}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • obligatory: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – Lie Ryan Oct 06 '12 at 01:42
0

If it's not for developers, have you considered a WYSIWYG addon like TinyMCE?

http://www.tinymce.com/

http://bakery.cakephp.org/articles/galitul/2012/04/11/helper_tinymce_for_cakephp_2

As for security, whitelisting is the safest method. Blacklisting should be avoided because there's no way you can handle all the tricks that can be used to bypass them (e.g. passing in text via hex, etc).

TinyMCE lets you specify a whitelist: http://www.tinymce.com/wiki.php/Configuration:valid_elements

Costa
  • 4,851
  • 33
  • 30
  • Thanks. How do I whitelist then at the server side using CakePHP? Presume I need to set FormHelper input field escape to false. But I can't use Sanitize for that whitelisting. How would I go about doing it? –  Oct 31 '12 at 18:57
  • I have now discovered that Tinymce is wonderful to use, plan to use Htmlpurifier for whitelisting at the back end. –  Nov 01 '12 at 21:14