AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / unix / Perguntas / 464539
Accepted
Billy
Billy
Asked: 2018-08-24 17:42:09 +0800 CST2018-08-24 17:42:09 +0800 CST 2018-08-24 17:42:09 +0800 CST

Como posso fazer um processo específico executar um determinado executável com ptrace ()?

  • 772

Estou tentando forçar o processo de inicialização de um sistema Linux embarcado para exec()meu próprio programa de inicialização (systemd) para que eu possa testar um sistema de arquivos externo antes de gravá-lo no flash do sistema (e arriscar bloquear o dispositivo). Com o GDB, posso executar o comando gdb --pid=1, então nesse tipo de shell call execl("/lib/systemd/systemd", "systemd", 0)(que funciona exatamente como eu preciso), mas não tenho espaço suficiente para colocar o GDB na flash do sistema.

Eu queria saber exatamente quais ptrace()chamadas o GDB usa com seu callcomando para que eu possa implementar isso em meu próprio programa C simples.

Tentei usar stracepara descobrir quais ptrace()chamadas o GDB usava, mas o arquivo resultante tinha 172.031 linhas. Eu também tentei olhar através de seu código-fonte, mas havia muitos arquivos para encontrar o que eu estava procurando.

O dispositivo está executando o kernel Linux versão 3.10.0, a configuração está disponível aqui: https://pastebin.com/rk0Zux62

linux system-calls
  • 1 1 respostas
  • 951 Views

