Tips to improve WordPress security

A few weeks ago, a website I had worked on became unavailable, and I investigated to find that it had been compromised, or hacked. A file, ‘indix.php’, was added to the root directory on the fileserver. The file contained some referral to a Ukrainian website, but it was enough to take the site down.

The site was a WordPress website. WP is quite renown for poor security, but that’s not to say you can’t make it secure. I’d like to now write about how I have increased the security of this website to prevent future problems.

The first thing I can recommend is to install the WP Security Scan plugin to see how secure your site is currently from here.

File Permissions

The general rule for WordPress file permissions is to keep file directories as 755, which means that a user can read, write and execute, and to keep individual files as 644. This means that the owner can read/write the file and other users (the world) can only read it. One exception to this rule is the ’.htaccess’ file, which you should keep on 400 permission, meaning that only you and the server can read the file.

.htaccess

A very important file to web development. You can use ’.htaccess’ to control security throughout your site.

Prevent directory browsing:


 Options All -Indexes

Protecting wp-config.php file:



Order Allow,Deny
Deny from all

Restrict access to any .php file:



AuthUserFile /etc/httpd/htpasswd
AuthType Basic
AuthName "restricted"
Order Deny,Allow
Deny from all
Require valid-user
Satisfy any

AskApache Password Protection Plugin

Another great plugin that will add a brick wall to your PHP files. Download from here.

Moving the wp-config.php file from the root

You should move the ‘wp-config.php’ file one directory up from the root WordPress folder.

This tip is quite controversial, but after reading through the answers posted here I’m convinced this is a good decision.

Keeping passwords secure

I’m sure this was the reason the site I worked on was hacked; poor passwords. I guess that a hacker ran a pass on millions of WordPress sites using a large word list, effectively guessing the user/password combination. The solution to this is simple: use a better password. One with numbers, capital letters, symbols. I feel this comic illustrates the idea well.

Keeping WordPress up-to-date

This is self-explanatory. Always check for updates.

Easy interstital pages with RoR & meta tags

Last week I was asked to create a simple interstitial page. Basically, a page that a user would be redirected to between page navigation. Normally they are used for ads, but you can be more creative.

I came across a simple way to implement the interstitial page into our link shortener app using HTML meta tags. First, a redirect page was created, ’redirect.html.erb’. Inside this page, I used the meta attribute ’http-equiv’ to force a refresh after 5 seconds, which along with the ‘content’ attribute would redirect to a given URL. For example:

<meta http-equiv="refresh" content="5;URL=http://mikamai.com" />

In order to direct this page to the user’s original URL, it was stored in a variable in the controller file, @url, in this case we will define it manually for readability:

@url = "http://mikamai.com"

Now, the URL can be dynamically changed, and we can swap out the static URL in the ’redirect.html.erb’ page for the @url variable:

<meta http-equiv="refresh" content="5;URL=<%= @url %>" />

The process of redirecting to the ’redirect.html.erb’ page is handled in the controller.


def follow
      respond_to do |format|
        format.html { render '/redirect' }  ## Renders the redirect.html.erb page
      end
 end

And thus, once a user goes to a shortened link, for example http://svel.to/1, an interstitial page will be rendered which after 5 seconds will redirect to http://mikamai.com.

I also added a simple countdown using pure JavaScript and the setTimeout function.:

var timer = 5,
countdownSpan = document.getElementById('countdown');

(function timeDown() {
    countdownSpan.innerHTML = timer--;
    if (timer >= 0) {
        setTimeout(function () {
            timeDown();
        }, 1000);
    }
}());

Some ways to improve Sublime Text (3)

Sublime Text is a fast, extensive, cross-platform text editor which is supported by a large open-source community and a library of plugins & themes. Here are some of the ways I’ve improved my version of Sublime Text:

The most essential Sublime Text plugin is Package Control:

This plugin will help you acquire the rest of the plugs I’ll mention later, and it’s simple to install. If you’re using Sublime Text 3 like me, open the console (View > Show Console) and paste the following:

import urllib.request,os,hashlib; h = '7183a2d3e96f11eeadd761d777e62404' + 'e330c659d4bb41d3bdf022e94cab3cd0'; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path();urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) ); by = urllib.request.urlopen( 'http://sublime.wbond.net/' + pf.replace(' ', '%20')).read(); dh = hashlib.sha256(by).hexdigest(); print('Error validating download (got %s instead of %s), please try manual install' % (dh, h)) if dh != h else open(os.path.join( ipp, pf), 'wb' ).write(by)

If you’re on Sublime Text 2, use this code:

