Thursday, May 16, 2013

Prevent SQL Injection Attacks In WordPress


sql injection wordpress Prevent SQL Injection Attacks In WordPress
SQL injection is a very popular technique to hack into database of a website by using incorrect user input with unescaped characters. It occurs when developer designs a bad database layer for an application. In WordPress, the database layer is $wpdb class, which is well-designed for this purpose. This class and WordPress itself have some built-in functions to help developers get rid of any SQL injection attack.

All these functions can be divided into 2 groups: input validation and query preparing.

Input validation functions

The input validation functions are useful when we need to take the right value from user input. They include:
esc_html($input): for getting plain text. This function will escape all HTML entities. The difference from PHP built-in function htmlspecialchars() is that htmlspecialchars() will double encode html entities if run twice.
wp_kses($string, $allowed_html): for getting HTML string. This will remove all unwanted HTML tags. You can read more about it at the Codex.
esc_url($input): for getting url. You don’t need to use regular expressions to check the url anymore. This function will do everything for you.
is_email($email): for checking email address.
intval($input): for getting integer. This is built-in PHP function.
There’re more validation functions that you can see at the Codex.
After getting the right values, you can now work with them, but it’s not enough to use them in SQL queries. We need to escape them before pass into the query string.

Query preparing functions

Before query the database, make sure that the query string is escaped. This is can be easily done by using WordPress built-in functions: esc_sql($query) or $wpdb->escape($query).
They will escape a single string for use in a SQL query. Basically, they’ll add slashes to single quotes, double quotes. They’re very similar to PHP addslashes() function. If you really need a version of addslashes(), you should use the WordPress built-in function addslashes_gpc(), it will check the magic quotes is set or not before adding slashes.
These function work will fully query string. That means the query string should contains all needed variables. For example:
  1. $query = $wpdb->escape("SELECT * from $wpdb->posts WHERE post_id=$id");
As you see, $id are passed directly into the query string. It is ok when all these variable have been escaped using functions that I mentioned above. But sometimes, you want a higher check for the data type of these variables. That’s when we need to use $wpdb->prepare function:
  1. $wpdb->prepare($query, (scalar) $value1, (scalar) $value2, ...);
where $query is a sprintf() like format string. It only understands %s (string) and %d(number), neither of which needs to be enclosed in quotation marks. Note that all values must not already be SQL-escaped.
For example, to get a comment from a known user, we can use the following code:
  1. $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_ID=%d and comment_author_email=%s", $id, $email));
Now, by using data validation functions and some escape functions for preparing SQL query you can work with the database without worry about SQL injection attacks, your code is protected! Here is the sample code of the process:
  1. $data = esc_html($_POST['data']);
  2. $result = $wpdb->get_results($wpdb->prepare("SELECT * FROM table WHERE field=%s", $data));
For better performance and compatibility, you should use built-in query functions of $wpdb class. All of them are well-documented at the Codex.

WordPress Security Tips To Protect Your Website


WordPress Security Tips To Protect Your Website 

WordPress is the most popular Content Management System in the world, used by more than 60 million people around the globe. WordPress hosts more than half of the blogs itself. The popular CMS is used by huge companies and associations in the world such as TechCrunch, NBC, CNN, CBS or the National Football League of the US. There are more than 2.5 billion WordPress pages in the world, read by more than 300 million people daily, while around 500.000 new posts and 400.000 comments are posted each day.
widely used WordPress is. WordPress doesn’t show signs of slowing down either, so expect these numbers to increase dramatically in the near future. Therefore we also need to learn how to protect ourselves, because there is no popular web technology nowadays not targeted by hackers and robots.
Today I will talk about tips, tricks and plugins to keep your WordPress blog safe from hackers and robots. This doesn’t mean you have to do all of them, but using as many of them as possible is recommended.

1. Always Update

Keeping your WordPress updated all the time is important, because the developers work to solve security issues as well and if they release an update, it is a good idea to update. It takes only a few seconds, is safe (because WordPress backs up your data before actually updating, so you can’t lose anything) and will help your blog run better and be compatible with more plugins too. When you update, do it through your dashboard or if you want to do it manually, do not download the update from another site than WordPress.org.

2. Strengthen your password

