#include #include #include #include #include #include #include char* get_elf_type(Elf32_Ehdr *elf); void banner(void); int elf_is_valid(Elf32_Ehdr *elf_hdr); void die(int line,char *err,int code); int section_header(Elf32_Shdr *shdr,char *strtable,char *section); int main(int argc, char *argv[]) { int fd = -1; char *buf = NULL; char *table = NULL; char * tochange; struct stat elf_stat; Elf32_Ehdr *elf_header = NULL; Elf32_Shdr *section_hdr = NULL; int i,size; int off; unsigned int vm_addr; if (argc < 5) die(__LINE__,"Usage: ./virtchange
[]",-1); banner(); vm_addr = atoi(argv[2]); printf( "@ File name \t: %s .\n", argv[1] ); if ((fd = open(argv[1],O_RDWR)) <0) /* Open file in read/write mode */ die(__LINE__,"error opening file",-1); if( fstat( fd, &elf_stat ) < 0 ) /* Getting size with fstat */ die(__LINE__,"error getting file size",-1); size = elf_stat.st_size; printf( "@ File size \t: %d bytes .\n", size ); buf = (char*)malloc(sizeof(char)*size+1); if (read(fd,buf,size) != size) /* Read whole file */ die(__LINE__,"error reading bytes",-1); if (!argv[5]) size = strlen(argv[4]); else size = atoi(argv[5]); tochange = (char*)malloc(size+1); memcpy(tochange,argv[4],size); elf_header = (Elf32_Ehdr *)buf; /* Copy the buffer into elf structure */ if (elf_is_valid(elf_header) == -1) die(__LINE__,"bad elf file",-1); printf("@ Type \t: %s .\n",get_elf_type(elf_header)); printf("@ Given address \t: 0x%x .\n",vm_addr); printf("\n"); section_hdr = (Elf32_Shdr *)(buf + elf_header->e_shoff); /* Get first section */ table = (char *)(buf + section_hdr[elf_header->e_shstrndx].sh_offset); /* Table of section name */ for(i = 0; i < elf_header->e_shnum; i++) if (section_header(§ion_hdr[i], table,argv[3])) { off = vm_addr - section_hdr[i].sh_addr; pwrite(fd,tochange,size,section_hdr[i].sh_offset + off); } close(fd); free(buf); return 0; } void die(int line,char *err,int code) { printf("[-]Line %d: %s.\n",line,err); exit(code); } int elf_is_valid(Elf32_Ehdr *elf_hdr) { if( (elf_hdr->e_ident[EI_MAG0] != 0x7F) || (elf_hdr->e_ident[EI_MAG1] != 'E') || (elf_hdr->e_ident[EI_MAG2] != 'L') || (elf_hdr->e_ident[EI_MAG3] != 'F') ) return 0; if(elf_hdr->e_ident[EI_CLASS] != ELFCLASS32) return 0; if(elf_hdr->e_ident[EI_DATA] != ELFDATA2LSB) return 0; return 1; } void banner(void) { printf("\t~~~ .section changer ~~~\n\n"); } char* get_elf_type(Elf32_Ehdr *elf) { char *types[] = { "None" , "Relocatable" , "Executable" , "Shared Object" , "Core" , "Defined Types" }; if (elf_is_valid(elf)) return (char*)types[elf->e_type]; return NULL; } int section_header(Elf32_Shdr *shdr, char *strtable,char * section) { if(!shdr) return 0; if (!strcmp(strtable+shdr->sh_name,section)) { printf("+ Section %s\n", strtable + shdr->sh_name); printf("\t@ Address: 0x%x\n", shdr->sh_addr); printf("\t@ Offset: 0x%x\n", shdr->sh_offset); printf("\t@ Size: %d\n", shdr->sh_size); printf("\t@ Address alignment: %d\n", shdr->sh_addralign); return 1; } return 0; }