All pastes #366161 Raw Edit

Stack/Heap Overflow

public text v1 · immutable
#366161 ·published 2007-02-21 15:24 UTC
rendered paste body
// hack1.cpp : Defines the entry point for the console application.
//

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

const size_t buffer_size = 16;
const size_t buffer_ret_offset = 8 ;
char*  buffer_data = "AAAABBBBCCCCDDD"; //"DEEEEFFFFGGGG";

void print_mem(unsigned char* mem, const int len, const int bytes_in_line = 8);
void stack_func(char* data);
void heap_func(char* data);


int main(int argc, char* argv[])
{
	stack_func(buffer_data); // 28 + 1
	heap_func(buffer_data); // 28 + 1

	system("pause");
	return 0;
}

void stack_func(char* data)
{
	char buffer[buffer_size];  // Staticky vytvoreny buffer
	printf("stack_func(data = 0x%p) - buffer(STACK %d Bytes) = 0x%p\n",data,buffer_size,&buffer);
	
	strcpy(buffer,data);

	print_mem((unsigned char*)&buffer+buffer_size+buffer_ret_offset,4);
	buffer[buffer_size+buffer_ret_offset+0] = 'A';
	buffer[buffer_size+buffer_ret_offset+1] = 'A';
	buffer[buffer_size+buffer_ret_offset+2] = 'A';
	buffer[buffer_size+buffer_ret_offset+3] = 'A';
	print_mem((unsigned char*)&buffer+buffer_size+buffer_ret_offset,4);
}


void heap_func(char* data)
{
	char* buffer = (char*) malloc(buffer_size); // Dynamicky vytvoreny model
	printf("heap_func(data = 0x%p) - buffer(HEAP %d Bytes) = 0x%p\n",data,buffer_size,buffer);

	strcpy(buffer,data);
	print_mem((unsigned char*)buffer,2*buffer_size);

	free(buffer);
}

void print_mem(unsigned char* mem, const int len, const int bytes_in_line)
{
	printf("MEMORY DUMP BEGIN - 0x%p (%d Bytes)\n",mem, len);
	for(int i = 0; i < (len/bytes_in_line)+1; i++)  // Prizpusobene zpracovani po radcich
	{

		for(int j = 0; j < bytes_in_line && (i*bytes_in_line+j < len); j++)
		{
			int c = (int)mem[i*bytes_in_line+j];
			if(isprint(c))
			{
				printf("%c (0x%02X)  ",mem[i*bytes_in_line+j],mem[i*bytes_in_line+j]);
			}
			else
			{
				printf("%? (0x%02X)  ",mem[i*bytes_in_line+j]);
			}
			
		}
	}
	printf("\nMEMORY DUMP END\n");
}