Posts tagged ‘Security’

A Sobering Post About Code Review From Microsoft

It’s easy to get on the code review band-wagon, and tout it as the “silver bullet” for bugs, or the key to developing awesome, elegant software, etc.  It’s easy to get carried away, and forget that code review should probably be accompanied by rigorous testing, static analysis, and security integration from day one.

While the purpose of this blog post by Shawn Hernan from Microsoft may be to attack or question the merits of open source software, I see it as an interesting discussion on the role of code review in software engineering and how it relates to writing secure code.

Insert your own joke about Microsoft security here.  I, personally, think their IE team should read Shawn’s post.

Particularly interesting is one of the comments to the post by “danclarke_2000″:

I think another point is diminishing returns of code review..  Each extra code review brings less value than the preeding; review comments can already be known and awaiting action, not important enough to change etc

having extra eyes reviewing code means generating extra code review output.  Here is the true cost, all the code review comments of the many eyes have to pass through the bottleneck of the few people who have authority to make changes.  As each extra review has less value, processing the extra reviews has a higher and higher opportunity cost.

Sound kind of familiar?

Anyhow, Hernan’s post is an interesting read.  Click here to check it out.

UPDATE:

Here’s a quote from Joshua Bloch of Google on a similar topic:

…We programmers need all the help we can get, and we should never assume otherwise. Careful design is great. Testing is great. Formal methods are great. Code reviews are great. Static analysis is great. But none of these things alone are sufficient to eliminate bugs: They will always be with us. A bug can exist for half a century despite our best efforts to exterminate it. We must program carefully, defensively, and remain ever vigilant.

Read the entire post here.

Fiddling Around with Skype

As I said last week, I’ve been working with a partner (Mohammad Jalali) on a project for our networks course.

The idea:  given an arbitrary IP and port number, we want to find a way of determining whether or not there is an FTP server, an HTTP server, or a Skype node on the other side.  FTP and HTTP are trivial – those protocols essentially announce themselves to the world.

Skype clients, on the other hand, act a little more strangely.  Skype goes out of its way to hide its traffic – from straight-up encryption, down to making their client executable really hard to reverse engineer.  Because of this, Skype has been an interesting challenge to the hacker community.

Anyhow, my partner and I have learned a few interesting things about Skype – and in particular, we’ve found a reliable way to determine whether or not Skype is running behind an arbitrary IP and port.  Cool.

Fact 1:  Skype pretends to be an HTTP server

I’m serious, it does.  Using Wireshark, we noticed that both UDP and TCP packets were being sent to one particular port.  Pretty funny behavior…so, we took a closer look.  And this is what we found.  Pop open your Skype client, connect to the network, then use nmap to find the ports that Skype is using:


$>nmap localhost -p10000-50000