Now this shouldn’t be something new to you. If you’ve been on the internet for some time you know strong passwords are recommended. Include small and capital letters, numbers and different symbols to make your password not difficult, but impossible to guess. Once somebody has full access to your blog, it’s not yours anymore!

3. Keep an eye on file permission

It is a good idea to keep an eye on the file permissions. You have a link at the end of the article with a guide about what file permissions are and how should they be used. You can set file permission with FTP clients and FileZilla works just fine, so I recommend it.

4. Use .htaccess

The .htaccess file is available by default in your hosting folder. You can use this file to block different IPs and you can learn how to do this by following the links at the bottom of the article.

5. Use SSL Encryption

SSL Encryption is used for encrypting data your blog sends. This means that nobody accessing your router can intercept the data you use, such as account credentials. This way your data is not only really difficult to intercept, but also to decrypt. The bad in general is that you have to pay for having an SSL encryption, but most of the services out there do a tremendous job and also help you set up the SSL server. However, for WordPress SSL encryption is free and you only have to add this particular line to your wp-config.php:
define (‘FORCE_SSL_ADMIN’, true);

6. Always Back-up

Backing up once a week is something I would like to recommend as well, because no matter how much you protect the blog, anything can happen. There are things you can’t even do anything about (like the host servers getting hijacked – which doesn’t really happen too often, but it is a possibility) and it is good to have a back-up which you can install again right away.

7. Protect the wp-config.php

This is one of the most important files in your WordPress folder, therefore you really have to protect it. You can hide it from public view by inserting few lines of code into your htaccess file:
order allow, deny
deny from all
This prevents the wp-config.php file from being seen by public users and makes it therefore more difficult to spot for hackers and robots.

8. Never use “admin” as login

A common mistake is to use “admin” as the login username. When you install WordPress, right after the process is done create a new account and use that one as default. The “admin” account is quite dangerous to use because all the robots go for it.

9. Use an SFTP

Most of the time people upload files by using FTP, but you could use a Secure FTP (SFTP) so that the files you send are encrypted. You can find a detailed guide about how to do this here.
Now we move onto plugins you can use to secure your WordPress.

1. Login Lockdown

You can use a plugin called Login Lockdown, but make sure you remember your password. Login Lockdown registers every failed login attempt and the IP of the person, and blocks the ability to login for a range of IPs if the number of failed logins exceeds the number you set. As a default setting, the plugin locks down IPs for an hour after 3 failed logins within 5 minutes. The IP addresses which have been blocked can be removed from the plugin panel in the WordPress dashboard.
9 WordPress Security Tips To Protect Your Website From Harm
Login Lockdown protects your WordPress login page from people trying to guess your password.

2. WP-DB-Backup

I told you earlier you should have backups for your database all the time. This is the plugin that I use for this purpose. It sends you backups on your e-mail or can also store them on the server. You can also set how often you wish the plugin to back up your data.

3. WP Security Scan

Removing the version of WordPress you have should be a basic option, but WordPress makes it difficult. Therefore you need to use a plugin to remove the version of WordPress from the header of your PHP page. Why? Because knowing which version you have means hackers know the security issues you have, therefore this makes it easier for them to hack you.
With all these plugins and tips being listed, I only wish to tell you that WordPress, although very popular and widely used, is threatened all the time by hackers and robots. WordPress security is something that has been discussed long and you should take a look into it, because finding out your blog is hacked and having no backup is definitely not fun. Try to avoid this by backing up regularly and following my tips and you will find yourself less often in troubles.

Wednesday, May 15, 2013

How To Improve WordPress Security & Protect wordpress Blog From Hackers


If you haven’t done anything to improve WordPress security then you have never had to learn the hard way.
I learnt the hard way a couple of years ago when I woke up to find one of my authority sites had tanked out of the SERPS losing out on 10,000 visitors a day.
That equated to nearly a $12,000 / £8,000 loss in affiliate commission…
After a bit of investigation it turned out someone had hacked the blog and created thousands of spam pages hidden from normal view and turned it into a cloaked link network.
That was enough for Google to slam the site even though it looked perfectly fine to the naked eye, even when logged in as admin!
It took me a few days to undo the damage due to my lack of backups (they injected C99MadShell code into every file) and a further 3-4 weeks for the recovery in Google.
All of this could have being avoided if I had just spent 10 minutes improving the security of the blog.
The irony is I had read and ignored plenty of articles just like this one ^^
WordPress it is a prime target for hackers no matter how big or small your site is. Check out the latest threats here and you’ll see what I mean.

