Search code examples
goptrace

how to detect if ptrace already called in golang linux


I am learning golang and I wanna implement a simple Linux anti-debugging method in golang. I have a CPP code which works in the same way I intended. But cannot do the same in golang. can you guys guide me how to do same in go?

Here is the C++ Code I am using as a reference.

#include <stdio.h>
#include <sys/ptrace.h>


bool isBeingTraced(){
    return ptrace(PTRACE_TRACEME, 0, 1, 0) == -1;
}

int main()
{
    if (isBeingTraced()) 
    {
        printf("don't trace me !!\n");
        return 1;
    }
    printf("Not being traced...  (maybe)\n");
    return 0;
}

And I wanna do the same thing in go lang. Is it even possible to do the same in go?

package main

import "fmt"

func main() {
    if isBeingTraced() {
        fmt.Println("don't trace me !!")
        return
    }

    fmt.Println("Not being traced...  (maybe)")
}

func isBeingTraced() bool {
    return true // How to Implement that Cpp Function here?
}

Solution

  • Based on @MarkPlotnick's comments, here is the golang Equivalent code for the c++ code posted by me.

    package main
    
    import (
        "fmt"
        "syscall"
    )
    
    func main() {
        if isBeingTraced() {
            fmt.Println("don't trace me !!")
            return
        }
    
        fmt.Println("Not being traced...  (maybe)")
    }
    
    func isBeingTraced() bool { 
        _, _, res := syscall.RawSyscall(syscall.SYS_PTRACE, uintptr(syscall.PTRACE_TRACEME), 0, 0)
        return res == 1
    }
    

    Ref: https://github.com/golang/go/blob/master/src/syscall/exec_linux.go#L511

    But the problem I have been with this code is, You cannot call exec.Command() after calling PTRACE_TRACEME. Will try to find a solution to this problem. and if I got any, I will reference it here.