1 respostas

  • Voted
  1. Best Answer
    Joseph Sible-Reinstate Monica
    2018-09-03T21:29:57+08:002018-09-03T21:29:57+08:00

    Aqui está um programa C que deve fazer isso. Observe alguns problemas conhecidos:

    • Provavelmente deve usar memcpy em vez de violações estritas de alias
    • Usa suas próprias variáveis ​​de ambiente em vez das variáveis ​​de ambiente do tracee antigo
    • Se o tracee não fizer syscalls, isso nunca conseguirá fazer nada
    • Não verifica quando o tracee é interrompido para ter certeza de que é realmente uma parada de syscall e não uma parada de sinal ou algo assim
    • Deve definir o IP de volta em syscall-exit-stop em vez de syscall-enter-stop
    • Não faz nenhuma verificação de sanidade dos argumentos execve (fazer isso seria uma boa oportunidade para execveat)
    • Completamente não portátil (hardcodes CONFIG_ARM_THUMBentre muitas outras coisas)
    • Deixa o processo em um estado em que provavelmente travará se alguma das syscalls não funcionar corretamente

    Compile-o com -fno-strict-aliasing, depois execute-o como ./a.out 1 /lib/systemd/systemd systemd.

    #include <stdio.h>
    #include <errno.h>
    #include <string.h>
    #include <stdlib.h>
    #include <sys/types.h>
    #include <sys/ptrace.h>
    #include <linux/ptrace.h>
    #include <sys/wait.h>
    #include <sys/user.h>
    #include <sys/syscall.h>
    #include <sys/mman.h>
    
    #define CONFIG_ARM_THUMB
    
    #ifdef CONFIG_ARM_THUMB
    #define thumb_mode(regs) \
            (((regs)->ARM_cpsr & PSR_T_BIT))
    #else
    #define thumb_mode(regs) (0)
    #endif
    
    extern char **environ;
    
    static pid_t pid;
    
    /* The length of a string, plus the null terminator, rounded up to the nearest sizeof(long). */
    size_t str_size(char *str) {
            size_t len = strlen(str);
            return len + sizeof(long) - len % sizeof(long);
    }
    
    void must_poke(long addr, long data) {
            if(ptrace(PTRACE_POKEDATA, pid, (void*)addr, (void*)data)) {
                    perror("ptrace(PTRACE_POKEDATA, ...)");
                    exit(1);
            }
    }
    
    void must_poke_multi(long addr, long* data, size_t len) {
            size_t i;
            for(i = 0; i < len; ++i) {
                    must_poke(addr + i * sizeof(long), data[i]);
            }
    }
    
    long must_poke_string(long addr, char* str) {
            size_t len = str_size(str);
            size_t longs_len = len / sizeof(long);
            char *more_nulls_str = malloc(len);
            memset(more_nulls_str + len - sizeof(long), 0, sizeof(long)); /* initialize the bit we might not copy over */
            strcpy(more_nulls_str, str);
            must_poke_multi(addr, (long*)more_nulls_str, longs_len);
            free(more_nulls_str);
            return addr + len;
    }
    
    int main(int argc, char** argv) {
            struct user_regs regs;
            int i, envc;
            unsigned long mmap_base;
            size_t mmap_string_offset, mmap_argv_offset, mmap_envp_offset;
            size_t mmap_len = 2 * sizeof(char*); /* for the NULLs at the end of argv and envp */
    
            if(argc < 3) {
                    fprintf(stderr, "Usage: %s <pid> <executable image> <args...>\n", argv[0]);
                    return 1;
            }
    
            pid = strtol(argv[1], NULL, 10);
    
            /* for the image name */
            mmap_len += str_size(argv[2]);
    
            for(i = 3; i < argc; ++i) {
                    /* for the pointer in argv plus the string itself */
                    mmap_len += sizeof(char*) + str_size(argv[i]);
            }
    
            for(i = 0; environ[i]; ++i) {
                    /* for the pointer in envp plus the string itself */
                    mmap_len += sizeof(char*) + str_size(environ[i]);
            }
            envc = i;
    
            if(ptrace(PTRACE_ATTACH, pid, 0, 0)) {
                    perror("ptrace(PTRACE_ATTACH, ...)");
                    return 1;
            }
            if(waitid(P_PID, pid, NULL, WSTOPPED)) {
                    perror("waitid");
                    return 1;
            }
    
            /* Stop at whatever syscall happens to be next */
            if(ptrace(PTRACE_SYSCALL, pid, 0, 0)) {
                    perror("ptrace(PTRACE_SYSCALL, ...)");
                    return 1;
            }
            printf("Waiting for the target process to make a syscall...\n");
            if(waitid(P_PID, pid, NULL, WSTOPPED)) {
                    perror("waitid");
                    return 1;
            }
            printf("Target made a syscall. Proceeding with injection.\n");
    
            if(ptrace(PTRACE_GETREGS, pid, 0, &regs)) {
                    perror("ptrace(PTRACE_GETREGS, ...)");
                    return 1;
            }
    
            /* End up back on the syscall instruction so we can use it again */
            regs.ARM_pc -= (thumb_mode(&regs) ? 2 : 4);
    
            /* mmap some space for the exec parameters */
            regs.ARM_r0 = (long)0;
            regs.ARM_r1 = (long)mmap_len;
            regs.ARM_r2 = (long)(PROT_READ|PROT_WRITE);
            regs.ARM_r3 = (long)(MAP_PRIVATE|MAP_ANONYMOUS);
            regs.ARM_r4 = (long)-1;
            regs.ARM_r5 = (long)0;
            if(ptrace(PTRACE_SETREGS, pid, 0, &regs)) {
                    perror("ptrace(PTRACE_SETREGS, ...)");
                    return 1;
            }
            if(ptrace(PTRACE_SET_SYSCALL, pid, 0, SYS_mmap2)) {
                    perror("ptrace(PTRACE_SET_SYSCALL, ...)");
                    return 1;
            }
    
            /* jump to the end of the syscall */
            if(ptrace(PTRACE_SYSCALL, pid, 0, 0)) {
                    perror("ptrace(PTRACE_SYSCALL, ...)");
                    return 1;
            }
            if(waitid(P_PID, pid, NULL, WSTOPPED)) {
                    perror("waitid");
                    return 1;
            }
    
            /* make sure it worked and get the memory address */
            if(ptrace(PTRACE_GETREGS, pid, 0, &regs)) {
                    perror("ptrace(PTRACE_GETREGS, ...)");
                    return 1;
            }
    
            if(regs.ARM_r0 > -4096UL) {
                    errno = -regs.ARM_r0;
                    perror("traced process: mmap");
                    return 1;
            }
            mmap_base = regs.ARM_r0;
    
            /* set up the execve args in memory */
            mmap_argv_offset = must_poke_string(mmap_base, argv[2]);
    
            mmap_string_offset = mmap_argv_offset + (argc - 2) * sizeof(char*); /* don't forget the null pointer */
            for(i = 0; i < argc - 3; ++i) {
                    must_poke(mmap_argv_offset + i * sizeof(char*), mmap_string_offset);
                    mmap_string_offset = must_poke_string(mmap_string_offset, argv[i + 3]);
            }
            must_poke(mmap_argv_offset + (argc - 3) * sizeof(char*), 0);
            mmap_envp_offset = mmap_string_offset;
            mmap_string_offset = mmap_envp_offset + (envc + 1) * sizeof(char*); /* don't forget the null pointer */
            for(i = 0; i < envc; ++i) {
                    must_poke(mmap_envp_offset + i * sizeof(char*), mmap_string_offset);
                    mmap_string_offset = must_poke_string(mmap_string_offset, environ[i]);
            }
            must_poke(mmap_envp_offset + envc * sizeof(char*), 0);
    
            /* jump to the start of the next syscall (same PC since we reset it) */
            if(ptrace(PTRACE_SYSCALL, pid, 0, 0)) {
                    perror("ptrace(PTRACE_SYSCALL, ...)");
                    return 1;
            }
            if(waitid(P_PID, pid, NULL, WSTOPPED)) {
                    perror("waitid");
                    return 1;
            }
    
            if(ptrace(PTRACE_GETREGS, pid, 0, &regs)) {
                    perror("ptrace(PTRACE_GETREGS, ...)");
                    return 1;
            }
    
            /* call execve */
            regs.ARM_r0 = (long)mmap_base;
            regs.ARM_r1 = (long)mmap_argv_offset;
            regs.ARM_r2 = (long)mmap_envp_offset;
            if(ptrace(PTRACE_SETREGS, pid, 0, &regs)) {
                    perror("ptrace(PTRACE_SETREGS, ...)");
                    return 1;
            }
            if(ptrace(PTRACE_SET_SYSCALL, pid, 0, SYS_execve)) {
                    perror("ptrace(PTRACE_SET_SYSCALL, ...)");
                    return 1;
            }
    
            /* and done. */
            if(ptrace(PTRACE_DETACH, pid, 0, 0)) {
                    perror("ptrace(PTRACE_DETACH, ...)");
                    return 1;
            }
            return 0;
    }
    

    Eu desenvolvi e testei isso via qemu-system-arm com o kernel 3.2.0-4 e a área de usuário wheezy de https://people.debian.org/~aurel32/qemu/armel/

    • 3

