A blog by the Brick Factory The Brick Factory
Injection attacks are still the number one security vulnerability

How to Protect Your Code Against Injection Attacks

When I started working with PHP years ago, the first thing I did was go online and try to find tutorials. I worked with someone who also did PHP (and was the primary driver for wanting to learn the language), but finding out how to do things on my own fit better into my schedule. Eventually I got to working with databases, and the tutorials I found looked like this:

This is perfectly valid code. In fact, if you look at a lot of examples today you will see the same thing. There’s a huge flaw in these examples, and one that has given PHP a bad name when it comes to security. It isn’t the fault of the language but of the way that many developers learned how to do things. PHP makes it easy to shoot yourself in the foot and it doesn’t help that developers keep showing new developers how to do it. Get gun, point at foot, pull trigger. That’s essentially what the above example is showing you.

So, what is so wrong with the example code? The problem is that we aren’t validating anything. Do we know what $_GET['id'] actually is? What happens if $_GET['id'] is set to something that isn’t an integer?

When mysql_query() runs it will return false. Depending on how well your code handles a false return, someone screwing around with the query variables will learn that we didn’t properly make sure that the id query variable is being checked. At the very least they learned that changing query string parameters does cause the code to change. Depending on the setup of our code, it might even expose what database we’re using. If it’s MySQL, they can get crafty and do something like this:

That little OR 1=1 bit will cause the SQL server to return all of the data in the user’s database. Let’s take this a step further, and say that we are authenticating a user. Most of the examples would look like this:

We’re doing one thing correctly (forcing this data to come through the POST array), but we’re still not really validating that $username or $password are actually good valid values. We can still do the following:

We’re in, and as a user where we didn’t even know the password. Why? The -- will comment anything after it, so we dropped the AND password= portion of the SQL and do the select based on just the username. It will return a single value just like the code will expect, so your code never knows that it was altered.

Both of these attacks are called “SQL Injection Attacks”, and is part of the OWASP Top 10’s #1 attack vector. The sad thing is that these are really easy to combat against. I see all the time on Reddit and Stack Overflow people asking for help and seeing this same sort of code. In 2013 we should have been able to stop this, but with years of old tutorials out there it is an uphill battle.

The reason that it sad to see this as still the #1 attack on OWASP is that it is easy to combat. The first and foremost is to stop using the mysql_* functions in your code. The module that handles those is old, and it doesn’t support the best way to handle SQL injections. Yes, it has mysql_real_escape_string(), but that relies on the developer remembering to use it. Better security comes from the developer having to not remember to do it and it just being built in.

Since PHP 5.0, PHP has shipped with something called PDO. PDO is a database abstraction layer that makes it easier to write cross-database code. If you write your app for MySQL, you can more easily port it to something like Postgres or MSSQL by doing nothing more than changing the connection parameter (assuming you haven’t written any engine specific code like using LIMIT, which MySQL and Postgres support but MSSQL doesn’t).

PDO has another big advantage in that it has support for something called a Prepared Statement. With a prepared statement, the SQL query is parsed by the engine by taking a SQL statement and a list of parameters and putting them together itself instead of relying on a fully built SQL statement. This becomes much safer because the DB engine does all the work on properly quoting the values coming in. The side effect of this is that the worry about the developer being safe is offloaded somewhere else, so by using PDO and prepared statements the developer doesn’t need to worry about if a parameter has been sanitized.

Let’s go back to our first example, with the $_GET parameter. What would this look like with PDO?

It’s a bit longer, but not so much that that there is a ton of extra work involved. What we did was create an SQL statement using placeholders, which in PDO can either be a ? or named like our example, which was :id. We run our SQL through the prepare() method on our PDO connection, which returns a statement object. This statement object gets executed, and at the same time we pass in the values for our placeholders. We can then get the user by calling the fetch() method on the statement.

We can rest assured that the SQL code is now safe from injections. That’s it! That is the single most effective way to combat SQL injections.

For older legacy applications switching out to PDO can be a major undertaking. Drupal did this in Drupal 7, where they replaced their underlying database abstraction layer to use PDO. Drupal didn’t use the database specific functions all over the codebase which made it somewhat easier to swap out, but if your application is riddle with calls to mysql_* or pg_* functions you will want to replace them all with PDO commands.

Do your part to help clean up the bad examples out there. If you ever do new code, use PDO. If you ever give examples, do it using PDO. Maybe we can make the internet a little better, and help knock SQL injections (and other injection types) off of the top of the OWASP Top 10.

boxer_top

Brick by Brick, Round 2

It used to be that when you launched a new website you would have two to three years before the design started to feel dated.  Given how quickly things are moving now, a design can start feeling stale after as little as six months.  The battle against dated design is constant.  While its design was only sixteen months old, we had gotten really sick of the design of our blog, Brick by Brick.   We needed a change.  So today we are pleased to launch a new version we think is a huge step forward (see a before and after here).  Following is a breakdown of the primary improvements we made.

Readability

I’m stating the obvious here, but your blog should really be about your content.  The design should get out of the way and let the posts be the star.

Our primary focus in redesigning our blog was to better showcase the content itself  by increasing readability.  To achieve this we:

  • Switched our primary font to Georgia.   We chose Georgia because it works well with the font used in our logo (Avenir), is a pleasure to read, and isn’t used on every site on the web like Arial. I think it adds a bit of elegance to the blog.
  • Jumped on the big type bandwagon and upped the sizes of our fonts throughout.
  • Switched from full justification of text to the justify left, ragged right style.  Full justification is more elegant and looks better on first glance, which is why it is still the dominant approach in book publishing.  Left justified, ragged right is easier to read online and has a bit more of an informal look, which we thought appropriate for our blog.
  • Changed to a one column layout.  Our previous blog had a sidebar with a list of recent posts and a subscribe box.  We found that very few people were clicking on any of that stuff, and going to one column gives us room for larger images to accompany our posts.

