Archive for July, 2010

Jul 31 2010

Part 1 of Cyber Security Challenge: Decoding the image

The first part of the Cyber Security Challenge requires you to decode a long stream of letters, numbers and symbols into something coherent. This was by far the easiest part of the challenge. The symbols look like this:

/9j/4AAQSkZJRgABAQEAYABgAAD/4QBaRXhpZgAATU0AKgAAAAgABQMBAAUAAAABAAAASgMDAAEA
AAABAAAAAFEQAAEAAAABAQAAAFERAAQAAAABAAAOxFESAAQAAAABAAAOxAAAAAAAAYagAACxj//b
AEMACAYGBwYFCAcHBwkJCAoMFA0MCwsMGRITDxQdGh8eHRocHCAkLicgIiwjHBwoNyksMDE0NDQf

This is only the first three lines — there’s 362 lines of this. The most important bit is that the last line ends in a = sign. This symbol is used for padding out messages when they are encoded in Base 64 format, so if any string has an equals symbols on the end it’s worth seeing what happens if you decode it as if it were Base64. (The truth of the matter is that by the time my mate Rich had told me about this challenge he’d already decoded the image so I didn’t do any of this stuff!)

Thankfully there are plenty of programs that will do the decoding for you, and the resulting file is a JPEG file. Brilliant:

This is XKCD comic number 538, with a subtle difference. Round the outside of the image there is an uneven dotted border. This isn’t in the original comic, and it looks irregular which suggests that it’s not just a pretty pattern but that it encodes some further information.

For the next stage I converted the image to PNG format because it was the easiest format to load and process.

The first part we need to do is load the image file and extract all the bytes from the actual image part, ignoring any metadata. The PNG file is represents a 24 bit colour image, with each component (red, green and blue) stored as an 8 bit number from 0–255. We just return the whole thing as a long list of bytes, starting at the top left and scanning left to right, top to bottom. It’s not efficient but it’s very simple to reason about because we don’t need to think about array locations.

getimage :: IO [Word8]
getimage = do
  (Right img) <- loadPNGFile "decode.png"
  getElems (imageData img)

The long list may be conceptually simple but it’s not representative of the structure of the image. Since each pixel is represented by 3 consecutive numbers we want to gather those numbers together, so we can start dealing with them as pixels. Thus we convert [r,g,b,r,g,b,r,g …] into [[r,g,b],[r,g,b],…]

splitIntoBytes = splitEvery 3

Even though each pixel can represent many colours we’re really only dealing with black and white here so we can represent each component as fully-on or fully-off. Each pixel can really be stored as boolean values like [True, False, False]. Since it’s possible that some values are not absolutely 0 or absolutely 255 I’ve divided them up the middle — anything darker than 128 is 0, and anything lighter is white.

Once each pixel is a list of booleans we can collapse that down into a single black/white value by taking the conjunction. If all values are True then the pixel is True (ie, black) otherwise False (white).

normalise = and . map (< 128)

At this stage our image is no longer a list of integers but a list of booleans. The original list had height-times-width-times-3 elements. Since we’ve collapsed all those three elements into a single value representing each pixel we now have height-times-width elements. The image is 350x175 pixels so we can split it into rows by cutting the list every 350 elements. This gives us 175 rows.

tomatrix = splitEvery 350 . map normalise . splitIntoBytes

The next stage is, I think, the most beautiful aspect of representing the image as a list of lists. We have a full image but we only want the wavy lines of pixels which make up the border. How do we extract those pixels?

The first thing to notice is that the border is not continuous. The top and bottom edges go to the edge of the screen at both sides, but the two sides don’t meet at the top or bottom. To illustrate:

#################
 
#               #
#               #
#               #
 
#################

So the first question, “where do we start and end?” is answered for us. Each segment is discrete. It was my colleague Rich which pointed out the slight gaps in the border which makes this simplification possible. If the border were complete we’d have to determine whether the corner pieces were part of both the horizontal and the vertical (like a crossword where Across and Down share letters) or not.

The second question we ask is, “which direction does the sequence go in?”. Do we go clockwise from top left, following this alphabetical sequence?

a b c d e
n       f
m       g
l k j i h

Or do we maybe scan left-to-right, ignoring gaps?

a b c d e
f       g
h       i
j k l m n

What about anticlockwise? A mixture of the above? I took the approach which seemed obvious to me, clockwise from top left, and it turned out to be correct. But interestingly the final message is repeated in part so choosing the wrong start point would not have mattered, and it would have been obvious that the output was almost right.

Each row is a list, stored in order from top to bottom. This means the top border is just the first list:

topedge = head

