| |

Cross-Site Scripting (XSS)

Cross-Site Scripting occurs when user input variables are not being escaped (output) and sanitized (input) properly. This usually happens due to there not being any sanitization and escaping at all or due to a misunderstanding of some of the WordPress functions.

The example below assumes a user input variable is saved directly inside of an option, which is then retrieved.

$identifier = get_option('my_identifier');

// Vulnerable, zero output escaping.
echo '<input type="text" name="my_identifier" value="' . $identifier . '">';

// Vulnerable, sanitize_text_field does not escape quotes.
echo '<input type="text" name="my_identifier" value="' . sanitize_text_field($identifier) . '">';

WordPress provides a long list of different escape functions you can use to escape your user input variables. Depending on where you output the user provided values, you might have to use different functions. The WordPress link will explain in-depth when and where to use each function.If your plugin or theme accepts custom HTML provided by a user, you should use the wp_kses function as it allows you to define a whitelist of allowed HTML tags and attributes. However, that gives no guarantee that XSS is not possible.

In the example above, we’d want to use the esc_attr function as it’s a user provided value that is printed into a HTML element’s attribute

$identifier = get_option('my_identifier');
echo '<input type="text" name="my_identifier" value="' . esc_attr($identifier) . '">';

Similar Posts

Leave a Reply

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