What You Will Learn

  • How to improve WordPress security
  • How to protect against hackers
  • How to automate backups free of charge
  • How to scan your site for malware
  • How to automatically monitor your site

Automatically Backing Up Your Site

First things first – make a backup of your site right now!
Having regular backups makes it easy to recover from hacks – in fact you can restore your entire site in just 1 click.
It is also handy to make a backup before making any significant changes to your site such as installing a new plugin or upgrading WordPress.
My host does this automatically for me and provides a great control panel but if your host doesn’t then don’t worry.
There are many paid backup plugins available but all you need is the free BackWPup plugin.
This will back up your site, the database and all of the files including everything in WP-Content into a single zip file.
It will then automatically upload the file to an FTP server, Amazon S3, Dropbox, SugarSync or a bunch of other services.
You can even setup a dedicated free Gmail account and get the plugin to email the backups to you! Gmail is great for storing your site backups!
Install the plugin and ensure you are doing daily backups!

Remove WordPress Version

By default WordPress will tell you which version of the software it is running in the source code.
The problem with this is when hackers discover a vulnerability it makes it very easy for them to get a list of blogs running the vulnerable version to attack.
To remove it, just login as admin and go to Appearance > Editor > Functions.php and add this line of code at the end before the closing ?> tag-
remove_action('wp_head', 'wp_generator');

Block Directory Browsing

Usually if you browse to a specific directory you can view all of the files in that folder, just like when your browsing through files and folders on your computer.
To stop the server from listing the files in a directory you need to add 1 line to .htaccess
Open up the .htaccess file in the root of your site (where the wp-config.php file is) and add this line-
Options -Indexes

Update WordPress & Plugins

New hacks and vulnerabilities are discovered all the time which is why it is important to keep up to date with both WordPress and plugin updates.
Make sure you keep both updated regularly!
It is also a good idea to make a backup of your files and database before updating anything just in case it breaks!

Delete Unused Themes / Plugins

While unused themes and plugins don’t interfere with your blog directly, if the plugin or theme is hacked (there are thousands of these in the official directory) then hackers can still access it.
So if you have any unused plugins and themes, delete them! This will not only improve security but help to speed up your site as well.

TimThumb Vulnerability Scanner

TimThumb is a popular script that is used by a lot of themes to resize images for thumbnails and so forth.
The only problem is this script had a huge bug which left the door wide open for any hacker.
The other problem is this is used by a lot of themes & plugins, meaning they come with a built in hacker friendly back door.
This is the back door that was used to hack my authority site.
To check if your theme is at risk, install the TimThumb Vulnerabiltiy Scanner.
That will scan your blog for any old versions of TimThumb and allow you to update them in one click if you need to!
You can uninstall the plugin once you have done that.

CloudFlare

CloudFlare offers a free service that helps to protect and speed up any website.
This actually works on the DNS level and helps stop hackers in their tracks before they even reach or see your site.
Here is how it works-
It only takes a few minutes to setup and will offer decent protection. There are paid options available but you won’t need those for the most part.

Install A Security Plugin

As well as the tips above you can improve WordPress security and protect from hackers by installing a plugin.
The Better WP Security plugin helps to protect your site in a number of ways-
  • Removes the WordPress version
  • Changes the URLs of the login and dashboard pages
  • Renames the default admit account
  • Changes the WordPress database table prefix
  • Removes login error messages
  • Protects your sites from hacks
  • Scans your site for vulnerabilities
  • Automatically bans bots and hackers
  • Improves server security
And a whole bunch of other stuff! It does also have an automatic backup option but this only backs up your database and not your files, so please see the separate backup section for that!

Install A Firewall

Alongside a security plugin you also want to install a firewall that will block any attacks from SQL/Java injection.
The OSE Firewall plugin has you covered!
The combination of the firewall and the Better WP security plugin is a great setup!

How To Monitor Your Sites Security

There are a number of free services we can use to monitor our site for hacks and downtime.

Sucuri Sitecheck

The first one is the Sucuri Sitecheck scanner which will check lots of URL’s across your site for a range of threats.
This covers everything from malware to checking if your site is blacklisted anywhere.

Pingdom