The bottom border is the last list, but because we’ve chosen clockwise we need to reverse the list too.

bottomedge = reverse . last

The right edge is the last element of each list, ignoring the first 3 rows and the last three rows, because as mentioned above, the side patterns are shorter. These two look slightly complicated but it’s mostly dealing with trimming the top and bottom edges off.

rightedge = reverse . drop 3  . reverse . map last . drop 3
leftedge = drop 3 . reverse . map head . drop 3

Now we can extract each edge of the border we can join them all together into our encoded message. This converts our list of lists, which is a complete picture, into a list of bits encoded in the border.

msgstream :: [[Bool]] -> [Bool]
msgstream bits = concatMap ($ bits) [topedge, rightedge, bottomedge, leftedge]

Now we have a long list of bits. And it just so happens the number of bits we have is divisible by eight! This is a good sign because binary information is typically grouped into sets of eight. For the next stage we group our list into sets of 8 bits and turn each 8 into a single number.

One of the tricky aspects about any number is that you can’t tell in advance which end to start from. You and I know that 12 is “twelve” not “twenty-one” but that’s because we know to read numbers from left to right. Computer formats have used both in the past so I wasn’t sure which one would be important to me — is the biggest number the first digit or the last digit? The actual question is, “is the leading digit the most significant bit or the least significant bit?”. I calculated both to see what would happen, and it turned out that most-significant-bit was the way to go. Thankfully, MSB and LSB are just the reverse of each other, so by implementing one we get the other for free!

msb,lsb :: [Bool] -> Int
msb = lsb . reverse
lsb = bitsToInt . map (fromIntegral . fromEnum)

We calculate least significant bit by converting all the True values to 1 and all the False values to zero, and then multiplying element-wise by a stream of powers of two. To illustrate:

  1 2 4 8 16
* 0 1 1 0 1
= 0 2 4 0 16

Then we just add that list up, so “0 1 1 0 1” is “0+2+4+0+16” or 22.

bitsToInt = sum . zipWith (*) (iterate (2*) 1)

After all that prelude we can put this segment together, dividing the image up into its matrix, extracting the bits from the border of the image, splicing them up into sets of eight and converting each 8 bits into a single number:

msgbits = map msb . splitEvery 8 . msgstream . tomatrix

Now what do we do with our numbers? Readable characters are represented internally as numbers, so it is a simple thing to convert between number and printable characters. If we convert each number to a character we get nonsense, but consistent and tantalising nonsense:

Cyrnfr sbyybj guvf yvax: uggcf://plorefrphevglpunyyratr.bet.hx/834wgc.ugzy uggcf://plorefrphevglpunyyratr.bet.hx/834wgc.ugzy

Look at those sequences “uggcf://” repeated twice. That looks so much like a web address, “https://”. If we assume that it is a web address how has it been altered? Each letter in a pair, h/u, t/g, c/p, is 13 characters apart from its partner. But the punctuation symbols aren’t any different.

This looks like the encoding called “rot13” where each character is shifted 13 characters along in the alphabet, and if we reach the end we wrap back to the start. Also, since the first letter of the nonsense message is a capital and none of the rest are it seems like case is being preserved by this encoding.

We convert back to sensible words by rot13 encoding again, since 13+13=26 so any two applications of this transformation will undo each other.

Uppercase and lowercase are treated separately but by the same process. We’re processing some character which we call c and we want to know how many characters it is away from the start of the alphabet. The letter ‘a’ (or ‘A’) is 0 characters away from the start, ‘b’ is 1 character and so on.

If we assume an infinite stream of letters “a b c … x y z a b c…” repeating the alphabet, then the Nth letter in that stream is the one which is N away from the start. The 0th letter is ‘a’, the first letter ‘b’. But if we chop the first 13 characters off this stream, so it’s “n o p … y z a b c …” then the 0th letter is ‘n’, the 1st letter ‘o’ and so on. Each offset now directly maps one letter onto its partner letter. And because the sequences of letters is endless we don’t have to worry about falling off the end. The mapping just loops back on itself:

0 1 2 3 4 5 6 ...
a b c d e f g ...
n o p q r s t ...

Thus we can find the alternate character in our pair by checking first of all how many characters our current letter is from the start, and then looking for the equivalent character in the list which has had its head chopped off. We do the same for the upper case characters and just pass through unchanged anything which isn’t upper or lower case — all the punctuation and spaces.

rot13 :: Char -> Char
rot13 c | isLower c = lowercase!!(ord c - ord 'a')
        | isUpper c = uppercase!!(ord c - ord 'A')
        | otherwise = c
  where lowercase = drop 13 $ cycle ['a'..'z']
        uppercase = map toUpper lowercase

