修改寄存器的值:
#include <stdio.h>
#include <stdlib.h>
#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/reg.h>
#include <linux/user.h>
#include <string.h>
#include <fcntl.h>
#include <limits.h>
static void usage(FILE *stream)
{
fprintf(stream, "Usage: register PID value\n");
}
int main(int argc, char *argv[])
{
pid_t traced_process;
struct user_regs_struct regs;
long orig_eax;
// long addr;
long num;
int insyscall = 0;
int status;
int ret;
// long edi;
if(argc < 2){
usage(stdout);
return -1;
}
traced_process = atoi(argv[1]);
//ret = kill(traced_process, 0);
//f(ret < 0){
// fprintf(stderr, "process does not exit\n");
// return -1;
//}
//num = atoi(argv[2]);
num = 6666;
ptrace(PTRACE_ATTACH, traced_process, NULL, NULL);
while(1){
wait(&status);
if(WIFEXITED(status))
break;
orig_eax = ptrace(PTRACE_PEEKUSER, traced_process, 4*ORIG_EAX, NULL);
//printf("the value of orig_eax is %ld\n", orig_eax);
if(orig_eax == SYS_write){
if(insyscall == 0){
insyscall = 1;
//ptrace(PTRACE_POKEUSER, traced_process, 4*EDI, num);
ptrace(PTRACE_GETREGS, traced_process, NULL, ®s);
regs.eax = num;
ptrace(PTRACE_SETREGS, traced_process, NULL, ®s);
printf("new value of eax is %ld\n", regs.eax); //cs,orig_eax, ss,无效
}
else{
insyscall = 0;
ptrace(PTRACE_DETACH, traced_process, NULL, NULL);
break;
}
}
ptrace(PTRACE_SYSCALL, traced_process, NULL, NULL);
}
return 0;
}
对目标进程的栈进行故障注入:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/reg.h>
#include <linux/user.h>
#include <string.h>
#include <fcntl.h>
#include <limits.h>
static void usage(FILE *stream)
{
fprintf(stream, "Usage: register PID value\n");
}
int main(int argc, char *argv[])
{
//int running = 1;
int ret;
pid_t traced_process;
long orig_eax;
long num;
long long addr;
int insyscall = 0;
int status;
key_t key;
//printf("BUFSIZ: %d\n", BUFSIZ);
if(argc < 2){
usage(stdout);
return -1;
}
traced_process = atoi(argv[1]);
// ret = kill(traced_process, 0);
// if(ret < 0){
// fprintf(stderr, "process does not exit\n");
// return -1;
// }
//num = atoi(argv[2]);
num = 88;
//key = (key_t)traced_process;
addr = (long long)atof(argv[2]); //进行故障注入的地址
printf("inject the fault of stack in address: %lld, 0x%x\n", addr, (unsigned int)addr);
ptrace(PTRACE_ATTACH, traced_process, NULL, NULL);
while(1){
wait(&status);
if(WIFEXITED(status))
break;
orig_eax = ptrace(PTRACE_PEEKUSER, traced_process, 4*ORIG_EAX, NULL);
if(orig_eax == SYS_write){
if(insyscall == 0){
insyscall = 1;
ptrace(PTRACE_POKEDATA, traced_process, addr, num);
}
else{
insyscall = 0;
ptrace(PTRACE_DETACH, traced_process, NULL, NULL);
break;
}
}
ptrace(PTRACE_SYSCALL, traced_process, NULL, NULL);
}
return 0;
}