The free account at Pingdom will check your site every minute from a range of locations.
You can get notifications of downtime via email, sms, Twitter, iOS or Android which is very handy indeed!
In fact if you manage a bunch of site the Pingdom mobile app is fantastic – I highly recommend it!

Change Detection

The Change Detection service is simple in function but amazingly handy!
All it does is monitor pages for changes and if a change is detected it sends you an email!
You can use it to make sure your alerted of any changes to your site. It’s also great for checking when popular items are back in stock on websites ^^

Have You Improved Your Blogs Security Yet?

For your own sake please do not ignore the advice in this article.
You do not want to learn the hard way like I did – heck I didn’t have the basics of regular backups in place when I was hacked!
If you don’t take this issue seriously you will have problems in the future.
It doesn’t take long to seriously beef up the security of your site, so what are you waiting for?
Don’t regret ignoring articles like this like I did! Take action NOW!

Thursday, April 4, 2013

Debugging a PhoneGap


When I had my first run-in with PhoneGap, I was furious with the lack of debugging facilities. I mean sure,XCode provides adequate tools for debugging Objective-C code, but the JavaScript running in the UI window cannot be debugged.
The official documentation says that if you wish to debug your UI code, you should load it as a standalone in a browser. Of course this has certain drawbacks. One is that the UIWebView, the iOS component that PhoneGap uses to display your UI, behaves slightly differently than the mobile Safari, and even more differently than the desktop one. The other problem is that you won't have access to the native PhoneGap plugins.
If your application is complex enough, it will be a single, complex entity, with native and JavaScript code leaning on and intertwining each other. That is what has happened with our ebook reader too, the books were extracted from their containers by the native code. The interdependence was simply far too high to debug the JavaScript as a standalone.
We were having trouble with a blocking issue that did not appear in unit testing of either the JS or the native code. We were on the verge of giving up, when we found out about the…

Secret UIWebView debugger!

The iOS simulator included with XCode in fact contains a javascript debugger and DOM inspector(basically the Safari developer tools) for UIWebViews, but it is unreleased. There is no checkbox or menu item you can use to activate it. However, you can enable it from code through a secret ninja technique.
We are going to reach behind the public API. Neither the class nor its method are published through header files, so we will use the NSClassFromString function to get there. If you are familiar with the concept of reflection from managed languages, this is something similar. It gives you access to a class based on a name given in a string.
[NSClassFromString(@"WebView") _enableRemoteInspector]; 
This is the line you need to run when your application starts. The best place to put it is in the "didFinishLaunchingWithOptions" method in AppDelegate.m. (You can find this file in the Classes folder of your project.)
Note that the compiler will issue a warning, since the method you use is not declared in a header you included. However, due to the "duck typing" nature of Objective-C, the code will compile, and since the method does exist, will run correctly.
1-Running
Now what this does is slightly obscure, as you will find no changes from before when running the application. You need a little ninja finesse even to access the debug facilities. What has happened is that the iOS simulator has opened a port for access by a browser.
Open localhost:9999 on a browser, and you will be presented with a rather plain selection between theUIWebViews present in your application. If you are using PhoneGap, chances are there will be only one.
2-select
After clicking it, you will be taken to a developer tools window, similar to the one built into Safari. If you have debugged JavaScript in a browser already, you will be familiar with how this works.
3-debugger
Happy debugging… Just make sure to remove this code from your app before submitting it to the App Store, or else it will certainly be rejected without fail, for using nonpublic calls.

The PhoneGap DebugView

