Call yourself a Hacker? Crack this.

A few years back I found myself hooked on a website that presented a number of password cracking challenges. You had to complete the first challenge before you could get to the second and so on.

It started with a password listed in plain HTML source code and moved on to executables and logging into *nix systems. It required reverse engineering, brute force and various other approaches to get the prize (the password) each time.

Lots of fun – and probably not a good use of my time when I should have been working on serious C++ code for real world projects, but still…

The site has long since disappeared, but it taught me a couple of worthwhile things:

Firstly, that it is very easy to create something that isn’t secure, and if you fall into that trap as a programmer, a web developer or a systems administrator, then the blame rests solely on your head. There WILL be someone out there that is interested in what you are doing.

Secondly, that quite often, it is sheer perseverance more than anything else that gets you the result. When you persevere, you end up using ingenuity – that lovely quality that comes into play when your first (or hundreth) attempt doesn’t work.

I have a penchant for programming challenges, and have been known to be sat at the computer at 5am trying to complete one on the rare occasions that sleep eludes me, so if you have some excess energy that you want to channel into something that won’t result in a debate on your extradition, try this ;-)

Can You Crack It?

Be good now.

 

Sponsored Post

Viral video by ebuzzing

 

Share this:
  • Google Bookmarks
  • Facebook
  • HackerNews
  • Reddit



Simple Programming | Core Dump Files and GDB

What’s a Core Dump?

It’s a file created when your program terminates abnormally. It contains a snapshot of the program’s state at the time of the failure.

What does it look like?

On Linux it will appear in the same location as the executable and will be named something like:

core.4196

Where the number is the process id of the program while it was running.

And what can I do with it?

You can have a look at it using GDB! GDB can read a core file to give you valuable information about a crash after the event.

Some Linux distributions have the ability to create core files disabled by default – you need to type:

ulimit -c unlimited

before running the program to allow the creation of the core file when the program terminates.

To examine a core file, just pass it to gdb:

gdb core.324

GDB will load up all the info and it will look as though you have just run the program and seen the error. You’ll be able to view a backtrace and a range of other information, but it will be a frozen “snapshot” of execution.

Instant debugging!

Share this:
  • Google Bookmarks
  • Facebook
  • HackerNews
  • Reddit



Download the 10 Minute Guide To Object Oriented Programming

I wrote some posts a while back on the principles of object oriented programming and have collated them into this 10 minute guide as a PDF file that you can download.

It covers the main concepts of OOP and also has a simple example of polymorphism in C++.

Get your copy here.

 

Share this:
  • Google Bookmarks
  • Facebook
  • HackerNews
  • Reddit



Geek Mugs Now Available!

girl geek muggeek mugHaving been very busy with a newborn baby for the last two months, the dust is finally settling and I’ve found some time to get my geek mugs online and available to buy.

The mugs are dishwasher and microwave safe and the designs will not crack or fade.

I hand-print each and every one. Delivery within 5 working days, and a snip at £6 each plus £2.50 P&P.

They make great Christmas presents too – get yours at the Geek Oveflow store today!

Share this:
  • Google Bookmarks
  • Facebook
  • HackerNews
  • Reddit



Simple Programming | Declaring Variables in Switch Statements

There you are, happily programming away, when suddenly you get a compile error:

error: jump to case label
error: crosses initialization of 'int x'

“Huh?” You say, peering at the computer screen. Your code looks fine, so what does it mean?

Look closely at your switch statement. A switch statement contains case labels, which provide options to do different things after checking the value of a variable. However, what you may not realise is that the contents of each of these case labels actually exists in the same scope.

Why does scope matter?

If you declare a variable after a case label, you are actually declaring that variable for all subsequent labels without realising it.

This could lead to you trying to declare the same variable twice (if you’re doing similar things for each case), or worse, for you to inadvertently change the value of a variable under another case.

To stop you from doing this, the compiler flags an error and stops compilation.

Oh right. But how do I fix it?

You can still declare variables in switch statements, you just have to put curly brackets around the code after the case label.

Compare the two examples below. The first one generates an error. The second lets you compile and move on.

1. This generates a compile error:

switch (y)
{
case 0:
    int x = 42;
    cout << "I declared variable x." << end;
    break;
case 1:
    cout << "Variable x is still in scope!" << end;
    break;
default:
    break;
}

2. This compiles successfully:

switch (y)
{
case 0:
    {
        int x = 42;
        cout << "I declared variable x." << end;
    }
    break;
case 1:
    cout << "I don't know about variable x." << end;
    break;
default:
    break;
}

 

Share this:
  • Google Bookmarks
  • Facebook
  • HackerNews
  • Reddit



Simple Programming | Using errno

