WordPress Plugin Developers and Escaping late

If you find this free website useful – why don’t you support this with a donation? It is easy…. read more ….

One major difficulty with passing WordPress org security reviews is escaping late. I wrote this article based on my experience of hardening the plugins I adopted.

What does this mean? It means applying a function around any data that is output at the time of output that removes any risky output.

What is risky output? As far as I understand any javascript type function that is created by a variable rather than by your own code. This is because, correctly engineered this data in a variable can be interpreted by the browser as javascript and code executed on the users computer that was never meant to be executed. This then can be used, for instance, to redirect a user, or alter the web page e.g. add a fake login form an then send the submitted form to a third party server stealing credentials ( phishing ).

Why do I have to do it at the point of output, I know the variable is safe, I checked it on input? A couple of reasons, the simplest being a future developer ( that may be you ) may just make some modification that invalidates the earlier checks ( sanitization ) – this happens more often than you think. The second being filters – WordPress filters allow other developers to hook in and modify variables and they may not do it safely.

That means I can never generate dynamic javascript? You can, but the best way to do that is via wp_add_line_script() and when you add that script escape any variable e.g. wp_add_line_script('my-script','alert('.esc_html($msg).');') You could also just echo the script e.g. echo 'alert('.esc_html($msg).');' as long as you escape the dynamic parts correctly

This is impossible for me as my html is all generated from templates, I can’t add escapes to every line, that would be crazy and unmaintainable? You don’t need to you can do this at the final output step with wp_kses_post() , this creates safe output suitable to post content, so just use echo wp_kses_post( $generated_ouput);

wp_kses_post() strips html that I want to keep so I can’t use it? OK so you want to output a form or svg or something the wp_kses_post() strips, then use wp_kses() . This take a bit more thought, as you have to specify what tags and attributes are allowed. But it is not hard, you can write a function that works generically for your plugin e.g. my_plugin_kses() and you can start by adopting all the wp_kses_post tags the following is an example from one of my plugins that allows svg and form input

See and download this on WP Code






Leave a Reply

Your email address will not be published. Required fields are marked *