I'm trying to create a buffer overflow with C# for a school project:
unsafe
{
fixed (char* ptr_str = new char[6] {'H', 'a', 'l', 'l', 'o', ','})
{
fixed (char* ptr_str2 = new char[6] {'W', 'e', 'r', 'e', 'l', 'd'})
{
fixed (char* ptr_str3 = new char[6] {'!', '!', '!', '!', '!', '!'})
{
for (int i = 0; i < 8; i++)
{
ptr_str2[i] = 'a';
}
for (int i = 0; i < 6; i++)
{
this.Label2.Text += ptr_str[i];
this.Label3.Text += ptr_str2[i];
this.Label4.Text += ptr_str3[i];
}
}
}
}
}
I thought this would flood ptr_str2
and thereby overwriting chars in ptr_str
. However that does not seem to happen. It does execute but the values in ptr_str
are not overwritten.
Can anyone help with achieving this? I don't understand what I'm doing wrong.
You are missing the fact that arrays are objects themselves. They have an object header like any managed reference type and a private field that stores the array size. You have to overwrite those first before you start overwriting the array elements. On a 32-bit machine, you'll start overwriting the first element of ptr_str2 with this:
Of course, it had to be 13.
Observe this by setting a breakpoint on the for loop. Debug + Windows + Memory + Memory 1, type "ptr_str" in the Address box. Step the code to see the memory getting changed. You'll see ptr_str2 right after that, 4 bytes for the syncblk, 4 bytes for the method table pointer and 4 bytes for the array length. 12 bytes total, 6 chars.