Skip to content

Instantly share code, notes, and snippets.

@kohnakagawa
Created July 27, 2019 02:23
Show Gist options
  • Save kohnakagawa/7e469a9d2ed496b0fb036ceaf4834b52 to your computer and use it in GitHub Desktop.
Save kohnakagawa/7e469a9d2ed496b0fb036ceaf4834b52 to your computer and use it in GitHub Desktop.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <linux/elf.h>
#include <sys/ptrace.h>
#include <linux/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/syscall.h>
#include <sys/user.h>
#include <errno.h>
#include <signal.h>
struct iovec {
void *iov_base;
unsigned int iov_len;
};
void err(char *str)
{
fprintf(stderr, "ERROR: %s\n", str);
}
void target(char *argv[], char *argp[])
{
if(ptrace(PTRACE_TRACEME, 0, NULL, NULL) != -1)
execve(argv[0], argv, argp);
else
err("PTRACE_TRACEME");
exit(0);
}
void controler(int pid)
{
int status;
struct user_regs_struct regs = {0};
struct iovec iov;
siginfo_t sif;
int flag = 0;
while (1) {
iov.iov_len = sizeof(regs);
iov.iov_base = &regs;
memset(&regs, 0, sizeof(regs));
waitpid(pid, &status, 0);
if (WIFEXITED(status)) break;
if (WIFSTOPPED(status)) {
if (WSTOPSIG(status) != SIGTRAP) continue;
int ret = ptrace(PTRACE_GETREGSET, pid, NT_PRSTATUS, &iov);
printf("%d %d\n", ret, errno);
printf("%llx: \n", regs.pc);
ret = ptrace(PTRACE_GETSIGINFO, pid, NULL, &sif);
printf("%d %d\n", ret, sif.si_signo);
if (sif.si_signo == SIGTRAP && flag) {
ret = ptrace(PTRACE_SETREGSET, pid, NT_PRSTATUS, &iov);
printf("%d\n", ret);
printf("%d\n", regs.a5);
ptrace(PTRACE_KILL, pid, 0, NULL);
}
if (sif.si_signo == SIGTRAP && regs.pc == 0x10542) {
regs.pc += 2;
ret = ptrace(PTRACE_SETREGSET, pid, NT_PRSTATUS, &iov);
printf("%d\n", ret);
printf("%d\n", regs.a5);
flag = 1;
}
ret = ptrace(PTRACE_SYSCALL, pid, 0, NULL);
}
ptrace(PTRACE_CONT, pid, 0, NULL);
}
}
int exec_prog(char *argv[], char *argp[])
{
int pid;
switch(pid = fork())
{
case 0:
target(argv, argp);
break;
case -1:
err("FORK");
break;
default:
controler(pid);
break;
}
return 0;
}
int main(int argc, char *argv[], char *argp[])
{
if(argc < 2){
fprintf(stderr, "%s <args>\n", argv[0]);
return 1;
}
argv++;
exec_prog(argv, argp);
return 0;
}
int main()
{
__asm__ __volatile__ ("ebreak\n\t"
"addiw a5,a5,5\n\t"
"ebreak\n\t");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment