How to remove the security hole in WordPress comment HTML

Before reading further, you should read my earlier post, Your WordPress site comments are giving information to hackers, since this post provides a neater solution to the problem described in… More »

Spread the love

Before reading further, you should read my earlier post, Your WordPress site comments are giving information to hackers, since this post provides a neater solution to the problem described in that post.

Summary of Problem

When a comment is made on a WordPress post, and the comment is by a logged-in user, WordPress adds two CSS classes to the HTML list item containing the comment:

  • byuser
  • comment-author-yournicename (where ‘yournicename’ is the ‘user_nicename’ stored in the users table for the user who added the comment)

This immediately tells would-be hackers that ‘yournicename’ may be a valid username with which they can try to log in, due to the particular way WordPress stores usernames, nicenames, nicknames and dispay names by default.

Furthermore, if the comment is made by the same user that originally published the post, WordPress adds another CSS class to the HTML list item containing the comment:

  • bypostauthor

So this time the would-be hacker knows that if ‘yournicename’ is a valid login, it’s also one with enough rights to publish posts.

The New Solution

Fortunately when WordPress assembles the classes to use when building the HTML for a comment, there is a filter that you can hook into, which can amend the list of classes before they are rendered. The filter is called comment_class.

So by hooking a simple function into that filter in the functions.php file of your theme, you can decide which CSS classes should be rendered for comments and which should not.

The Code

Here’s my resulting function that goes into the functions.php file in my theme and hooks into the filter:

function filter_comment_class($classes) { if (is_array($classes)) { if (count($classes) >= 1) { foreach ($classes as $key => $class) { if ($class == 'bypostauthor') { unset($classes[$key]); } if ($class == 'byuser') { unset($classes[$key]); } if (substr($class, 0, 15) == 'comment-author-') { unset($classes[$key]); } } } } return $classes;
}
add_filter('comment_class', 'filter_comment_class');

You can see from this that I’m removing the ‘byuser’ class, the ‘bypostauthor’ class and any class that starts with ‘comment-author-‘. When the comments for a post are shown, the underlying HTML will not contain any of these classes.

This code now goes into all my projects where comments may be enabled. Job done.

Share Button
Facebook Comments
Spread the love

Posted by News Monkey