relate perguntas

  • Inicie/pare o serviço systemd usando o atalho de teclado [fechado]

  • Necessidade de algumas chamadas de sistema

  • astyle não altera a formatação do arquivo de origem

  • Passe o sistema de arquivos raiz por rótulo para o kernel do Linux

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Como exportar uma chave privada GPG e uma chave pública para um arquivo

    • 4 respostas
  • Marko Smith

    ssh Não é possível negociar: "nenhuma cifra correspondente encontrada", está rejeitando o cbc

    • 4 respostas
  • Marko Smith

    Como podemos executar um comando armazenado em uma variável?

    • 5 respostas
  • Marko Smith

    Como configurar o systemd-resolved e o systemd-networkd para usar o servidor DNS local para resolver domínios locais e o servidor DNS remoto para domínios remotos?

    • 3 respostas
  • Marko Smith

    Como descarregar o módulo do kernel 'nvidia-drm'?

    • 13 respostas
  • Marko Smith

    apt-get update error no Kali Linux após a atualização do dist [duplicado]

    • 2 respostas
  • Marko Smith

    Como ver as últimas linhas x do log de serviço systemctl

    • 5 respostas
  • Marko Smith

    Nano - pule para o final do arquivo

    • 8 respostas
  • Marko Smith

    erro grub: você precisa carregar o kernel primeiro

    • 4 respostas
  • Marko Smith

    Como baixar o pacote não instalá-lo com o comando apt-get?

    • 7 respostas
  • Martin Hope
    rocky Como exportar uma chave privada GPG e uma chave pública para um arquivo 2018-11-16 05:36:15 +0800 CST
  • Martin Hope
    Wong Jia Hau ssh-add retorna com: "Erro ao conectar ao agente: nenhum arquivo ou diretório" 2018-08-24 23:28:13 +0800 CST
  • Martin Hope
    Evan Carroll status systemctl mostra: "Estado: degradado" 2018-06-03 18:48:17 +0800 CST
  • Martin Hope
    Tim Como podemos executar um comando armazenado em uma variável? 2018-05-21 04:46:29 +0800 CST
  • Martin Hope
    Ankur S Por que /dev/null é um arquivo? Por que sua função não é implementada como um programa simples? 2018-04-17 07:28:04 +0800 CST
  • Martin Hope
    user3191334 Como ver as últimas linhas x do log de serviço systemctl 2018-02-07 00:14:16 +0800 CST
  • Martin Hope
    Marko Pacak Nano - pule para o final do arquivo 2018-02-01 01:53:03 +0800 CST
  • Martin Hope
    Kidburla Por que verdadeiro e falso são tão grandes? 2018-01-26 12:14:47 +0800 CST
  • Martin Hope
    Christos Baziotis Substitua a string em um arquivo de texto enorme (70 GB), uma linha 2017-12-30 06:58:33 +0800 CST
  • Martin Hope
    Bagas Sanjaya Por que o Linux usa LF como caractere de nova linha? 2017-12-20 05:48:21 +0800 CST

Hot tag

linux bash debian shell-script text-processing ubuntu centos shell awk ssh

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve