1#!/usr/bin/env python 2# @lint-avoid-python-3-compatibility-imports 3# 4# capable Trace security capabilitiy checks (cap_capable()). 5# For Linux, uses BCC, eBPF. Embedded C. 6# 7# USAGE: capable [-h] [-v] [-p PID] [-K] [-U] 8# 9# Copyright 2016 Netflix, Inc. 10# Licensed under the Apache License, Version 2.0 (the "License") 11# 12# 13-Sep-2016 Brendan Gregg Created this. 13 14from __future__ import print_function 15from os import getpid 16from functools import partial 17from bcc import BPF 18import errno 19import argparse 20from time import strftime 21import ctypes as ct 22 23# arguments 24examples = """examples: 25 ./capable # trace capability checks 26 ./capable -v # verbose: include non-audit checks 27 ./capable -p 181 # only trace PID 181 28 ./capable -K # add kernel stacks to trace 29 ./capable -U # add user-space stacks to trace 30""" 31parser = argparse.ArgumentParser( 32 description="Trace security capability checks", 33 formatter_class=argparse.RawDescriptionHelpFormatter, 34 epilog=examples) 35parser.add_argument("-v", "--verbose", action="store_true", 36 help="include non-audit checks") 37parser.add_argument("-p", "--pid", 38 help="trace this PID only") 39parser.add_argument("-K", "--kernel-stack", action="store_true", 40 help="output kernel stack trace") 41parser.add_argument("-U", "--user-stack", action="store_true", 42 help="output user stack trace") 43args = parser.parse_args() 44debug = 0 45 46# capabilities to names, generated from (and will need updating): 47# awk '/^#define.CAP_.*[0-9]$/ { print " " $3 ": \"" $2 "\"," }' \ 48# include/uapi/linux/capability.h 49capabilities = { 50 0: "CAP_CHOWN", 51 1: "CAP_DAC_OVERRIDE", 52 2: "CAP_DAC_READ_SEARCH", 53 3: "CAP_FOWNER", 54 4: "CAP_FSETID", 55 5: "CAP_KILL", 56 6: "CAP_SETGID", 57 7: "CAP_SETUID", 58 8: "CAP_SETPCAP", 59 9: "CAP_LINUX_IMMUTABLE", 60 10: "CAP_NET_BIND_SERVICE", 61 11: "CAP_NET_BROADCAST", 62 12: "CAP_NET_ADMIN", 63 13: "CAP_NET_RAW", 64 14: "CAP_IPC_LOCK", 65 15: "CAP_IPC_OWNER", 66 16: "CAP_SYS_MODULE", 67 17: "CAP_SYS_RAWIO", 68 18: "CAP_SYS_CHROOT", 69 19: "CAP_SYS_PTRACE", 70 20: "CAP_SYS_PACCT", 71 21: "CAP_SYS_ADMIN", 72 22: "CAP_SYS_BOOT", 73 23: "CAP_SYS_NICE", 74 24: "CAP_SYS_RESOURCE", 75 25: "CAP_SYS_TIME", 76 26: "CAP_SYS_TTY_CONFIG", 77 27: "CAP_MKNOD", 78 28: "CAP_LEASE", 79 29: "CAP_AUDIT_WRITE", 80 30: "CAP_AUDIT_CONTROL", 81 31: "CAP_SETFCAP", 82 32: "CAP_MAC_OVERRIDE", 83 33: "CAP_MAC_ADMIN", 84 34: "CAP_SYSLOG", 85 35: "CAP_WAKE_ALARM", 86 36: "CAP_BLOCK_SUSPEND", 87 37: "CAP_AUDIT_READ", 88} 89 90class Enum(set): 91 def __getattr__(self, name): 92 if name in self: 93 return name 94 raise AttributeError 95 96# Stack trace types 97StackType = Enum(("Kernel", "User",)) 98 99# define BPF program 100bpf_text = """ 101#include <uapi/linux/ptrace.h> 102#include <linux/sched.h> 103 104struct data_t { 105 u32 tgid; 106 u32 pid; 107 u32 uid; 108 int cap; 109 int audit; 110 char comm[TASK_COMM_LEN]; 111#ifdef KERNEL_STACKS 112 int kernel_stack_id; 113#endif 114#ifdef USER_STACKS 115 int user_stack_id; 116#endif 117}; 118 119BPF_PERF_OUTPUT(events); 120 121#if defined(USER_STACKS) || defined(KERNEL_STACKS) 122BPF_STACK_TRACE(stacks, 2048); 123#endif 124 125int kprobe__cap_capable(struct pt_regs *ctx, const struct cred *cred, 126 struct user_namespace *targ_ns, int cap, int audit) 127{ 128 u64 __pid_tgid = bpf_get_current_pid_tgid(); 129 u32 tgid = __pid_tgid >> 32; 130 u32 pid = __pid_tgid; 131 FILTER1 132 FILTER2 133 FILTER3 134 135 u32 uid = bpf_get_current_uid_gid(); 136 struct data_t data = {.tgid = tgid, .pid = pid, .uid = uid, .cap = cap, .audit = audit}; 137#ifdef KERNEL_STACKS 138 data.kernel_stack_id = stacks.get_stackid(ctx, 0); 139#endif 140#ifdef USER_STACKS 141 data.user_stack_id = stacks.get_stackid(ctx, BPF_F_USER_STACK); 142#endif 143 bpf_get_current_comm(&data.comm, sizeof(data.comm)); 144 events.perf_submit(ctx, &data, sizeof(data)); 145 146 return 0; 147}; 148""" 149if args.pid: 150 bpf_text = bpf_text.replace('FILTER1', 151 'if (pid != %s) { return 0; }' % args.pid) 152if not args.verbose: 153 bpf_text = bpf_text.replace('FILTER2', 'if (audit == 0) { return 0; }') 154if args.kernel_stack: 155 bpf_text = "#define KERNEL_STACKS\n" + bpf_text 156if args.user_stack: 157 bpf_text = "#define USER_STACKS\n" + bpf_text 158bpf_text = bpf_text.replace('FILTER1', '') 159bpf_text = bpf_text.replace('FILTER2', '') 160bpf_text = bpf_text.replace('FILTER3', 161 'if (pid == %s) { return 0; }' % getpid()) 162if debug: 163 print(bpf_text) 164 165# initialize BPF 166b = BPF(text=bpf_text) 167 168TASK_COMM_LEN = 16 # linux/sched.h 169 170class Data(ct.Structure): 171 _fields_ = [ 172 ("tgid", ct.c_uint32), 173 ("pid", ct.c_uint32), 174 ("uid", ct.c_uint32), 175 ("cap", ct.c_int), 176 ("audit", ct.c_int), 177 ("comm", ct.c_char * TASK_COMM_LEN), 178 ] + ([("kernel_stack_id", ct.c_int)] if args.kernel_stack else []) \ 179 + ([("user_stack_id", ct.c_int)] if args.user_stack else []) 180 181# header 182print("%-9s %-6s %-6s %-6s %-16s %-4s %-20s %s" % ( 183 "TIME", "UID", "PID", "TID", "COMM", "CAP", "NAME", "AUDIT")) 184 185def stack_id_err(stack_id): 186 # -EFAULT in get_stackid normally means the stack-trace is not availible, 187 # Such as getting kernel stack trace in userspace code 188 return (stack_id < 0) and (stack_id != -errno.EFAULT) 189 190def print_stack(bpf, stack_id, stack_type, tgid): 191 if stack_id_err(stack_id): 192 print(" [Missed %s Stack]" % stack_type) 193 return 194 stack = list(bpf.get_table("stacks").walk(stack_id)) 195 for addr in stack: 196 print(" ", end="") 197 print("%s" % (bpf.sym(addr, tgid, show_module=True, show_offset=True))) 198 199# process event 200def print_event(bpf, cpu, data, size): 201 event = ct.cast(data, ct.POINTER(Data)).contents 202 203 if event.cap in capabilities: 204 name = capabilities[event.cap] 205 else: 206 name = "?" 207 print("%-9s %-6d %-6d %-6d %-16s %-4d %-20s %d" % (strftime("%H:%M:%S"), 208 event.uid, event.pid, event.tgid, event.comm.decode('utf-8', 'replace'), 209 event.cap, name, event.audit)) 210 if args.kernel_stack: 211 print_stack(bpf, event.kernel_stack_id, StackType.Kernel, -1) 212 if args.user_stack: 213 print_stack(bpf, event.user_stack_id, StackType.User, event.tgid) 214 215# loop with callback to print_event 216callback = partial(print_event, b) 217b["events"].open_perf_buffer(callback) 218while 1: 219 try: 220 b.perf_buffer_poll() 221 except KeyboardInterrupt: 222 exit() 223