Lots of functions in the C standard library will set errno to an error code if something goes wrong, so using errno in your programming can help you pinpoint where problems are occurring and what they might be.

errno remains set at the last error code, so bear in mind that:

a) if two subsequent functions are returning errors, you’ll miss the first one if you’re not looking for it, and

b) a function called after one that returns an error does not set errno back to zero (but you can set errno to zero if you like).

How do I use errno?

First of all, include the header in your C program:

#include <errno.h>

Or in your C++ program:

#include <cerrno>

Then, you can access the error code just by using the integer errno.

OK, I’ve got a number from errno, but what does it mean?

All the error codes are defined in the errno.h header file. On Linux this lives somewhere like:

/usr/include/linux/errno.h

Er, isn’t there an easier way to see what’s going wrong?

Well there is, since you ask. You can use strerror to return the actual text error message.

See the example code, and its output below – this will return a nice error message and save you having to rummage through the file looking for an error to match the code you’ve been given. Handy, eh?

Output

Attempting file access...
Something went wrong! errno 13: Permission denied

Source

#include <iostream>
#include <cerrno>
#include <string.h>
#include <stdio.h>
int main()
{
    std::cout << "Attempting file access..." << std::endl;
    FILE *f = fopen("/proc/cpuinfo","w");
    if (f == NULL)   
    {       
        std::cout << "Something went wrong! errno " << errno << ": ";
        std::cout << strerror(errno) << std::endl;
    }
    return 0;
}


Share this:
  • Google Bookmarks
  • Facebook
  • HackerNews
  • Reddit



Simple Programming | Override or Overload?

Occasionally I’ve heard these terms used interchangeably – but they actually refer to two completely separate concepts.

So what’s what?

Overloading describes the creation of a method with the same name as an existing method, but different parameters. For example:

int method();
int method(int);
int method(int, double);

Overriding describes the creation of a method in a derived class  with the same name and parameters as an existing method in its base class.

class base {
public:
    int method();
};

class derived : public base
{
public:
    int method();
};

The actual method that is called in this case depends on what kind of object you are dealing with, and whether the base class is abstract, the methods are virtual, and so on.

How do you remember the difference?

Think of it as load versus ride.

Overloading gives you loads of methods in the same class with different parameters.

Overriding lets you ride on the back of a method declared in a base class.

Easy, eh?

Share this:
  • Google Bookmarks
  • Facebook
  • HackerNews
  • Reddit



Simple Programming | Save Time With GDB init Files

I can’t leave the subject of GDB alone for too long, so today I thought I’d talk about GDB init files.

Each time GDB is run, it checks the local directory for the existence of a file called .gdbinit. If it finds this file, it reads the contents and runs any commands it finds there.

This is extremely handy if you are repeatedly debugging an executable and don’t want to keep typing in the same old commands at startup.

For example, if you always put a breakpoint in a certain method because you like it as a starting point, you can specify this in the .gdbinit file, exactly as you would on the command line for GDB:

b main

And if you just can’t be bothered to keep typing ‘r’ to run GDB once it’s loaded your program, you can specify that too:

b main
r

You can also add any arguments that you repeatedly type in:

set args param1 param2
b main
r

And any configuration settings that you might want:

set prompt debug-->
set args param1 param2
b main
r

Now all you have to do is run GDB on your exe as usual, but now it will set up a custom prompt, pass in your arguments, set a breakpoint in main, and even start the program for you. Next thing you know, you’ve got a GDB prompt at the top of the main function and you’re ready to go!

Share this:
  • Google Bookmarks
  • Facebook
  • HackerNews
  • Reddit



Simple Programming | Initialization Lists

When you first start using C++ you tend to set member variables with default values inside your constructor.

For example, you might have a class called Message that has three variables, and your constructor sets the default values like this:

Message::Message()
{
    messageLength = 0;
    messageType = 0;
    messageBody = "Empty message";
}

This is acceptable and I’ve seen it in hundreds of classes, but there is a better way.

When setting member variables to their defaults, it can be more efficient to set them in an initialization list. You create this by adding a colon after the constructor name and listing the variables underneath separated by a comma. You set the default value by adding it in brackets, e.g.

Message::Message() :
    messageLength(0),
    messageType(0),
    messageBody("Empty message")
{
}

In my opinion this also aids readability, since you are leaving the body of the constructor free to do ‘real’ construction work (if necessary), and you don’t have to hunt through lines of code to determine if and where a variable was set to a default value*.

Why is it more efficient?

Setting defaults in the body of the constructor uses assignment, whereas in the initialization list it uses initialization (you could have guessed from the name, right?).

If you are initializing classes (rather than built-in types, in which case this doesn’t apply), then using assignment means that behind the scenes you call the default constructor, followed by an assignment to set the variable. Putting the string variable in the initialization list means that you only call the copy constructor to set up the variable – so it costs one method call, not two.

The order matters

If you don’t enter the member variables in the initialization list in the same order as they appear in the header file (declaration), then gcc will prompt you with a warning:

warning: 'Message::MessageBody' will be initialized after
warning: 'int Message::MessageLength'
warning: when initialized here

Should you care about this warning?

I would argue that you should care about all warnings! It appears because it is possible that a member variable may rely on another member variable during initialization. For example, say your header contains the following:

int total;
int multiplier;

And you initialize them like this:

Constructor::Constructor() :
    multiplier(3),
    total(multiplier * SOME_OTHER_VALUE)
{
}

This won’t work – total will be initialized first (no matter where you put it in your initialization list), because it is declared first in the header, so what will the value of multiplier be at this point? That depends on your compiler, but it almost certainly won’t be what you were expecting!

*Note that you can’t initialize the members of an array in a list – this must be done in the body of the constructor.

Share this:
  • Google Bookmarks
  • Facebook
  • HackerNews
  • Reddit



Simple Programming | Bitwise RGBA Values

Let’s take a look at bit shifting in practice.

Say we have a variable called colour, that contains an RGBA value. If you have never had any experience with graphics, all you need to know is that the colours you see on your screen may be represented as a combination of four different variables – red, green, blue and alpha. The alpha value is usually a percentage to describe the opacity, while red, green and blue values are combined to describe the final colour.

RGBA values are usually stored in a single 32 bit integer, with 8 bits used for each component:

RRRRRRRR GGGGGGGG BBBBBBBB AAAAAAAA

All well and good, but imagine we need to know what the green value is independently of everything else. How can we extract this information? And moreover, how do we get a colour encoded into the variable in the first place?

Setting an RGBA value

Imagine we want to set our colour to a bright yellow, fully opaque. This uses the RGBA components:

R) 0xFF
G) 0xCC
B) 0×00
A) 0xFF

As binary this looks like:

11111111 11001100 00000000 11111111

OK, we could set the colour variable using a large number:

int colour = 4291559679;

but that isn’t a very intuitive (or re-usable) solution.

Instead we’ll add our components in one at a time using a mask, and shift them to the correct positions:

unsigned int colour =
0xFF | (0x00 << 8) | (0xCC << 16) | (0xFF << 24);

To fully break down what is happening here, let’s look at the binary behind the scenes:

The first step is a bitwise OR on 0xFF with 0×00 shifted left by 8 places:

0000 0000 1111 1111 // 0xff
0000 0000 0000 0000 // 0×00 << 8
___________________
0000 0000 1111 1111

The next step is a bitwise OR on the result with 0xCC shifted left 16 places:

0000 0000 0000 0000 1111 1111 // result
1100 1100 0000 0000 0000 0000 // 0xCC << 16
_____________________________
1100 1100 0000 0000 1111 1111

And finally a bitwise OR on the result with 0xFF shifted left 24 places:

0000 0000 1100 1100 0000 0000 1111 1111 // result
1111 1111 0000 0000 0000 0000 0000 0000 // 0xFF << 24
_______________________________________
1111 1111 1100 1100 0000 0000 1111 1111 // 0xFFCC00FF, or 4291559679

The final result is the number we want to assign to the colour integer.

Extracting an RGBA value

Now say we want to extract that green value from our colour integer. We can simply do the following:

int green = (colour & 0x00FF0000) >> 16;

What’s happening here?

First off, we’re masking our colour variable using bitwise AND to effectively “turn off” all the components that we aren’t interested in:

1111 1111 1100 1100 0000 0000 1111 1111
0000 0000 1111 1111 0000 0000 0000 0000
_______________________________________
0000 0000 1100 1100 0000 0000 0000 0000

Then we shift 16 places to the right to put our green component in the first byte:

0000 0000 0000 0000 0000 0000 1100 1100 // 0xCC

Simple! Now we know how to extract any component we choose by adjusting the mask and number of places shifted accordingly.

Bitwise operator summary

A quick guide to which operator to use when.

Bitwise AND

  • Use with a mask to check if bits are on or off
  • Turn off individual bits

Bitwise OR

  • Turn on individual bits

Bitwise XOR

  • Toggle bits on and off, like a switch

Bitwise NOT

  • Turn off individual bits with AND

Bitwise left and right shift

  • Extract bytes from longer variables
  • Insert bytes into longer variables
  • Multiplication and division by powers of 2 (but be cautious with signed integers, remainders and overflow)

This is not an exhaustive list, but a basic guide. Have fun with bitwise operators, and if you want more examples and ideas, have a look at this fantastic collection of code snippets from Sean Eron Anderson.

Share this:
  • Google Bookmarks
  • Facebook
  • HackerNews
  • Reddit