Another "secret" debugger is the DebugView included with PhoneGap. It dumps verbose debug messages on the output console while running. Note that this should also be removed from the application before submitting it for review.
First, you need to locate the code, which is NOT included by default with the new PhoneGap project. Navigate to the PhoneGap library root (for me the installer created it at Documents/CordovaLib), where you will find a folder named "debugview" under "Classes".
Take this folder, and copy it under your project. If you wish to abide by Objective-C conventions, this belongs under the Vendor folder, as it is third-party code you integrate as source into your project.
4-debugview
However, just compiling it into the project isn't enough, you will need to use it to replace the default PhoneGap view object. You can do this by overriding the newCordovaViewWithFrame method inMainViewController.h, as shown in the image above.
You need the following code:
- (CDVCordovaView*) newCordovaViewWithFrame:(CGRect)bounds
{
   return [[CDVDebugWebView alloc] initWithFrame:bounds]; 
} 
Note that in the image above, I defined a preprocessor variable for turning this on and off. The result? It dumps each and every JavaScript exception and some other debug data to the output window. This can be mighty misleading, so be careful! Not all exceptions are errors, many JavaScript libraries use handled exceptions to determine browser capabilities, for example.
Example snippet of its output:
2012-08-01 01:54:17.985 eBookReader[5983:13403] JavaScript exception: (obj-c):1 - ReferenceError - Can't find variable: cordova
Function name: '(null)' Line: 'cordova.fireDocumentEvent('active');'
2012-08-01 01:54:18.007 eBookReader[5983:13403] JavaScript exception: (obj-c):1 - ReferenceError - Can't find variable: cordova
Function name: '(null)' Line: 'cordova.fireDocumentEvent('active');'
wait_fences: failed to receive reply: 10004003
2012-08-01 01:54:18.965 eBookReader[5983:15203] JavaScript exception: (www/js/libs/jquery.js):5187 - SYNTAX_ERR - SYNTAX_ERR: DOM Exception 12 
To be honest, we didn't benefit much from using this component, but in certain cases, it can most certainly be useful. What did help us a LOT however, was...

Using the PhoneGap event handlers to catch errors

When developing the book reader, we were faced with an inexplicable error upon an iFrame being opened. Debugging through the JavaScript didn't yield any result, and neither did placing breakpoints in the plugin code.
What eventually solved our problem was the event handlers in MainViewController.m. This class contains the event handlers for the application, even though most of them are commented out by default, as the handler implementations themselves reside in the superclass.
Uncommenting these methods can serve two purposes. Either you wish to implement custom logic, or you wish to place a breakpoint. And this is what we did. The method names speak for themselves:webViewDidStartLoadwebViewDidFailLoadWithError, etc.
Placing breakpoints here, you can follow the very heartbeat of the PhoneGap application, and catch any error that occurs outside the JavaScript code, or the plugin code you are more familiar with.

Wednesday, April 3, 2013

phonegap 10 tips


1 – Never use JQuery library for your Next Phonegap App. It’s a hell of a job make things work, specially for loading content, the side effect is you’re using chuncks of code for IE, Opera, Safari and a bunch of other __prototype__ you don’t need it at all.
My suggestion is use ZeptoJS. Tiny, fast and ultra lightweight lib, and you just load what you need, targeting webkit child-browser. The syntax is very similar to jQuery and works like a charm, supporting even gestures out of the box.
2 – Never use file:/// to load local files in your Phonegap Apps, instead, use $.ajax(), better transverse XMLHttpRequest then loading files directly into DOM without pitfalls of loading.
And when doing so, disable async, otherwise browser will pimp or flicker specially if you’re in iOS.
Other thing to mention is the access Origin, if you’re just like me, use * for all website to request.
3 – Use as much as possible @media queries, there’s a bunch of tutorials and materials out there who can teach you exactly your needs. This is a very good point for multi-device density. And never forget to use images by screen dpi as well, otherwise your App is floated with dpis not used.
4 – For Android Developers, always clear the content of your App first then delete the App from the device, before you generate another version to your device, PhoneGap always cache the content of loaded files and you will be failing if you’re trying to fix some bugs on meantime.
5 – Use only the device capabilities you need it, Specially if you’re in Android and by default the ./create methods enables everything by default, you might be scary your user if all available capabilities are in use.
6 – Test your code in Chrome, Since uses the lastest webkit approach, you will need it to emulate your content and test media queries.
7 – Continuing with the testing code approach, Forget about Emulators when you’re designing the UI, you don’t need them for creating UI and workflow. You just need to fire up a Emulator when you need to test device capabilities like Camera, Mic. Even if you need GPS you Chrome serves very well those things.
8 – DRY (Don’t Repeat Yourself), Use AngularJS for the databinding, very usefull for Mobile developers. But if you’re a good MVC fan, BackboneJS is there for it.
9 – For Blackberry developers, use their own API for Media, PhoneGap API for Media is slow on BB6 devices, works awesome on BB7, specially playing local files.
10 – For iOS developers, Keep in mind for big density, so do a very well elaborate images for those devices, otherwise the Apple’s team will reject your app if graphics are poor. “Trust me, they will”.