Illustrations

We have a talented team of designers that we frankly don’t utilize as much as we should on our blog.  To rectify this we decided to have our design team develop quick illustrations to accompany most of our posts.  They did the illustration for this post, as well as for this one and this one.  I love them.  I think they really add something to our blog.

Responsiveness

Our new blog is completely responsive, so that the layout adjusts along with screen size.  This means it looks great on a desktop, tablet, or mobile phone.  Nearly all the sites we are building now are responsive to some degree, so it made sense that our own blog would be.  We think this is how sites will be designed moving forward.

Let us know what you think.

Unit Testing In Drupal

PHP is a language that traditionally has not had unit testing as part of the development process. A large part of that was that way back when, there just weren’t any good tools for doing testing. Another major factor is that many of the learning resources for PHP do not mention doing things like unit tests, which is a major contrast to languages like Ruby. I personally think this has helped lead to the notion that PHP code is much harder to maintain than other languages.

PHP is nearly 20 years old now, and today we have the tools to do proper unit and functional testing without having to go through the pain of writing those kind of systems ourselves. At The Brick Factory, we tend to use the Drupal CMS quite a bit, and thankfully Drupal has a proper testing system built right in.

(more…)

rolling_momentum_buzz

Possibly The Greatest Article About Headline Writing Ever Written

With the rise of social networks like Twitter, Facebook and Pinterest the way content is discovered has changed dramatically the last few years. If you want to be successful, your content strategies have to evolve along with the discovery mechanisms.

From a content creation standpoint, one of the things that has changed the most the last few years is the the headline.

When I first started writing blog posts ten years ago I treated the article headline as an afterthought.  I’d spend hours on a blog post and then approximately thirty seconds on the headline.   As I got a bit more savvy I started writing keyword-rich headlines with search engines in mind.

As Facebook and Twitter have taken off, my focus has evolved further.  Facebook and Twitter users are barraged with hundreds of posts/links a day and make the decision on whether to click or not in just a few seconds.  To succeed in this competitive environment you have to make your headline click-worthy.  A headline has to grab readers attention and compel them to click.  A click-worthy headline is a way of pushing the snowball down the hill.

One media company that gets the importance of headlines is Upworthy.  Upworthy requires writers to draft 25 headlines for every single article.  They then test the headlines to see which ones generate the highest click rates and use that as the permanent article headline.  All the effort pays off.  Upworthy has found that “an item’s traffic can differ by as much as 500 percent simply because of the headline.”

Here are some examples of click-worthy headlines I found on Upworthy today:

The thing about these examples is that the content isn’t necessarily click-worthy in and of itself.  These aren’t listicles or articles about cute animals or Ryan Gosling.  These are pieces about immigration, the plight of our schools and poverty.  Great headlines are what make you want to click, not necessarily the subject matter itself.

As I work to improve my own headline writing, I’ve found these two simple tips to be helpful

  1. I consciously think about what all the headlines I write will look like when I post them to Facebook and Twitter.  I still consider search engines, but my headlines are now written primarily for social networks.  As a result, my headlines have gotten a bit more casual and tongue and cheek.
  2. I make myself write ten headlines for every article and take my time in choosing which one to use.  I haven’t gotten to the point of doing testing like Upworthy does, but by taking the time to brainstorm my options I’ve found the quality of my headlines has improved and I’m seeing more clicks (and shares).  I’m no longer just using the first headline I come up with or writing exclusively for Google’s bots.

I’m still not a great headline writer, as evidenced by the headline to this article.  But by giving more thought to the headlines I’m getting a bit better every time out.

stone_wide

Pounding the Rock: Lessons from the San Antonio Spurs on running a great digital campaign

I grew up in San Antonio and like everyone from there I’m a big fan of the San Antonio Spurs. Since drafting Tim Duncan in 1997, the Spurs have gone on an unprecedented run, winning four NBA titles and more than 50 regular games each season for the last thirteen years.  Led by their cranky coach, Gregg Popovich, the Spurs are celebrated for their unselfishness and commitment to team.

The following quote from Dutch American reformer Jacob Riis hangs in the Spurs dressing room and serves the team’s unofficial motto:

“When nothing seems to help, I go and look at a stonecutter hammering away at his rock perhaps a hundred times without as much as a crack showing in it. Yet at the hundred and first blow it will split in two, and I know it was not that blow that did it, but all that had gone before.”

In the context of basketball, the quote is an obvious call for players to put maximum effort into everything they do.  Winning an NBA title is the culmination of years spent taking jumpers in the gym when no one else is watching.  To be great you have to pound the rock.

The quote is also an accurate description of what it takes to build and maintain a great digital program.

There are tons of organizations that want a great, successful online campaign but don’t want to put in the work.  The truth is there really aren’t short cuts.  The truth is that building websites and running digital campaigns is hard work that requires a significant commitment.  A successful web program isn’t the result of one transcendent idea so much as it is hundreds of small ideas implemented well.

To be great you have to write compelling content every week, and preferably every day.

To be great you have to optimize your email messaging and design.

To be great you have to make sure your website works in all browsers (even IE) on all devices (desktop, tablet and smartphone).

To be great you have to experiment.

To be great you have to test and then test some more.

To be great you have to pound the rock.