WordPress Security (in many small steps)
(This is for people who like reading code, cross-posted at supernaut.info)
Earlier this year supernaut got hacked. Many other of my WordPress installs did also, perhaps because they occupy the same shared hosting space. I learnt a lot about website and WordPress security very quickly – even to the point of inadvertently vanishing all but my index page for quite some time. Nothing if not clever, I am.
Because I am doing all my projects in WordPress at the moment, and also seem to have turned quite a few people over to using it also, I thought to document my approach and methods. The first thing I do then, is read. A lot.
I have a subjective and not-too carefully analysed approach to learning, especially when it comes to finding out information on a topic I know nothing about and need to know much quickly. It applies to everything, not simply limited to web design or computer stuff. I search and read and search and read and keep repeating until the same stuff starts to come up over and over again. Then I start to think I might be on the right path. So I might try a few things then. The key here is easiness. Anything requiring more than a few clicks, a few lines of text or modifications is not a reasonable solution.
Things that break this early get thrown away. A plug-in that asks for stupid things, or doesn’t perform without me rewriting some line in php.ini is not going to stay installed long. I wondered often if this was the wrong approach, but really, basic, effective security should be as simple to understand as a household door key. You shouldn’t have to build a lathe in order to cut the key yourself.
So, having done some research and playing, I slowly put together something useful. This is a mix of things I’ve been using for a while, and new things I’m adding at the moment, in response to pissy annoying php exploits, sql injections and other clever irritations.
Installing WordPress.
The first thing to change during an install is the database table prefix wp_. If you’ve already installed WordPress, it’s possible to also change this either using a plugin, or by editing wp-config.php and changing the table prefixes in phpMyAdmin.
Once logged in, make a new user with administrator privileges and suitably complex password (OSX Keychain Access has a very good password generator), log in with the new user and delete the user, ‘Admin’.
Now is also a good time to delete the default theme (after uploading your new one of course). As with the user named ‘Admin’, the wp_ table prefix and other defaults, botnet code injection methods look for these defaults as an easy place to start.
To avoid messiness, I think it’s better to leave installing plugins till last, though because information is sent in the clear unless using SSL or SSH, it’s probably a good idea to change the password again when it’s all finished.
Get rid of install.php
After your installation is finished, you don’t need this file, located in wp-admin. Delete it, or change the name, or even better log attempts to access it with this (just change the email address to receive notifications):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <?php // install.php replacement page: http://perishablepress.com/press/2009/05/05/important-security-fix-for-wordpress/ ?> <?php header("HTTP/1.1 503 Service Temporarily Unavailable"); ?> <?php header("Status 503 Service Temporarily Unavailable"); ?> <?php header("Retry-After 3600"); // 60 minutes ?> <?php mail("email@domain.tld", "Database Error", "There is a problem with teh database!"); ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Error Establishing Database Connection</title> </head> <body> <h1>Error Establishing Database Connection</h1> <p>We are currently experiencing database issues. Please check back shortly. Thank you.</p> </body> </html> |
Dealing with wp-config
Every time I open this file and see the database name, user, password and host all in plain text, I get a little queasy. There are several ways to make this less painful, firstly using htaccess, which I’ll cover later. A quite elegant solution is to put all the sensitive information in a separate php file outside the root web directory, and make a call to that in the wp-config file.
First make a new file, config.php stick it (on Dreamhost) in the /home directory, chmod to 644, and cut-paste the following from the original wp-config.php:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <?php // ** MySQL settings - You can get this info from your web host ** // /** The name of the database for WordPress */ define('DB_NAME', 'database-name'); /** MySQL database username */ define('DB_USER', 'username'); /** MySQL database password */ define('DB_PASSWORD', 'p@s5w0rD'); /** MySQL hostname */ define('DB_HOST', 'sqlhost.domainname.tld'); /** * WordPress Database Table prefix. * * You can have multiple installations in one database if you give each a unique * prefix. Only numbers, letters, and underscores please! */ $table_prefix = 'prefix_'; /** force ssl login and admin - might slow things down */ /** on dreamhost must pay for ssl cert, hence not used */ /** define('FORCE_SSL_ADMIN', true); */ ?> |
Then in the original file, just put:
1 | include('/home/path/to/config.php'); |
For those lucky enough to have SSL on their server, using FORCE_SSL_ADMIN is an excellent idea. Changing permissions to 640 also is a good idea.
Adding Unique Authentication Keys takes about 30 seconds, and gives four separate keys to be used with your password. Copy-paste from the Secret Key online generator, it will look like this:
1 2 3 4 | define('AUTH_KEY', ' ;+ Xk*Kf:y3e1L?.,r[Hx<m;rV57d>2WL#<#3[ d]!#+$79/pSAF(HrGEAfS`a4'); define('SECURE_AUTH_KEY', '.k0zMi[@f&)E>~y=ZqO6~IfHS$S SP8d>C]S@:zhxh?H]VtXEpqV?p-OJV*O~3?v'); define('LOGGED_IN_KEY', '~:b*7/m+Lx|-irCxYAHQn1t2$sYA+2}+*2c@!_,9/D2-H5cJ_:wJ8X7|-p%W&xGh'); define('NONCE_KEY', '%#T+Y*|N>cq/2m3CRqR}SCM BodKio`<x+?nMAe6,qgU:YiyKgEu,%<er>>qS$V'); |
Functions.php
Most themes have a functions.php file which does all sorts of exciting things, writing bits to the theme templates, interacting with WordPress admin interface… A couple of extra lines provide a little obscurity. WordPress puts its version number in the header in wp_generator, and also a link to xml-rpc.php, which for most people is unnecessary – unless they are using a blogging client like Marsedit – and a risk. This quickly removes both, as well as hiding information about failed login attempts through the browser:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php //security stuff add_filter('login_errors',create_function('$a', "return null;")); function removeHeadLinks() { remove_action('wp_head', 'rsd_link'); remove_action('wp_head', 'wlwmanifest_link'); } add_action('init', 'removeHeadLinks'); function no_generator() { return''; } add_filter('the_generator', 'no_generator'); ?> |
htaccess
.htaccess is a joyous little world unto itself, like finding a hole in your backyard that leads into a vast cave system. mmm spelunking.
Much of my learning about security has revolved around what can be done with htaccess, and in particular Perishable Press and their 4G Blacklist. And much of what I do for security takes place here.
Starting with denying access to all to read the htaccess file itself. Then there is the WordPress hook that allows the install to exist in a different directory location to the site url. For those again who have SSL on their server, forcing SSL can be done here for admin and login. Then there are a bunch of protections to stop access to certain important files, install.php, wpconfig.php, and the WordPress readme.html.
Using gzip compression to deliver files and adding content expires information doesn’t strictly have much to do with security, but really, the difference in load times the former can make to a site, and the general usefulness of expires tags make this one to automatically add.
For those on Dreamhost, the DH-PHP handlers is automatically added when using the site-specific php.ini installer, something I’ll cover a bit further down.
Hotlinking prevents leechers sucking images and other content off your site, one of the first things I ever learnt how to prevent, when supernaut suddenly had massive bandwidth use as my images turned up in all manner of places.
The no-referrer section is specifically to thwart spammers circumventing your site altogether and trying to inject comment spam directly into the comments php. It’s also possible to block access to xml-rpc here, and use login passwords via httpasswd for extra security on the login page, both not included here.
Then comes the Perishable Press 4G Blacklist, a cornucopia of amazingness, which I left out for sake of brevity (haha). I have included two lines that need to be commented out in order for the browser-based file manager AjaXplorer to function ok.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | # === DENY HTACCESS === <files .htaccess> order allow,deny deny from all </files> # === END DENY HTACCESS === # === BEGIN WORDPRESS === <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # === END WORDPRESS === # === FORCE SSL === #RewriteRule !^/wp-(admin|login|register)(.*) - [C] # === END FORCE SSL === # === PROTECT install.php === <Files install.php> Order Allow,Deny Deny from all Satisfy all </Files> # === END PROTECT install.php === # === PROTECT readme.html <files readme.html> Order deny,allow deny from all </files> # === END PROTECT readme.html # === PROTECT wpconfig.php === <files wp-config.php> order allow,deny deny from all </files> # === PROTECT wpconfig.php === # === DH-PHP handlers === AddHandler fastcgi-script fcg fcgi fpl AddHandler php-fastcgi .php Action php-fastcgi /cgi-bin/dispatch.fcgi # === END DH-PHP handlers === # === BEGIN GZIP FILE TYPES BY EXTENSION === <Files *.html> SetOutputFilter DEFLATE </Files> <Files *.css> SetOutputFilter DEFLATE </Files> <Files *.js> SetOutputFilter DEFLATE </Files> <Files *.ttf> SetOutputFilter DEFLATE </Files> # === END GZIP FILE TYPES BY EXTENSION === # === BEGIN CONTENT EXPIRES === #set expire dates <IfModule mod_expires.c> ExpiresActive on # 60 seconds * 60 minutes * 24 hours * 7 days ExpiresDefault A604800 # 60 seconds * 60 minutes * 24 hours ExpiresByType text/html A86400 </IfModule> <FilesMatch "\.(ico|pdf|flv|f4v|m4v|jpg|jpeg|png|gif|swf|js|css|ttf)$"> # configure ETag FileETag none # max-age set to one week as above Header set Cache-Control "max-age=604800, public, must-revalidate" # if you use ETags, you should unset Last-Modified # Header unset Last-Modified </FilesMatch> # === END CONTENT EXPIRES === # === DISABLE HOTLINKING === <IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{HTTP_REFERER} !^$ RewriteCond %{REQUEST_FILENAME} -f RewriteCond %{REQUEST_FILENAME} \.(gif|jpe?g?|png|ico)$ [NC] RewriteCond %{HTTP_REFERER} !^https?://([^.]+\.)?domainname\. [NC] RewriteRule \.(gif|jpe?g?|png|ico)$ - [F,NC,L] </ifModule> #=== END DISABLE HOTLINKING === # === DENY ACCESS TO NO-REFERRER REQUESTS === <IfModule mod_rewrite.c> RewriteCond %{REQUEST_METHOD} POST RewriteCond %{REQUEST_URI} .wp-comments-post\. [NC] RewriteCond %{HTTP_REFERER} !.*domainname\. [OR,NC] RewriteCond %{HTTP_USER_AGENT} ^$ RewriteRule (.*) - [F,L] </IfModule> # === END DENY ACCESS TO NO-REFERRER REQUESTS === # === PERISHABLE PRESS 4G BLACKLIST === (snip…) # QUERY STRING EXPLOITS <IfModule mod_rewrite.c> # this line stops ajaxplorer working RewriteRule ^(.*)$ - [F,L] </IfModule> # CHARACTER STRINGS <IfModule mod_alias.c> # BASIC CHARACTERS # RedirectMatch 403 \/\/ ajaxplorer again </IfModule> |
robots.txt
Equally effective, and probably overkill, using robots.txt can grant or forbid access to a slew of places, particularly directories that you don’t want spidered, as well as any and all WordPress directories, using Disallow: /wp*.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | User-agent: * Disallow: /cgi-bin Disallow: /lurking Disallow: /phpsecinfo Disallow: /wp-* Disallow: /tag Disallow: /author Disallow: /wget/ Disallow: /httpd/ Disallow: /i/ Disallow: /f/ Disallow: /t/ Disallow: /c/ Disallow: /j/ User-agent: Mediapartners-Google Allow: / User-agent: Adsbot-Google Allow: / User-agent: Googlebot-Image Allow: / User-agent: Googlebot-Mobile Allow: / User-agent: ia_archiver-web.archive.org Disallow: / Sitemap: http://www.domainname.tld/sitemap.xml |
php.ini and phpsecinfo
Getting deeper into the system still and further yet from WordPress, modifying php.ini, the file that sets up what php can do is another essential. Dreamhost doesn’t make it easy to edit the php.ini, but fortunately there’s a script which installs it locally. More excitement ahead.
As with htaccess, much can be done in php.ini to prevent messiness. The following seem to work rather well. I’ll leave this uncommented upon except to say AjaXplorer needs fopen to be on, and shall devote a future post to elaborating on php.ini security.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | open_basedir = /home/site/folder:/home/site/tmp/folder disable_functions = exec,passthru,system,proc_open,popen,curl_multi_exec,parse_ni_file,show_source expose_php = Off error_reporting = E_ALL & ~E_NOTICE register_globals = Off ; Whether to allow HTTP file uploads. file_uploads = On upload_tmp_dir = /home/site/folder/tmp/php ; Maximum allowed size for uploaded files. upload_max_filesize = 200M ; Whether to allow the treatment of URLs (like http:// or ftp://) as files. allow_url_fopen = On ; Whether to allow include/require to open URLs (like http:// or ftp://) as files. allow_url_include = Off |
In addition to editing php.ini, and making sure there isn’t a file lying around called info.php with phpinfo() inside, phpSecInfo is an invaluable tool for assaying the security of your website, the results from which can be directly used to edit php.ini.
FTP, or rather SFTP.
As with passwords being sent in the clear, so too is FTP on its own not so great. Dreamhost allows for shell plus SFTP access with FTP disabled, which is both sensible for using desktop FTP clients (such as the amazing Transmit), and for searching out code injections. Time to open Terminal.
Commandline access is essential for a number of reasons, and instead of using the username/password combination, create passwordless login using private keys.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | //Generate a RSA private key ssh-keygen -t rsa // copy the key to your website scp ~/.ssh/id_rsa.pub user@domainname.tld:~/ //ssh into your website ssh user@domainname.tld //Make a new folder, .ssh and copy the key to the authorized_keys file, then delete the key mkdir .ssh cat id_rsa.pub >> .ssh/authorized_keys rm id_rsa.pub //Set all permissions chmod go-w ~ chmod 700 ~/.ssh chmod 600 ~/.ssh/authorized_keys |
Why might this all be useful? Going back to when I was hacked earlier this year, I could have gone though all the files on all my sites looking for base64 code, instead I opened Terminal, SSH’ed in and sent this command:
1 | find . -name "*.php" -exec grep "base64" '{}' \; -print |
Which searches through all files with the extension .php for the string base64 and dumps the results on screen. I found every instance of the hack in a matter of seconds.
Plugins for security.
Leaving aside all that code now…
WordPress is amazing because of its plugins and the community around its development. The problem though, for any plugin is twofold. Which one does the task you want the best (while integrating with the rest of your setup), and is updated frequently enough to not become a liability?
After the initial hack, I had many installed, which I then uninstalled because of small irritations and annoyances. After changing all my passwords to 16+ characters, including as many of type !@£$%^&_ as allowable, WordPress File Monitor has become an installation standard.
Rather than provide security, it lets you know when any modifications to files and folders have occurred, and in which. Notification via email and/or Dashboard alert, alterable scan intervals and directory path exclusions for me make this indispensable. When a new exploit emerges, instead of panicking and manually scanning all my installs for changes (which I do anyway out of nervous boredom), I can be fairly secure they will show up here. Of course, the idea is not to get hacked in the first place.
I’ve read a lot of good things about AskApache Password Protect, but I’ve never got it working, despite adding all the .htaccess files and even chmod up to 666. I would at least play with it otherwise, but for now don’t want to spend the time on it.
In general though (and said with a caveat that I don’t really know WordPress very well), much or all security that can be done with plugins can be done in other ways – .htaccess, robots.txt. php.ini, wp-config, sql changes and so on. Also, so many of the plugins haven’t been updated recently, which for me is worse than no protection due to the false sense of security.
During the course of the last two days, while I went through all the security stuff I could find, websites, pdfs, my own archives, I came across a couple of other plugins which I think are useful.
Semi Secure Login Reimagined provides about as good public and secret key encryption for passwords as possible if you don’t have access to SSL.
WP Security Scan I found useful for a post-install check to make sure all the settings were as minimally tight as could be. In the interests of not having hundreds of plugins, I uninstalled it after.
404 Notifier does just that, though I suspect getting off my ass and reading the logs (or ssh and then grepping them for 404s) would be a better idea.
Sources
Much of my information for this comes from a few places.
The WordPress Codex itself is a good place to start, and the Plugin directory also worth spending time in.
Perishable Press is invaluable, and not just for security.
Digging into WordPress, both the website and the book are the fundamental step-by-step guide for all things security and WordPress.
The WordPress community, across many blogs, forums, books, comments and bits and pieces.
Oh, and while this applies also to WordPress 2.9.x, I’m currently running the 3.0 beta on thingswithbits.info where I tested all this. (hopefully this all doesn’t add to confusion.)