Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTMLPurifier : How to allow a single attribute without redefining the whole whitelist

I'm using HTMLPurifier to sanitize HTML string (it's about security).

Some attributes (like width or height) are removed when HTMLPurifier is called. I don't consider this as a security issue.

How can I add this attribute without redefining the whitelist ?

I searched on Stackoverflow and HTMLPurifier documentation, but the only solution seems to be :

$config->set('HTML.Allowed', 'p,b,a[href],i');

But this is not a solution, because I don't want to redefine the whitelist (I trust the default HTMLPurifier configuration, I just want to add an exception).

like image 341
rap-2-h Avatar asked Jul 03 '12 10:07

rap-2-h


2 Answers

I found the same issue and the only solution was pasting in the whitelist styles into the HTML purifier add attribute settings.

The whitelist settings are:

a.class,
a.href,
a.id,
a.name,
a.rev,
a.style,
a.title,
a.target,
a.rel,
abbr.title,
acronym.title,
blockquote.cite,
div.align,
div.style,
div.class,
div.id,
font.size,
font.color,
h1.style,
h2.style,
h3.style,
h4.style,
h5.style,
h6.style,
img.src,
img.alt,
img.title,
img.class,
img.align,
img.style,
img.height,
img.width,
li.style,
ol.style,
p.style,
span.style,
span.class,
span.id,
table.class,
table.id,
table.border,
table.cellpadding,
table.cellspacing,
table.style,
table.width,
td.abbr,
td.align,
td.class,
td.id,
td.colspan,
td.rowspan,
td.style,
td.valign,
tr.align,
tr.class,
tr.id,
tr.style,
tr.valign,
th.abbr,
th.align,
th.class,
th.id,
th.colspan,
th.rowspan,
th.style,
th.valign,
ul.style
like image 118
trkest Avatar answered Oct 20 '22 10:10

trkest


This code:

<?php

require('purifier/library/HTMLPurifier.auto.php');

$html = "<img width='200' height='200' src='test.jpg' alt='bla>";
$config = HTMLPurifier_Config::createDefault();
$purifier = new HTMLPurifier($config);
echo $purifier->purify($html) . "\n";

$html = "<table width='100'><tr><td>test</td></tr></table>";
echo $purifier->purify($html) . "\n";

?>

Produces this output:

<img width="200" height="200" src="test.jpg" alt="bla" />
<table width="100"><tr><td>test</td></tr></table>

Using php 5.3.10 and HTMLPurifier version 4.4.0. So these attributes are not stripped by default (I am using a clean install of HTMLPurifier)

On which HTML elements are you using the width/height attributes?

Also note invalid attributes will be stripped when using xhtml strict. Width and height on img and table elements are allowed as far as I know but should be lowercase. Except for "width='100%'" on an image element (added for completeness after rap-2-h his comment)

In general: use addAttribute instead of the whitelist to add allowed attributes.

like image 45
Willem Joosten Avatar answered Oct 20 '22 09:10

Willem Joosten