Post Pic

WordPress plugin: Protect your blog from malicious URL Requests

Due to its popularity, WordPress is often the target of hackers. Today, let’s see how we can build a plugin that will check for malicious URL requests (Long request strings, presence of either “eval” and “base64″ php functions, etc.) and use it to protect our blog.

Paste the following code into a text file, and save it as blockbadqueries.php. Once done, upload it to your wp-content/plugins directory and activate it like any other plugins. That's all!

<?php
/*
Plugin Name: Block Bad Queries
Plugin URI: http://perishablepress.com/press/2009/12/22/protect-wordpress-against-malicious-url-requests/
Description: Protect WordPress Against Malicious URL Requests
Author URI: http://perishablepress.com/
Author: Perishable Press
Version: 1.0
*/
global $user_ID; if($user_ID) {
  if(!current_user_can('level_10')) {
    if (strlen($_SERVER['REQUEST_URI']) > 255 ||
      strpos($_SERVER['REQUEST_URI'], "eval(") ||
      strpos($_SERVER['REQUEST_URI'], "CONCAT") ||
      strpos($_SERVER['REQUEST_URI'], "UNION+SELECT") ||
      strpos($_SERVER['REQUEST_URI'], "base64")) {
        @header("HTTP/1.1 414 Request-URI Too Long");
	@header("Status: 414 Request-URI Too Long");
	@header("Connection: Close");
	@exit;
    }
  }
}
?>

Thanks to Jeff Starr for this great plugin! Do you know that Digging into WordPress, Jeff's book, has just been updated? Click here for more info.

16 Responses

Mar 04 2010 12:09

Could you please clarify more in what for situation this would be needed aka who or what are these ‘malicious URL Requests’?

I understand is against hackers, but hats too vague for me…

Thanks in advance.

Mar 04 2010 14:53

Like a wp-firewall plugin but this is very simple and powerfull..Thanks for share

Mar 04 2010 21:11

@Tschai: There is more information available in the original post (as well as in the comment thread): http://perishablepress.com/press/2009/12/22/protect-wordpress-against-malicious-url-requests/

Mar 05 2010 02:31

I will put on my site…

Mar 05 2010 04:54

Nice bit of code, except that “level_10″ as a capability has been deprecated for several WP versions now….

Mar 06 2010 01:48

@Stephen R: Good point – level_10 is a hard habit to break for us old-timers, but I’ll make sure to swap it out with the latest code for the next version. Thanks for the reminder.

Mar 06 2010 18:30

with this code, do you cut requests from google image searcher?

Mar 07 2010 19:47

@jj: That is a possibility if the request URLs are longer than 255 chars. You can change this value to something greater to accommodate though.

Jul 03 2010 15:19

Thanks a lot for yet another super article. I am always trying to find good WordPress tricks to suggest to my clients. Thanks for creating this article. It’s just what I was trying to find. Truly wonderful post.

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required