import urllib2,os,hashlib; h = '7183a2d3e96f11eeadd761d777e62404' + 'e330c659d4bb41d3bdf022e94cab3cd0'; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); os.makedirs( ipp ) if not os.path.exists(ipp) else None; urllib2.install_opener( urllib2.build_opener( urllib2.ProxyHandler()) ); by = urllib2.urlopen( 'http://sublime.wbond.net/' + pf.replace(' ', '%20')).read(); dh = hashlib.sha256(by).hexdigest(); open( os.path.join( ipp, pf), 'wb' ).write(by) if dh == h else None; print('Error validating download (got %s instead of %s), please try manual install' % (dh, h) if dh != h else 'Please restart Sublime Text to finish installation') 

The next plugin I recommend is this Git plugin. It’s fairly self-explanitory: it adds Git traits to the text editor. With Package Control, installation is simple: open Package Control with the “⌘+Shift+P” keystroke, type ‘Install Package’, and select ‘Git’.

Third plugin I can recommend is ‘Sidebar Enhancements’. This can be installed similarly to the Git plugin. It adds a wealth of features to the bare default sidebar, of which can be seen below:

Fourth: Quick File Creator. This simple plugins adds the feature to create files with the command palette.

Fifth: SublimeLint – error highlighting.

Finally, Emmet – an incredibly useful plugin for any web developer. Emmet is an auto-completion engine for HTML and CSS code. Check out an example in this .gif:

Some useful keyboard shortcuts:

Show file in project: This shortcut needs to be added to Sublime, but it is one that I find myself constantly using. It will reveal the location of the current file in the sidebar. To map it, open your keymap file (⌘+Shift+P, search for ‘key bindings’), and add the following line:

	{ "keys": ["super+shift+r"], "command": "goto_symbol_in_project" }, 

Multiple cursors: Great for repetitive tasks. The keystroke is: ‘CTRL+Shift+Arrow Key’. This will allow you to add as many cursors as you want!

Close the current HTML tag: a great keystroke for web-developers: ‘⌘+Alt+.’

Theming

There are thousands of themes for Sublime, so it’s really down to your preference. I’m using the Soda theme, but you can find many more here!

The .uk TLD has arrived

At 8:00am on June 10th, registrars began to allow the registration of the .uk TLD for all. Previously, .co.uk and .org.uk were the most common used, and .uk was reserved mostly for government usage, such as police.uk or gov.uk.

In order to prevent domain-squatting, Nominet, the registry behind the .uk domain reserved all .uk domains that had an existing .co.uk counterpart until 2019. However, this still means that you need to pay for a new .uk domain if you own an existing .co.uk site.

The release of the domain has not been met with great enthusiasm. Low demand, increased consumer confusion, the devaluation of the .co.uk domain, and the fact that businesses are being pressured to move from the .co.uk domain through an increase of costs, create the perception that this move by Nominet is simply a 5-year-late money grab.

To purchase a .uk domain, I recommend using a third party registrar rather than Nominet such as namecheap or Gandi as these are both cheaper and faster.

With the exclusion of “.co”, comes the opportunity for more creative domains, check out http://dumb.domains for some inspiration.

Some WordPress plugins you should know about

I’ve compiled a list of some great WordPress plugins that you should know about and have in your toolkit:

Security

Akismet – the ultimate spam blocker. Keep in mind this plugin is not free, but is a must have if you plan to include commenting on your blog. Akismet will save you from a lot of worry.

AntiSpam Bee – a free solution to Akismet. This plugin uses a honeypot method to counter spam and is very successful.

