[wp-hackers] the template tags and their default safe contexts

Haluk Karamete halukkaramete at gmail.com
Sun Feb 16 19:49:42 UTC 2014

Right off the bat, I'd like to express that this post of mine is not a
criticism of the current system, whatsoever. I know security is a complex
I'm only trying to get the hang of the issue I will be trying to point out
below to pick your brains for ideas. That's all there is to it.

Having said that...  here we go.

To make my point, I will just pick the template tag the_title().

The the_title() outputs the title.

And it's very easy to learn this fact, thanks to the codex and the
countless articles that are out there.

Since it's a WordPress core function, it's also pretty human to think that
it should be safe to use it is as is. At least, I would not blame the many
who think so, from the get-go.

But the fact of the matter is HTML is a complex thing. And dealing with XSS
or simply writing valid HTML is even more complex. And most people can
easily get lost in this.

Take a look a this piece for instance...

It uses the_title() in a straightforward HTML.

<a href="#" title="<?php the_title(); ?>"><?php the_title(); ?></a>

The question is - Is it safe?

Obviously not...

Well, it is %50 secure. :)

The part within the HTML context ( which will eventually be falling in
between > and < ) is fine but the attribute part ( which will be falling
into title=" and " ) is not.

The the_title() call within the title attribute above is like a military
mines which is waiting to detonate for the wrong title.

Considering so many different contexts, and some many template_tags and so
many esc_ functions, and millions of people out there, what do we do? or
should do?

And what do you guys do to sort this kind of matters when writing your own
template files that outputs stuff? What handle or conventions do you use?

obviously, we do not have
the_title_attr() and
the_title_html() versions for each and every template tag - which would
follow the esc_API context conventions in a one to one fashion ) as Mark
demonstrates here->

I do know the fact that here, we have "the_title_attribute()" available to
us, but hey, you just have to know that.

What if, I needed to use the the_title() within a javascript context as
below. Which way do I go about it - and how do I know  which one would be
Stackoverflow it?

$the_title = '<?php the_title();?>';
$the_title = '<?php esc_js(the_title());?>';
$the_title = '<?php the_title_attribute();?>';
$the_title = '<?php esc_js(the_title_attribute());?>';

Is the only way to sort this out to know each-and-every-template_tag and
their safe output contexts? Or are there tips or conventions you guys use
to sort these things in a convenient way?

I'm just curious.

More information about the wp-hackers mailing list