By now I think you’re dying to know what the message says, so let’s finish up here. We decipher a message by converting each integer to a character and performing a rot13 transformation — then we print it.

decipher = putStrLn . map (rot13 . chr)
main = getimage >>= decipher . msgbits

The whole thing is pulled together so we can run it from the command line and we receive the sensible output of:

Please follow this link:
https://cybersecuritychallenge.org.uk/834jtp.html https://cybersecuritychallenge.org.uk/834jtp.html

Next time I’ll look at what happens when we follow that link, and how we complete the next phase of the challenge.

If any of this doesn’t make sense or is confusing please ask questions in the comments. If you want to look at the code in full you can read the solutions for part 1 and part 2 online at http://www.dougalstanton.net/code/cybersecurity/.

As I mentioned in my introductory post I was incredibly impressed by the easy exploratory power of the Haskell code I wrote. Writing little segments to splice, decode, convert and transform made it simple to try out different ways of getting sensible output. I had no idea when I started which way the answer would take me, but putting them together in different combinations in the interpreter was easy and provided instant feedback. (That being said, Rich kinda floored me with his ability to wrangle Excel of all things into solving this problem, though that doesn’t mean it’s the right tool for the job!) Tune in next time for more exciting cryptographic games!

One response so far

Jul 30 2010

Cyber security teaser challenge

Published by Dougal under Computing, Programming

During the week a friend from work pointed me towards the Cyber Security Challenge, which is being touted as a popular method to promote the field of computer security in the UK.

They had released a teaser challenge as a sample of the main competition which seemed like it was worth trying. It took us a couple of days to get to the answer, not least of all because we actually had work to do!

Since the teaser challenge is now well over and the “official” method has been published on the challenge page (move your mouse over the big white space to see the solution) I thought it would be interesting to go through my solution and see (a) what the puzzle-setters had done (b) how the answer was stumbled upon (c) how the answer could have been derived and (d) where my method differed from the official approach, despite reaching basically the same answer. It’s been a while since I thought about the practical techniques of cryptanalysis so my methods are neither the best nor the most sensible, but at least I can be honest. Helen’s just finished reading Cryptonomicon so will probably tell where I went wrong!

If you want to try out your skills the original problem is still available and will probably be there for some time. At least you can see what the starting point was.

I’ll write up my results and methods in the next few days, posting each section as it goes. I’ll also publish the code I used to extract the solution, which was written in Haskell. I’ve never done anything like this before but the Haskell list-munging functions and point-free style made it simple. The effortless compositional style of creating pipelines of functions meant that I could play with little sections, joining and splicing them as necessary, until I found something which seemed like a good result. But there will be more details in the coming days.

Comments Off

Jul 24 2010

Networking and redundancy (double meanings)

Published by Dougal under Humour, Networking, Work

For the past three and a half years I have been working on router redundancy protocols. When your router (or its upstream connection) dies for some reason you want to minimise the loss on people using the network. Ideally users should never notice loss of connection, though in the real world there will be some time delay before things are working again. The work I’ve been doing relies on having a second router which has its own connection to the local network and to the wider world. It acts as a redundant backup so that when the first one dies the second can step into its place within some short period.

When the primary router is working normally the secondary doesn’t do much. Its only role is to monitor the liveliness of the primary machine. The redundant router can often be used for other things when the primary is operating — and many times the primary acts as a redundant router for the secondary’s clients. Each provides backup for the other.

So when I found out recently that I was being made redundant I thought “great! I’ll just sit and watch other people working and take over if they burst into flames”. But it turns out that when people are redundant it’s totally different from when routers are redundant. Instead of being relied on for backup in case of failure, it means “no longer working”. Strange but true! I can see why it wouldn’t catch on very well in networking.

My last day at Cisco is this Friday (30 July). It’s been an interesting few years and provided novel experiences, silly conversations about Star Trek and given me a bit more confidence. I’m sad to be going, and though there will always be loose ends to tie up and the promise of interesting projects on the horizon, the team I’m leaving behind seems to have a glut of these at the moment. I’m also disappointed that the study group at work will continue reading SICP without me. Obviously I can read it alone but the discussion and peer support/pressure was a useful part of it.

Meanwhile, the job hunt continues. Recruitment agencies make this process at least ten times harder by hiding the employer, the industry and the specifics of the job for their own ends. I have had a few friends pass on job details, and had some telephone discussions, but no success yet. Watch this space, or one very much like it.

One response so far

Jul 23 2010

What does your IP address mean?

Published by Dougal under Networking

The internet protocol (IP) address of my laptop is 192.168.0.3/24. What does this mean?