Starting Nmap 5.00 ( http://nmap.org ) at 2009-12-01 20:33 EST
Interesting ports on localhost (127.0.0.1):
Not shown: 39999 closed ports
PORT      STATE SERVICE
48915/tcp open  unknown

Ok, cool – there’s something at 48915, and it looks like it accepts TCP connections.  Pop open Telnet, connect to it, and feed it an HTTP request:


$>telnet localhost 48915
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
GET / HTTP/1.1
HTTP/1.0 404 Not Found
Connection closed by foreign host.

Ok, we got an HTTP response – looks like there’s an HTTP server back there, right?

Wrong.  Reconnect, and send it some garbage:


$>telnet localhost 48915
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
thisissomegarbagetextthatisnotanHTTPrequest
��Nun��2�=���1��N$O/(����
���u.)(yy�g��$
ș�oT�b렑�-z#x�&���[P���\��(yVO���

See all of those funny characters down at the bottom?  That’s what I got back.  In the words of Obi-Wan Kenobi…that’s no HTTP server…it’s a space station (Skype node).

So we’ve learned something here – Skype opens a port, and “spoofs” an HTTP server.  We can easily check for this – just write a script that connects to a port, spews some garbage, and check to see if we got binary garbage back.

It’s so easy, that someone else has already done it.  Remember that nmap tool we used earlier?  Somebody over in that camp wrote a script for the Nmap Scripting Engine that runs this exact analysis on some ip/port.  Don’t believe me?  Read the script yourself! We stumbled upon that script while trying to figure out what Skype was doing with the spoofed HTTP server.
And sure enough:

$>nmap localhost -p48915 --script skype.nse
Starting Nmap 5.00 ( http://nmap.org ) at 2009-12-01 20:45 EST
Interesting ports on localhost (127.0.0.1):
PORT      STATE SERVICE
48915/tcp open  skype2

Nmap done: 1 IP address (1 host up) scanned in 0.14 seconds

Hmph.  So much for cutting edge, never-been-done research.  Go figure.

Fact 2:  Given some UDP packets, Skype echos back a predictable pattern

For this part, we’re pretty sure no one else has tried this.

While connected to Skype, we recorded some packets with tcpdump.  We wrote a script that loaded up those packets, and could “replay” the packet payloads to an arbitrary IP and port.

So, we played some packets against an IP/port with Skype behind it.  Most of the time, we got TCP packets with RST flags (which is TCP’s way of telling us to “shut yer trap”).  But wayyyy down in the middle, there was a section of UDP packets that actually got a response:

From Misc Blog Images

192.168.0.19 was the computer we were playing the packets from, and 192.168.0.14 was the computer with Skype running on it. See those UDP packets that are getting echoed back?  That’s the interesting part…instead of just shutting us down with RST’s, Skype appears to be saying something back.

So, is there a pattern in all of this?  Actually yes.  We isolated 4 of those UDP packets, and repeatedly fired them at the same IP/Port on the computer running Skype, and we found a pattern.

The pattern:  the first two bytes that are sent in our UDP packets are echo’d back to us in the first two bytes of the UDP packets that come back.

So, for example,  one UDP payload we sent looked like this:

92 40 02 a1 66 65 ea 0d 8c 82 c3 0c 27 cd c5 e7
4e 78 fe a1 50 a6

And we got back:

92 40 17 c0 a8 00 13 74 a0 41 f0

See that common 92 40?  Bingo.  ;)

And it’s pretty consistent – if we repeat the same UDP packet, we get (almost) the same response.


92 40 67 c0 a8 00 13 11 00 10 4f

And if we repeat again…


92 40 37 c0 a8 00 13 68 08 43 3a

92, 40, and c0, a8, 00, 13. Nice!  Looks like a fingerprint to me!

Except…

Except, remember, we already found a way of determining whether or not Skype was running behind a given IP/port.  This last finding was just bonus.  My partner and I aren’t sure if our instructor is going to let us stay with this topic, seeing as how it’s pretty much been solved by other people before.  We’ve only got 2 weeks before this project is due, so…if we get another project, let’s hope it’s relatively simple.  Push come to shove, we could always try to fingerprint a different protocol…maybe BitTorrent clients.

Either way, working on this stuff has been pretty cool…and it let me try out some pretty neat tools that are usually reserved for the people with coloured hats (and no, I didn’t mean Red Hat):

  • nmap: port scanner that can also do service/os fingerprinting
  • Scapy: sculpt, gut, spoof, manipulate, and send packets – the power of C, with the simplicity of Python!  We used Scapy as a library while writing our scripts.  Lots of potential with this tool.  Feel like poisoning an ARP cache?  Scapy is for you!
  • Wireshark: a network student’s best friend.

Click here to check out Mohammad’s blog post about this project.

Poland – Part 10: Journey To Krakow, Wawel Hill, and The Dragon

June 23, 5:10AM

At 5:10AM, a huge clap of thunder woke us all with a start.  Groaning,  moaning, and uttering expletives… we tried to go back to sleep, but the thunder storm and heavy rain raged all around us.

And then, eventually, the storm moved off…finally, we could sleep…

…but before it could happen, one by one, our alarm clocks started to go off.  It was time to leave.

Grumbling, lights flicked on, and we headed to the washrooms and showers…

6:12AM

A few people reported that there was some food missing from the hostel kitchen.  Tom and Tara reported half a carton of chocolate milk had been pilfered, and half of Linn’s salami was missing.

Apparently, some of the guests thought we wouldn’t mind sharing.  Or there was a mix up.

Either way, it didn’t improve anyone’s mood.

Not long after, we packed up our stuff, got on the bus, and left Wroclaw for Krakow.

10:27AM

We had been on the bus for a few hours, and I had been trying (unsuccessfully) to take a nap.  I eventually gave up, and I joined in with a bunch of the group who were quizzing each other on Canadian provinces and U.S. states.

It turns out that I know relatively little about Canadian provinces, and next to nothing about U.S. states.  Hmph.

Eventually, we pulled over at a rest stop.  I took the opportunity to try some of the local junk food, and purchased two chocolate bars – a “Corny Big” and a “3Bit”.  They tasted better than they sound.

Tamara also took the opportunity to tell us how the rest of the trip was going to work.  She also lightly condemned the last hostel, which was clearly not to her liking.

While talking about the rest of the trip, she mentioned that she had arranged for us to visit Auschwitz for the next morning.  The group got quiet.  Tamara also said that she had left open the possibility of visiting the Wieliczka Salt Mines after Auschwitz, but that it would really depend on our mood.  We would probably be upset after Auschwitz, and would want to go home and rest.

12:30PM

We arrived at the hostel around 11:30PM, and man, what a difference!  The place was absolutely spartan, the rooms were gorgeous, the views were incredible… we were quite happy, as you can see:

Yev and Alexi, posing in the Krakow hostel!
Yev and Alexi, posing in the Krakow hostel!
Una is digging the room
Una is digging the room
Linn likes the room too!
Linn likes the room too!

Yes, it was a welcome change.  In case you’re interested, the hostel was called “Cracow Hostel Apartment“.  You can see more photos of the place if you click these words – but having been there, it’s pretty clear that these photos try to make the rooms seem bigger with lens effects.

So we had nice rooms.  But guess what?

Peter got the pent house! The lucky guy got the hostel apartment!  The room was incredible!  It was too bad we were only staying a few nights.

The hostel was particularly awesome because it was in the Market Square.  Here are a few shots of the view from the common room window:

Our view from the Krakow hostel common room window
Our view from the Krakow hostel common room window
Looks like rain...
Looks like rain…
Krakow market square - looks a lot like Wroclaw's, doesn't it?
Krakow market square – looks a lot like Wroclaw’s, doesn’t it?

Wow!  (Looks a lot like Wroclaw, doesn’t it?  That’s what I thought, too.)

If it isn’t clear from the photos, it was still drizzling out.  But that didn’t mean we weren’t starving.  After unpacking and cleaning up, we hit the pavement to try to find some lunch.

Wandering through Krakow
Wandering through Krakow

1:06PM

This was lunch:

Mmmm....I don't remember what it was, but it was tasty.
Mmmm….I don’t remember what it was, but it was tasty.

And this was where we ate it:

This restaurant was called "Chimera", I think...
This restaurant was called "Chimera", I think…

The place was called ChimeraInteresting concept for a restaurant.

1:41PM

After leaving the restaurant, Tamara took us on a walking tour of the surrounding area:

Exploring Krakow
Exploring Krakow
I think this is Krakow University
I think this is Krakow University

The rain had stopped, and the air was left dripping with humidity.  Here’s Alexi, not liking the humidity:

Alexi doesn't like the humidity
Alexi doesn’t like the humidity

In the background of that photo, there’s a church.  That’s the Bazylika Sw Franciszka Z Asyzku XIII W.  Hm.  Maybe I wasn’t hearing right, but apparently there was some stained-glass work by Adam Mickiewicz there…

Here are some shots from the church.  Not the greatest shots I’ve ever taken, but hey – it was dark in there:

Shroud of Turin?  In Krakow?  Maybe it's a photocopy...
Shroud of Turin? In Krakow? Maybe it’s a photocopy…

I don’t know if Mickiewicz did the stained-glass – regardless, here’s a shot of one of the pieces:

Poseidon!
Poseidon!

2:07PM

We left the church, and meandered through the streets.

Eventually, we found ourselves at an outcropping called Wawel – home of Wawel Castle, which was to be our next stop.

A castle in Krakow.  The main castle, I believe.
A castle in Krakow. The main castle, I believe.
The castle from the "front".
The castle from the "front".

Here’s a window dog we saw on our way to the castle ramp.  It breaks the narrative, but I can’t resist:

Window dog
Window dog

And while I’m breaking narrative, here’s Alex posing in front of a Bauhaus poster:

…and eventually, we found ourselves climbing the ramp up to Wawel Castle:

Going into the castle...
Going into the castle…

Here’s a view from one of the castle turrets:

At the castle gate, we bought tickets to enter, and to see the “Dragon’s Den” underneath the castle grounds.  We were stoked.

2:45PM – Wawel Castle

High security.  Metal detectors.  Armed guards.  This place wasn’t taking any chances.  There was a very strict code of conduct in there – no sitting, no leaning on walls, keep quiet, and absolutely no pictures.  So I just took notes.

So I can’t show you what it was like inside, but I can try to describe it:

It was a museum.  Stone and hardwood floors.  Quiet like a tomb.  Marble staircases.  Wooden cabinets, uncomfortable looking wooden chairs, wooden tables…tapestries, beds.  Old paintings.

Tamara told us a story about how when the Germans invaded, relics and artifacts were smuggled out of Europe.  It turns out that some relics from Wawel Castle eventually found themselves holed up with a cloister of nuns in Canada.  Go figure.

Everything was ornate, and gold rimmed.  Even the ceilings were covered in gold.

Oh the hell with it – so I couldn’t take any photos: that doesn’t mean I can’t scrape some from off the Internet.  Here’s what I was seeing, care of this website:

There, that’s better.  I’ve always been a visual kind of guy.

Check out the ceiling on this room:

You probably can just barely see them, but those are human heads carved and painted into the ceiling.  Just staring down.  And one has his mouth gagged.  It was creepy.  Apparently, those heads were carved by Sebastian Tauerbach back in the 1500s.

3:55PM

The castle wasn’t the only thing on Wawel Hill.  Inevitably, there was a church – Wawel Cathedral.

So, interesting theatre connection with Wawel Cathedral:

There was a theatre artist who wanted to do a show in the cathedral.  His idea for the play:  that all of the tapestries and statues would come to life on the night before Easter to demonstrate the resurrection of Christ.  It was like Night at the Museum, but with 100% more Jesus.

Anyhow, that play was called Akropolis, and would eventually be staged by Jerzy Grotowski in the 1960’s. Grotowki’s spin on it was to stage it in Auschwitz instead of the Wawel Cathedral.

Anyhow, Grotowki’s Akropolis caused ripples in the theatre world, and was a shining example of the “poor theatre” that he was striving to achieve.

For the people who don’t study drama, Grotowski, Poor Theater, and Akropolis are a pretty big deal.  I’ve seen a taping of Akropolis a few times…it’s one of the few recordings of Grotowski’s work.

Anyhow, that’s the connection.  We were inside the cathedral where that whole thing began.

4:02PM

Walking through the cathedral.  Once again, I couldn’t take any photos.

Description:  high ceilings, gold, tapestries, stained glass.  Gothic architecture.  Gold alter.  Chandaliers.  Ornate, dark woodwork.  Coffins and tombs.  Sarcophagi.

There was a narrow, claustrophobic staircase that led up to the cathedral bell tower.  It was windy up there, and the bells were absolutely massive.  Huge cast-iron things.  Mother of all bells.  I couldn’t help myself – I whipped out my camera like a gunslinger, and snuck a shot:

Yeah, I know – doesn’t look that impressive.  It’s due to lack of size reference points.  You’ve just got to trust me.

There were tombs in the basement.  Thick marble slabs, stone… there were some disturbingly small sarcophagi too.

The tombs got more modern the farther through we went – towards the end, we saw tombs with the occupants’ firearms strapped to the wall.

Maybe I’ve seen too many Indiana Jones movies, but I couldn’t help feeling that there were probably secret passages all over the place.

4:30PM

Finally, we got out of the catacombs into the fresh air.  We hung around outside, and waited for stragglers.  I took the opportunity to take a photo of some kids who were clearly disobeying the “don’t step on the grass” rule:

These kids were totally ignoring the "do not step on grass" rule.  They were never seen again.
These kids were totally ignoring the "do not step on grass" rule. They were never seen again.

Thunder rumbled in the distance.

4:50PM

Remember the Dragon’s Den?  That was our last stop on Wawel. We took a narrow, twisty flight of stairs down…down…deep…down…wayyyyy down into the cave beneath the castle.

It was…a cave.  Kinda underwhelming, but I don’t know what we were expecting.  A real dragon?

The lighting conditions weren’t ideal, so here are my crappy photos of the cave:

Exploring the cave
Exploring the cave

And here’s Tom filling up the cave with some dragon presence:

TOM IS THE DRAGON
TOM IS THE DRAGON

We eventually left the cave.  We took the time to sit, rest our legs, and stare up at this dragon monument that was outside the exit:

Here's the dragon outside of the cave.  It's supposed to breathe fire, but we never saw it.
Here’s the dragon outside of the cave. It’s supposed to breathe fire, but we never saw it.

The Dragon

Now, I don’t know how the rumour got started, but apparently, every hour, that dragon was supposed to breathe fire.  So the bunch of us stuck around for about 15 minutes, waiting for the fireball.

Evidently, the group of us make enough of a crowd to cause other people to wonder what’s going on, because more people from off the street started joining our group, staring up at the dragon, waiting.

And then the hour came…and went…and nothing happened.

Jiv went to talk to a local street vendor.  It went something like this:

Jiv:  Isn’t this thing supposed to breathe fire every hour?

Vendor:  [Look of confusion]

Jiv:  [Mimes breathing fire, and points at dragon]

Vendor:  [Shakes head vigorously]

Disappointed, the crowd dispersed.

5:35PM

Tamara had led us into the Jewish Quarter of Krakow.

Alex Rubin:  A Jew in the Jewish Quarter.
Alex Rubin: A Jew in the Jewish Quarter.

The storm was really threatening now – dark clouds, and rumbling that was closer than before.

Trouble brewing
Trouble brewing

Rain started to fall.  It was time to get indoors.  As a torrent of rain started to come down, we found a restaurant, and took shelter.

And then it started to hail for a bit.  Strange.

6:52PM

The restaurant we had chosen was pretty fancy.  I ordered what eventually turned out to be chicken shish kabab.  For the price…not that great.  But whatever, we were inside and dry.  And I was full.

The group was pretty tired at this point.  The lack of sleep from the night before, and the long tour of the day had worn us out.  After we had finished eating, Tamara told us that we had the rest of the day to ourselves.

A pack of us left the restaurant to explore the Jewish Quarter.  Eventually, we found ourselves back in the Market Square, where I promptly ordered myself a lemon sorbet.  I missed the ice cream from Wroclaw, but the lemon sorbet was amazing.  Sonia took the opportunity to buy some zapiekanka.

Have I told you about zapiekanka?  I don’t think I have.  Polish equivalent to a hot dog.  Long half of a baguette, topped with melted cheese and mushrooms, and a long strip of ketchup.  I liked ‘em.

Some of us went back to the hostel.  I hung around the Market Square for a little bit and snapped a few photos:

Poland is under construction everywhere.  There are cranes all over the place.
Poland is under construction everywhere. There are cranes all over the place.

Here’s Adam Mickiewicz again!  What a guy!

Adam Mickiewicz!
Adam Mickiewicz!

And a giant head:

Massive head.
Massive head.

The very center of the Market Square was a…market.  Lots of little booths selling trinkets.  Religious figurines…amber… a high number of chess boards, which I found strange.

The market in the center of the market square.  It was like a flea market.
The market in the center of the market square. It was like a flea market.

And wouldn’t you know it, I also found some miniature copies of those creepy head sculptures that I’d seen in Wawel Castle!

At this point, I was pretty tuckered out.  I walked back to the hostel, and eventually went to sleep.

We would be getting up early the next day to go to Auschwitz.

Click here to go back to Part 9:  The Halfway Point

SQL Injection Prevention in PHP – Tip 1

It’s amazing – I’ve been going around, Googling for anything with “index.php?id=”…and that’s really all it takes.  Now, granted, SQL Injection isn’t new, and a lot of the top hits have taken some steps to protect themselves, but if you go deep – like, Google search page 23 deep – you’ll find ones that break if you put a semi-colon after the id # – and if it breaks, it’s vulnerable.

So, here’s my first tip on preventing SQL Injection – when you’re asking for an ID number, make sure it’s a number, and nothing else. Also consider using prepared statements – database wrappers like MDB2 for PHP make this easy.

Check this out – this might be how I would have done it 3 years ago:

<?php
  //Assume we're already connected to a MySQL database...
  $id = $_GET['id'];

  $result = mysql_query('SELECT * from pages where id='.$id);
  if (!$result) {
     die('Invalid query: ' . mysql_error());
  }
  ... //Code to print out my result to the page
?>

I’d do it this way now:

Note: My use of MDB2 might be a little rusty – I haven’t tested this code, and I usually compose RowDataGateway objects with MDB2 to represent my data.  So pay more attention to the structure than the actual syntax.

<?php
  require 'View.php';
  require 'MDB2.php';  //An excellent DB layer from the PEAR libs

  //Code to set $mdb2 as our DB connection variable
  //See http://pear.php.net/package/MDB2 for details
  $id = $_GET['id'];

  try {
    if(!is_int($id)) {
      //ID wasn't an int, it's no good, let's bail
      throw new Exception('Could not recognize the id that you passed');
    }
    //ID was an int, let's see if we can find the record
    $sql = 'SELECT * from pages where id=:id";
    $statement = $mdb2->prepare($sql);
    $statement->bindParam('id', $id);
    $result = $statement->execute();
    if(PEAR::isError($result)) {
      //Uh oh - our result was an error on the PEAR library level
      throw new Exception('There was an error communicating with the database');
    }
    //Insert the database result into the view, render, and die.
    $content = new View('templates/page.tpl', array('page' => $result->fetchOne()));
    $content->render();
    die;
  }
  catch(Exception $e) {
    //We must have caught an exception - put this into our
    //error page template with the error message, render, die.
    $content = new View('templates/error.tpl', array('message' => $e->getMessage()));
    $content->render();
    die;
  }
?>

Yes, it’s quite a bit more code. But I feel safer just looking at it.
Did I miss anything on this? Please post a comment if you  notice that I’ve left a gaping hole.  Learning is good.

Preventing SQL Injection Attacks

Over the reading week, along with studying for various midterms and assignments, I’ve decided to brush up on preventing SQL Injection attacks in web applications.

Pretty scary/awesome stuff out there on this stuff.  Here’s a great place to get some SQL Injection training, and here’s an excellent SQL Injection cheat sheet.

I got hit with a pretty bad SQL Injection attack last summer on an application I had written 3 years ago (before I had any clue that SQL Injection attacks were possible).

Here’s the take home message:  never trust user input.  Ever. If you’re expecting an int, make sure it’s an int.  Never insert user input directly into an SQL string. Use prepared statements instead, or stored procedures.

Luckily, I just did a quick survey of all of my running apps, and I seem to be OK in terms of SQL Injection.  Still, it’s a common attack vector – and the consequences of being lazy on user input can be pretty awful.

Update: Want to see something awesome?  Check this out – a Debian box gets rooted through MySQL injection…killer soundtrack too.