| 1 |
#! /bin/sh |
| 2 |
|
| 3 |
# Disable ptrace(2) on a dynamic list of processes, by rewriting the |
| 4 |
# incoming arguments on an attempted ptrace(2) syscall. The list of |
| 5 |
# processes is enlarged upon fork(), shrunken by exit(), and may be |
| 6 |
# edited interactively with a set of /proc files. |
| 7 |
|
| 8 |
# note use of guru mode, to enable changing of syscall arguments |
| 9 |
//bin/true && exec stap -g $0 ${1+"$@"} |
| 10 |
|
| 11 |
global noptrace # map pid->name: list of pids forbidden from ptrace(2) |
| 12 |
|
| 13 |
|
| 14 |
probe begin { # init. noptrace process list with stap -x PID/-c CMD, if given |
| 15 |
if (target()) |
| 16 |
noptrace[target()]="?" |
| 17 |
} |
| 18 |
|
| 19 |
probe scheduler.process_fork { # propagate flag to child processes |
| 20 |
if (parent_pid in noptrace) |
| 21 |
noptrace[child_pid] = noptrace[parent_pid] |
| 22 |
} |
| 23 |
|
| 24 |
probe syscall.*execve { # update stored pid->name mapping |
| 25 |
if (pid() in noptrace) |
| 26 |
noptrace[pid()] = filename |
| 27 |
} |
| 28 |
|
| 29 |
probe syscall.exit { # optional; clean up pid->name mapping table |
| 30 |
delete noptrace[pid()] |
| 31 |
} |
| 32 |
|
| 33 |
# procfs control files under /proc/systemtap/stap_XXXXX/ |
| 34 |
|
| 35 |
probe procfs("blocked").read { # report currently blocked processes |
| 36 |
foreach (pid in noptrace) |
| 37 |
$value .= sprintf("%d %s\n",pid,noptrace[pid]) |
| 38 |
} |
| 39 |
|
| 40 |
probe procfs("block").write { # block given pid |
| 41 |
pid = strtol($value,10) |
| 42 |
noptrace[pid]="?" |
| 43 |
} |
| 44 |
|
| 45 |
probe procfs("unblock").write { # unblock given pid |
| 46 |
pid = strtol($value,10) |
| 47 |
delete noptrace[pid] |
| 48 |
} |
| 49 |
|
| 50 |
# payload |
| 51 |
|
| 52 |
global deny_ptrace |
| 53 |
|
| 54 |
probe kernel.function("cap_ptrace_traceme").return, |
| 55 |
kernel.function("cap_ptrace_access_check").return |
| 56 |
{ |
| 57 |
if (tid() in deny_ptrace) { |
| 58 |
$return = -1 /* -EPERM */ |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
probe syscall.ptrace { |
| 63 |
if (pid() in noptrace) { |
| 64 |
# report |
| 65 |
printf ("%s[%d] ptrace(%d) blocked: ", execname(), tid(), request) |
| 66 |
# (or if desired, accumulate counts and report at probe end {}) |
| 67 |
|
| 68 |
# disable the ptrace call in progress |
| 69 |
# if it weren't for PTRACE_TRACEME, we could set $pid=1 => -EPERM |
| 70 |
# instead make the capability check fail with -PERM |
| 71 |
deny_ptrace [tid()] = 1 |
| 72 |
} |
| 73 |
} |
| 74 |
|
| 75 |
probe syscall.ptrace.return { # should occur instantly |
| 76 |
if (pid() in noptrace) { |
| 77 |
printf ("rc=%d\n", retval) |
| 78 |
} |
| 79 |
delete deny_ptrace [tid()] |
| 80 |
} |