iThemes Security (formerly Better WP Security – this is one of the most recommended WP security plugins. It comes with great features such as forced SSL, bot detection, 404 detection (this feature also helps with SEO), away mode (ability to turn off the login feature completely), and more.

WordFence security – Another security plugin and a competitor to iThemes Security. I find this plugin easier to configure than the previous, but it is also bulkier. Recently this plugin has caught up with many of the features offered by iThemes Security, and more, such as the ability to monitor users, so it’s mostly down to personal preference between the two.

WordPress Backup to Dropbox – Pretty self explanatory. A nifty way to handle WP backups.

Limit Login Attempts – another self explanatory plugin. This will block users (or bots) from brute forcing your WordPress site. Keep in mind that this feature is included in the security plugins I mentioned earlier, so is not necessarily needed if you’ve chosen to use of them.

WordPress Importer – this plugin is the easiest way to import posts, comments, pages, attachments, etc. into your WordPress site. Along with WordPress Backup to Dropbox, these plugins make for a simple version control system.

SEO

Yoast – WordPress SEO – SEO is something that is difficult to get right, but it can make a huge difference to your WordPress’ popularity.

No Follow – this simple plugin adds the option to include the HTML nofollow rel tag to links on your site. This infographic helps explains how and when to use the nofollow tag.

Misc.

Google Analyticator – this plugin enables the use of Google Analytics (GA). It really is a must have plugin, as GA is invaluable to a developer looking to improve the popularity of their site.

Advanced Custom Fields – a powerful custom field editor.

Gravity Forms – the most versatile way to handle custom forms in WordPress. Great for creating contact forms.

Integrity – this isn’t a WordPress plugin, but is an alternative to one (the less plugins, the less bloated your site is). Integrity is an OS X app that will search your site for dead links. Xenu Link Sleuth is a Windows alternative

(Physically) Printing with Ruby!

Recently, we were asked to develop an application that would silently print to a physical printer (in this case, a Zebra ZR203) on a Windows computer. The aim of the program was to use it to print coupons in conjunction with a touch screen computer.

One way we considered doing this was by using the Zebra Programming Language (ZPL) to create the label, connect the Zebra printer to the LAN, and sending it to TCP port 9100 on the printer. However, this method could get very messy when deploying the finished product to dozens of locations. We needed the setup to be as trouble-free as possible.

I found Foxit, a (Windows only) PDF reader, which conveniently allows for command line printing. Together with the great PDF generator gem, Prawn, I generated a PDF from the coupon PNG image:

Prawn::Document.generate("coupon.pdf", :page_size => [225, 1132], :margin => [0,0,0,0]) do |pdf|
    pdf.image("coupon.png", :fit => [225, 1132])
end

and executed a system command using Ruby’s “system” command:

    system(""C:\Program Files (x86)\Foxit Software\Foxit Reader\Foxit Reader.exe" /t "coupon.pdf"")

Of course this command depends on the install location of Foxit, but Program Files (x86) is the default location. This command will print to the current default printer, but you can specifiy a printer by appending its name to the end of the command like so:

   system(""C:\Program Files (x86)\Foxit Software\Foxit Reader\Foxit Reader.exe" /t "coupon.pdf" "#{printerName}" ")

Finally, we had this small application running locally with Sinatra, and had the frontend perform Ajax GET requests to the backend:

$.get('http://localhost:4567/print', (data) ->)

And that’s it!

Showing bulletpoints in an inline unordered list [CSS, HTML]

When displaying an unordered list () as inline, you will lose the bullpoints. For times when you want to create a horizontal list with bullets, you can use a non-repeated background image, and positioning them next to your list items using CSS. I’ve included a JSFiddle at the end of this post.

Creating the HTML list

<ul>
<li><a href="#one">One</a></li>
<li><a href="#two">Two</a></li>
<li><a href="#three">Three</a></li>
</ul>

CSS

Set the unordered list’s margin and padding to 0, and remove any bullet points that might appear.

ul {
margin: 0;
padding: 0;
list-style-type: 0;
}

To create the horizontal list, set the list items to display inline. Add the bullet image using background-image (I’m hosting an example bullet on Imgur for now), set to no-repeat, position it using background-position, and give it a left margin:

li { 
    display: inline;
    background-image: url(http://i.imgur.com/qWICm4M.jpg);
    background-repeat: no-repeat;
    background-position: 0 .4em;
    padding-left: .6em;
}

Click here for a JSFiddle demo

Optimizing performance in PhoneGap

PhoneGap is an open-source application framework designed to bridge the gap between multiple mobile development devices. The result is an efficient and simple way to create hybrid mobile apps with a common codebase.

Developers create the HTML, CSS, and JavaScript files, and PhoneGap (powered by Apache Cordova) creates the rest.

One common issue that arises with PhoneGap (and other broad application frameworks) is related to its performance.

Some tips to increase performance include:

Removing (JQuery) animations

Transistions and animiations have a considerable effect an app’s performance. One alternative to JQuery animations is pure CSS animations. By default, 3D CSS animations will be hardware accelerated, but you can force hardware acceleration on 2D animations by adding this CSS rule:

 -webkit-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);

Ajax loading

Favouring Ajax loading will reduce the stress on the processor. If you prefer otherwise, I suggest using the great HTML5 feature ‘prefetch’ to silently load pages before a user requests them:

link rel="prefetch" href="http://dev.mikamai.com/post/79398725537/using-native-javascript-objects-from-opal" /

Consider some external libraries, but avoid JQueryMobile

JQueryMobile has a bad reputation at the moment. It’s large, bloated and slow, and the documentation isn’t great. An alternative to JQM is Sencha Touch. Unlike JQM, Sencha is not designed to work on both desktop and mobile, which makes the library smaller and more optimized for mobile devices. One thing to note about Sencha is that it is not free, so you should expect initial expenses when developing your app with Sencha.

Note: For a great Sencha + Phonegap guide, see here.

Another useful library I can recommend is FastClick. This will remove the horrible 300ms delay (used to detect double tabs) when pressing a button, following a link, changing pages etc. It will make the application feel a lot smoother.