The first and obvious question is, What’s an IP address? It’s an identifier that your computer uses to talk to other computers on the network. It bears a lot of resemblance in form and function to a telephone number. There are prefixes which are shared by every address in the area, and then there’s a bit specific to you.

ethernet cable

An IP address has two important pieces of information embedded in it. The first is the host ID — the identifier of my specific computer. The second is the network address — which is the number of the network my computer is found in, and is analogous to a telephone area code.

Just to make things difficult though, the two numbers are joined together so you can’t tell where one part ends and the other begins. So when talking about addresses we need another piece of information to tell us which part is network and which part is host.

First, let’s write out 192.168.0.3 in binary. This makes a very long number but it will make everything much clearer from here on. Each number between the dots is converted separately. This number is not the same as 19,216,803.

192.168.0.3 = 11000000 10101000 00000000 00000011

I’ve left spaces where the dots were previously. Each section is 8 binary digits long, so each section can represent a maximum number of 11111111 — which is 255 in decimal.

The next bit we come to is choosing a point on that line so that all the digits on the left represent the network address and all the ones on the right show the host address. Looking back up at the address I gave at the top you’ll see a “/24” sitting at the end. This is called the network mask and it works just like a piece of card with a hole in it. You write out your address and then align 24 bits underneath: everything with a 0 underneath is masked out, leaving the network address. We are getting the result of 1 whenever both the address and the mask is 1.

192.168.0.3  = 11000000 10101000 00000000 00000011
mask 24 bits = 11111111 11111111 11111111 00000000
result       = 11000000 10101000 00000000 00000000

Back in decimal land, that network address is 192.168.0.0. Since the network mask is also a binary number it is often written like an IP address, as four decimal numbers separated by dots. The same address can be written as 192.168.0.3/24 or 192.168.0.3/255.255.255.0.

We can invert the network mask to give a host mask and use the same procedure to find out the host ID, which turns out to be 00000011, otherwise known as 3.

192.168.0.3 = 11000000 10101000 00000000 00000011
mask 8 bits = 00000000 00000000 00000000 11111111
result      = 00000000 00000000 00000000 00000011

You probably knew that from inspection but computers ain’t so clever!

Another useful number we can learn from the address and mask is the broadcast address. This can be used to send messages to everyone on the network. We calculate this by inverting the mask again, so we’ve got 8 bits on the right instead of 24 bits on the left, and taking the result to be 1 wherever the address or the mask is 1.

192.168.0.3 = 11000000 10101000 00000000 00000011
mask 8 bits = 00000000 00000000 00000000 11111111
result      = 11000000 10101000 00000000 11111111

The result can then be written as 192.168.0.255 in dotted-decimal format. Packets sent to this address will be examined by every host on the local network. This is useful if you don’t know the address of your recipient!

Photo is The World’s Network by saschaaa.

Comments Off

Jul 08 2010

Mex-a-Tron!

Published by Dougal under Films, Food, Reviews

I don’t know if I ever saw it the first time round, but I saw Tron this evening. Now I’m fully prepared for the sequel when it appears.

A few friends came over and we got fajitas from Los Cardos across the road — and despite the utilitarian appearance the food was pretty good. The staff were friendly too. I got a “fajita burrito”, which is kinda what I’d call a fajita if I was making it at home, except they loaded it with rice as well as the usual fried onions, peppers, cheese, salsa and spicy chicken. (There are a number of other fillings available besides chicken, including haggis…) The food was more or less what you’d make yourself, simple but plentiful, and they had big, good quality tortillas which seems to be the hardest part when it comes to make-your-own fajita meals.

The film was weird as all hell. I borrowed the special edition with audio commentary and a separate making-of disc — I wonder what explanation they’ll have for some of the stranger scenes. Some didn’t even seem to connect at all to the rest of the story. It certainly wasn’t what I expected. I knew there was action in light-striped arenas that probably represented some gaming system, but I didn’t realise that most of the protagonists would be computer programs. Needless to say, if you know anything about computers you have to plug your ears at some points or risk bursting into entirely inappropriate laughter. The plot is a bit like The Lord of the Rings (take the magical item into the evil overlord’s domain to free everyone from tyranny).

The sequel — coming out in December I think, so aiming for the family Christmas market I suppose — follows the action twenty five years later in the same inner-computer environment. Hopefully they won’t be relying on the crutch of dazzling graphics and spectacle instead of coherent plot. But that’s probably a foolish hope…

Helen’s out tonight because one of her colleagues is leaving the lab, so she didn’t get to see it. Maybe we’ll watch it tomorrow with extras before I give the DVD back.

3 responses so far