blob: 368f4b057fec95ab19657ab114f7b9856fa1f1f6 [file] [log] [blame]
Alexey Ivanov777e8022019-01-03 13:46:38 -08001#!/usr/bin/env python
Brendan Gregg12989982016-09-14 08:15:09 -07002# @lint-avoid-python-3-compatibility-imports
3#
4# capable Trace security capabilitiy checks (cap_capable()).
5# For Linux, uses BCC, eBPF. Embedded C.
6#
Andrea Righi8417f692018-11-15 03:13:45 +01007# USAGE: capable [-h] [-v] [-p PID] [-K] [-U]
Brendan Gregg12989982016-09-14 08:15:09 -07008#
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
Andrea Righi8417f692018-11-15 03:13:45 +010015from os import getpid
16from functools import partial
Brendan Gregg12989982016-09-14 08:15:09 -070017from bcc import BPF
Andrea Righi8417f692018-11-15 03:13:45 +010018import errno
Brendan Gregg12989982016-09-14 08:15:09 -070019import 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
Andrea Righi8417f692018-11-15 03:13:45 +010028 ./capable -K # add kernel stacks to trace
29 ./capable -U # add user-space stacks to trace
Brendan Gregg12989982016-09-14 08:15:09 -070030"""
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")
Andrea Righi8417f692018-11-15 03:13:45 +010039parser.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")
Brendan Gregg12989982016-09-14 08:15:09 -070043args = 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
Andrea Righi8417f692018-11-15 03:13:45 +010090class 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
Brendan Gregg12989982016-09-14 08:15:09 -070099# define BPF program
100bpf_text = """
101#include <uapi/linux/ptrace.h>
102#include <linux/sched.h>
103
104struct data_t {
Andrea Righi8417f692018-11-15 03:13:45 +0100105 u32 tgid;
106 u32 pid;
107 u32 uid;
Brendan Gregg12989982016-09-14 08:15:09 -0700108 int cap;
109 int audit;
110 char comm[TASK_COMM_LEN];
Andrea Righi8417f692018-11-15 03:13:45 +0100111#ifdef KERNEL_STACKS
112 int kernel_stack_id;
113#endif
114#ifdef USER_STACKS
115 int user_stack_id;
116#endif
Brendan Gregg12989982016-09-14 08:15:09 -0700117};
118
119BPF_PERF_OUTPUT(events);
120
Andrea Righi8417f692018-11-15 03:13:45 +0100121#if defined(USER_STACKS) || defined(KERNEL_STACKS)
122BPF_STACK_TRACE(stacks, 2048);
123#endif
124
Brendan Gregg12989982016-09-14 08:15:09 -0700125int kprobe__cap_capable(struct pt_regs *ctx, const struct cred *cred,
126 struct user_namespace *targ_ns, int cap, int audit)
127{
Andrea Righi8417f692018-11-15 03:13:45 +0100128 u64 __pid_tgid = bpf_get_current_pid_tgid();
129 u32 tgid = __pid_tgid >> 32;
130 u32 pid = __pid_tgid;
Brendan Gregg12989982016-09-14 08:15:09 -0700131 FILTER1
132 FILTER2
Andrea Righi8417f692018-11-15 03:13:45 +0100133 FILTER3
Brendan Gregg12989982016-09-14 08:15:09 -0700134
135 u32 uid = bpf_get_current_uid_gid();
Andrea Righi8417f692018-11-15 03:13:45 +0100136 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
Brendan Gregg12989982016-09-14 08:15:09 -0700143 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; }')
Andrea Righi8417f692018-11-15 03:13:45 +0100154if 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
Brendan Gregg12989982016-09-14 08:15:09 -0700158bpf_text = bpf_text.replace('FILTER1', '')
159bpf_text = bpf_text.replace('FILTER2', '')
Andrea Righi8417f692018-11-15 03:13:45 +0100160bpf_text = bpf_text.replace('FILTER3',
161 'if (pid == %s) { return 0; }' % getpid())
Brendan Gregg12989982016-09-14 08:15:09 -0700162if 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_ = [
Andrea Righi8417f692018-11-15 03:13:45 +0100172 ("tgid", ct.c_uint32),
173 ("pid", ct.c_uint32),
174 ("uid", ct.c_uint32),
Brendan Gregg12989982016-09-14 08:15:09 -0700175 ("cap", ct.c_int),
176 ("audit", ct.c_int),
Andrea Righi8417f692018-11-15 03:13:45 +0100177 ("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 [])
Brendan Gregg12989982016-09-14 08:15:09 -0700180
181# header
Andrea Righi8417f692018-11-15 03:13:45 +0100182print("%-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)))
Brendan Gregg12989982016-09-14 08:15:09 -0700198
199# process event
Andrea Righi8417f692018-11-15 03:13:45 +0100200def print_event(bpf, cpu, data, size):
Brendan Gregg12989982016-09-14 08:15:09 -0700201 event = ct.cast(data, ct.POINTER(Data)).contents
202
203 if event.cap in capabilities:
204 name = capabilities[event.cap]
205 else:
206 name = "?"
Andrea Righi8417f692018-11-15 03:13:45 +0100207 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'),
jeromemarchandb96ebcd2018-10-10 01:58:15 +0200209 event.cap, name, event.audit))
Andrea Righi8417f692018-11-15 03:13:45 +0100210 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)
Brendan Gregg12989982016-09-14 08:15:09 -0700214
215# loop with callback to print_event
Andrea Righi8417f692018-11-15 03:13:45 +0100216callback = partial(print_event, b)
217b["events"].open_perf_buffer(callback)
Brendan Gregg12989982016-09-14 08:15:09 -0700218while 1:
Jerome Marchand51671272018-12-19 01:57:24 +0100219 try:
220 b.perf_buffer_poll()
221 except KeyboardInterrupt:
222 exit()