Solve XSS in WordPress code in two simple steps.

In the last post we talked about a real world case of XSS in a WordPress plugin.

You can read the last post here.

Exploring XSS in sanitize_text_field.

But what is XSS?

Cross-site Scripting (XSS) is a type of malicious code injection in web applications, classified among the main vulnerabilities.

I always say that there is no silver bullet solution.

In the case discussed in the last post, the developer used a method that could help but was being used the wrong way.

Today we’ll talk about how to protect XSS.

Only XSS, so let’s go.

XSS as we have seen is a code injection attack, and we can defend against it by clearing the input data and / or by clearing the data that is going to be printed.

Cleaning the input data:

<form>
<input type="text" name="title" value="title" />
<input type="submit" />
</form>

$title = sanitize_text_field( $_POST['title'] );
update_post_meta( $post->ID, 'title', $title );

In this case we should use sanitize_text_field () because it is a text field, but there are many options like:

  • sanitize_option()
  • sanitize_text_field()
  • sanitize_textarea_field()
  • sanitize_title()
  • e outros;

Clearing the output:

As we can not always trust the data that came in, we have to clear the output, in this case it should be use:

<form>
<input type="title" name="title"
value="<?php echo
esc_attr( $title ); ?>" />
<input type="submit" />
</form>

In this case, we clear the output of the attribute with esc_attr as we are cleaning an attribute of a tag, but we have more options like:

  • esc_textarea
  • esc_js
  • esc_html
  • esc_url

Well, we are all protected.

See you in the next post, maybe how to protect yourself from a traversal path.

See you.

Leave a Reply

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