Debian Codegraph @

utils/pscap.c

raw
1 /*
2 * pscap.c - A program that lists running processes with capabilities
3 * Copyright (c) 2009,2012,2020 Red Hat Inc.
4 * All Rights Reserved.
5 *
6 * This software may be freely redistributed and/or modified under the
7 * terms of the GNU General Public License as published by the Free
8 * Software Foundation; either version 2, or (at your option) any
9 * later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; see the file COPYING. If not, write to the
18 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor
19 * Boston, MA 02110-1335, USA.
20 *
21 * Authors:
22 * Steve Grubb <[email protected]>
23 */
24
25 #include "config.h"
26 #include <stdio.h>
27 #include <stdio_ext.h>
28 #include <unistd.h>
29 #include <stdlib.h>
30 #include <errno.h>
31 #include <string.h>
32 #include <dirent.h>
33 #include <fcntl.h>
34 #include <pwd.h>
35 #include <stdbool.h>
36 #include <sys/stat.h>
37 #include <sys/ioctl.h>
38 #include "cap-ng.h"
39 #include "proc-sanitize.h"
40
41 #define CMD_LEN 16
42 #define ACCOUNT_LEN 32
43 #define USERNS_MARK_LEN 3 // two characters plus '\0'.
44
45 static void usage(void)
46 {
47 fprintf(stderr, "usage: pscap [-a] [-p pid] [--tree]\n");
48 exit(1);
49 }
50
51 struct proc_info {
52 pid_t pid;
53 pid_t ppid;
54 char *cmd;
55 char account[ACCOUNT_LEN];
56 char *caps_text;
57 };
58
59 static int get_euid(int pid)
60 {
61 char path[32], buf[128];
62 FILE *f;
63 int euid = -1;
64
65 snprintf(path, sizeof(path), "/proc/%d/status", pid);
66 f = fopen(path, "rte");
67 if (f == NULL)
68 return 0;
69
70 __fsetlocking(f, FSETLOCKING_BYCALLER);
71 while (fgets(buf, sizeof(buf), f)) {
72 if (memcmp(buf, "Uid:", 4) == 0) {
73 int uid;
74
75 sscanf(buf, "Uid: %d %d", &uid, &euid);
76 break;
77 }
78 }
79 fclose(f);
80
81 if (euid < 0)
82 return 0;
83
84 return euid;
85 }
86
87 static void get_account_name(int pid, char *account, size_t account_len)
88 {
89 struct passwd *p;
90 int euid;
91
92 euid = get_euid(pid);
93 if (euid == 0) {
94 strncpy(account, "root", account_len - 1);
95 account[account_len - 1] = '\0';
96 return;
97 }
98
99 p = getpwuid(euid);
100 if (p && p->pw_name) {
101 strncpy(account, p->pw_name, account_len - 1);
102 account[account_len - 1] = '\0';
103 return;
104 }
105
106 snprintf(account, account_len, "%d", euid);
107 }
108
109 static int get_width(void)
110 {
111 struct winsize ws;
112 char *e;
113 long c;
114
115 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col > 0)
116 return ws.ws_col;
117
118 e = getenv("COLUMNS");
119 if (e) {
120 char *endptr;
121
122 errno = 0;
123 c = strtol(e, &endptr, 10);
124 if (errno == 0 && endptr != e && *endptr == '\0' && c > 0 &&
125 c < 400)
126 return (int)c;
127 }
128
129 return 80;
130 }
131
132 static size_t wrap_to(const char *text, size_t max)
133 {
134 size_t len = strlen(text);
135 size_t i;
136
137 if (len <= max)
138 return len;
139
140 for (i = max; i > 0; i--) {
141 if (text[i - 1] == ',') {
142 if (i < len && text[i] == ' ')
143 return i + 1;
144 return i;
145 }
146 if (text[i - 1] == ' ')
147 return i;
148 }
149
150 return max;
151 }
152
153 /*
154 * compare_pid - order processes by pid for sorting/bsearch
155 * @a: pointer to left struct proc_info
156 * @b: pointer to right struct proc_info
157 *
158 * Returns -1, 0, or 1 for ordering.
159 */
160 static int compare_pid(const void *a, const void *b)
161 {
162 const struct proc_info *left = a;
163 const struct proc_info *right = b;
164
165 if (left->pid < right->pid)
166 return -1;
167 if (left->pid > right->pid)
168 return 1;
169 return 0;
170 }
171
172 /*
173 * find_proc - locate a process record by pid
174 * @procs: process array sorted by pid
175 * @count: number of entries in @procs
176 * @pid: process id to locate
177 *
178 * Returns pointer to the matching entry or NULL if not found.
179 */
180 static void *find_proc(struct proc_info *procs, size_t count, pid_t pid)
181 {
182 struct proc_info key;
183
184 key.pid = pid;
185 return bsearch(&key, procs, count, sizeof(*procs), compare_pid);
186 }
187
188 /*
189 * append_marker - append a marker string to the capability text
190 * @text: capability text buffer pointer to append to
191 * @marker: marker string to append (e.g. " @" or " +")
192 *
193 * Returns 0 on success, -1 on allocation failure.
194 */
195 static int append_marker(char **text, const char *marker)
196 {
197 size_t len = strlen(*text);
198 size_t marker_len = strlen(marker);
199 char *tmp = realloc(*text, len + marker_len + 1);
200
201 if (!tmp)
202 return -1;
203 memcpy(tmp + len, marker, marker_len + 1);
204 *text = tmp;
205 return 0;
206 }
207
208 /*
209 * format_caps - format capability text with optional markers
210 * @caps: capability summary state from capng_have_capabilities()
211 * @ambient: true if ambient capabilities are present
212 * @bounds: true if bounding set differs from full
213 *
214 * Returns allocated capability string or NULL on allocation failure.
215 */
216 static char *format_caps(int caps, bool ambient, bool bounds)
217 {
218 char *text;
219
220 if (caps == CAPNG_PARTIAL)
221 text = capng_print_caps_text(CAPNG_PRINT_BUFFER,
222 CAPNG_PERMITTED);
223 else if (caps == CAPNG_FULL)
224 text = strdup("full");
225 else
226 text = strdup("none");
227
228 if (!text)
229 return NULL;
230 if (ambient)
231 append_marker(&text, " @");
232 if (bounds)
233 append_marker(&text, " +");
234 return text;
235 }
236
237 /*
238 * print_tree_node - render a node and its children in tree mode
239 * @procs: process array
240 * @count: number of entries in @procs
241 * @index: index of current node in @procs
242 * @prefix: current line prefix
243 * @is_last: true if this node is the last child of its parent
244 * @is_root: true if this node is a tree root
245 *
246 * Returns nothing. Recurses through children to emit full subtree.
247 */
248 static void print_tree_node(struct proc_info *procs, size_t count,
249 size_t index, const char *prefix, bool is_last,
250 bool is_root, int width)
251 {
252 struct proc_info *proc = &procs[index];
253 size_t child_total = 0;
254 size_t child_seen = 0;
255 size_t i;
256 size_t prefix_len;
257 size_t cont_len;
258 size_t avail;
259 size_t n;
260 const char *caps;
261 char head[64];
262 const char *branch = "";
263 char *line_prefix;
264 char *cont_prefix;
265 char *child_prefix;
266
267 if (!is_root)
268 branch = is_last ? " " : "│ ";
269
270 line_prefix = malloc(strlen(prefix) + strlen(is_root ? "" :
271 (is_last ? "└─ " : "├─ ")) + 1);
272 if (!line_prefix)
273 return;
274 strcpy(line_prefix, prefix);
275 if (!is_root)
276 strcat(line_prefix, is_last ? "└─ " : "├─ ");
277
278 cont_prefix = malloc(strlen(prefix) + strlen(branch) + 1);
279 if (!cont_prefix) {
280 free(line_prefix);
281 return;
282 }
283 strcpy(cont_prefix, prefix);
284 strcat(cont_prefix, branch);
285
286 snprintf(head, sizeof(head), "%s(%d:%s) [", proc->cmd,
287 proc->pid, proc->account);
288 prefix_len = strlen(line_prefix);
289 cont_len = strlen(cont_prefix);
290 caps = proc->caps_text;
291
292 if ((int)(prefix_len + strlen(head) + strlen(caps) + 1) <= width) {
293 printf("%s%s%s]\n", line_prefix, head, caps);
294 goto children;
295 }
296
297 avail = width > (int)(prefix_len + strlen(head)) ?
298 (size_t)(width - (int)(prefix_len + strlen(head))) : 10;
299 if (avail < 10)
300 avail = 10;
301 n = wrap_to(caps, avail);
302 printf("%s%s%.*s\n", line_prefix, head, (int)n, caps);
303 caps += n;
304
305 while (*caps) {
306 avail = width > (int)cont_len ? (size_t)(width - (int)cont_len) : 10;
307 if (avail < 10)
308 avail = 10;
309 if (strlen(caps) + 1 <= avail) {
310 printf("%s%s]\n", cont_prefix, caps);
311 break;
312 }
313 n = wrap_to(caps, avail);
314 printf("%s%.*s\n", cont_prefix, (int)n, caps);
315 caps += n;
316 }
317
318 children:
319 free(line_prefix);
320 free(cont_prefix);
321
322 for (i = 0; i < count; i++) {
323 if (procs[i].ppid == proc->pid)
324 child_total++;
325 }
326
327 if (child_total == 0)
328 return;
329
330 child_prefix = malloc(strlen(prefix) + strlen(branch) + 1);
331 if (!child_prefix)
332 return;
333 strcpy(child_prefix, prefix);
334 strcat(child_prefix, branch);
335
336 for (i = 0; i < count; i++) {
337 if (procs[i].ppid != proc->pid)
338 continue;
339 child_seen++;
340 print_tree_node(procs, count, i, child_prefix,
341 child_seen == child_total, false, width);
342 }
343
344 free(child_prefix);
345 }
346
347 /*
348 * print_tree - render all process trees in pid order
349 * @procs: process array
350 * @count: number of entries in @procs
351 *
352 * Returns nothing. Each tree starts at a pid whose parent isn't present.
353 */
354 static void print_tree(struct proc_info *procs, size_t count)
355 {
356 size_t i;
357 int width = get_width();
358
359 if (count > 1)
360 qsort(procs, count, sizeof(*procs), compare_pid);
361 for (i = 0; i < count; i++) {
362 if (!find_proc(procs, count, procs[i].ppid))
363 print_tree_node(procs, count, i, "", true, true, width);
364 }
365 }
366
367 /*
368 * Precise recursive checks for parent-child relation between namespaces
369 * using ioctl() were avoided, because there didn't seem to be any case when
370 * we may dereference the namespace symlink in /proc/PID/ns for processes in
371 * user namespaces other than the current or child ones. Thus, the check just
372 * tries to dereference the link and checks that it does not point to the
373 * current NS.
374 */
375 static bool in_child_userns(int pid)
376 {
377 char ns_file_path[32];
378 struct stat statbuf;
379 ino_t own_ns_inode;
380 dev_t own_ns_dev;
381
382 if (stat("/proc/self/ns/user", &statbuf) < 0)
383 return false;
384
385 own_ns_inode = statbuf.st_ino;
386 own_ns_dev = statbuf.st_dev;
387
388 snprintf(ns_file_path, sizeof(ns_file_path), "/proc/%d/ns/user", pid);
389 if (stat(ns_file_path, &statbuf) < 0)
390 return false;
391
392 return statbuf.st_ino != own_ns_inode || statbuf.st_dev != own_ns_dev;
393 }
394
395 int main(int argc, char *argv[])
396 {
397 char *endptr = NULL;
398 DIR *d;
399 struct dirent *ent;
400 int header = 0, show_all = 0, caps;
401 pid_t our_pid = getpid();
402 pid_t target_pid = 0;
403 int uid = -1;
404 char *name = NULL;
405 int tree_mode = 0;
406 struct proc_info *procs = NULL;
407 size_t proc_count = 0;
408 size_t proc_capacity = 0;
409 size_t i;
410
411 for (i = 1; i < (size_t)argc; i++) {
412 if (strcmp(argv[i], "-a") == 0) {
413 show_all = 1;
414 continue;
415 }
416 if (strcmp(argv[i], "--tree") == 0) {
417 tree_mode = 1;
418 continue;
419 }
420 if (strcmp(argv[i], "-p") == 0) {
421 if (i + 1 >= (size_t)argc)
422 usage();
423 errno = 0;
424 target_pid = strtol(argv[++i], &endptr, 10);
425 if (errno) {
426 fprintf(stderr, "Can't read pid: %s\n",
427 argv[i]);
428 return 1;
429 }
430 if ((endptr == argv[i]) || (*endptr != '\0')
431 || !target_pid) {
432 fprintf(stderr, "Invalid pid argument: %s\n",
433 argv[i]);
434 return 1;
435 }
436 if (target_pid == 1)
437 show_all = 1;
438 continue;
439 }
440 usage();
441 }
442
443 d = opendir("/proc");
444 if (d == NULL) {
445 fprintf(stderr, "Can't open /proc: %s\n", strerror(errno));
446 return 1;
447 }
448 while (( ent = readdir(d) )) {
449 int pid, ppid;
450 char buf[100];
451 char *safe_cmd = NULL;
452 char *tmp, cmd[CMD_LEN + USERNS_MARK_LEN], state;
453 int fd, len;
454 struct passwd *p;
455
456 // Skip non-process dir entries
457 if(*ent->d_name<'0' || *ent->d_name>'9')
458 continue;
459 errno = 0;
460 pid = strtol(ent->d_name, NULL, 10);
461 if (errno)
462 continue;
463
464 if (target_pid && (pid != target_pid))
465 continue;
466
467 /* Skip our pid so we aren't listed */
468 if (pid == our_pid)
469 continue;
470
471 // Parse up the stat file for the proc
472 snprintf(buf, sizeof(buf), "/proc/%d/stat", pid);
473 fd = open(buf, O_RDONLY|O_CLOEXEC, 0);
474 if (fd < 0)
475 continue;
476 len = read(fd, buf, sizeof(buf) - 1);
477 close(fd);
478 if (len < 40)
479 continue;
480 buf[len] = 0;
481 tmp = strrchr(buf, ')');
482 if (tmp)
483 *tmp = 0;
484 else
485 continue;
486 memset(cmd, 0, sizeof(cmd));
487 sscanf(buf, "%d (%15c", &ppid, cmd); // ppid is throwaway
488 sscanf(tmp+2, "%c %d", &state, &ppid);
489
490 // Skip kthreads
491 if (pid == 2 || ppid == 2)
492 continue;
493
494 // now get the capabilities
495 capng_clear(CAPNG_SELECT_ALL);
496 capng_setpid(pid);
497 if (capng_get_caps_process())
498 continue;
499
500 // And print out anything with capabilities
501 caps = capng_have_capabilities(CAPNG_SELECT_CAPS);
502 safe_cmd = sanitize_untrusted_field(cmd);
503 if (!safe_cmd)
504 continue;
505 if (in_child_userns(pid)) {
506 char *marked = malloc(strlen(safe_cmd) + 3);
507
508 if (!marked) {
509 free(safe_cmd);
510 continue;
511 }
512 snprintf(marked, strlen(safe_cmd) + 3, "%s *", safe_cmd);
513 free(safe_cmd);
514 safe_cmd = marked;
515 }
516 if (tree_mode) {
517 char *caps_text;
518 bool has_ambient;
519 bool has_bounds;
520
521 if (!show_all && caps <= CAPNG_NONE) {
522 free(safe_cmd);
523 continue;
524 }
525
526 has_ambient = capng_have_capabilities(
527 CAPNG_SELECT_AMBIENT) > CAPNG_NONE;
528 has_bounds = capng_have_capabilities(
529 CAPNG_SELECT_BOUNDS) > CAPNG_NONE;
530
531 caps_text = format_caps(caps, has_ambient, has_bounds);
532 if (!caps_text) {
533 free(safe_cmd);
534 continue;
535 }
536
537 if (proc_count == proc_capacity) {
538 size_t new_capacity = proc_capacity ?
539 proc_capacity * 2 : 256;
540 struct proc_info *pi_tmp;
541
542 pi_tmp = realloc(procs, new_capacity *
543 sizeof(*procs));
544 if (!pi_tmp) {
545 free(caps_text);
546 free(safe_cmd);
547 continue;
548 }
549 procs = pi_tmp;
550 proc_capacity = new_capacity;
551 }
552
553 procs[proc_count].pid = pid;
554 procs[proc_count].ppid = ppid;
555 procs[proc_count].cmd = safe_cmd;
556 get_account_name(pid, procs[proc_count].account,
557 sizeof(procs[proc_count].account));
558 procs[proc_count].caps_text = caps_text;
559 proc_count++;
560 safe_cmd = NULL;
561 } else if (caps > CAPNG_NONE) {
562 int euid = get_euid(pid);
563
564 if (header == 0) {
565 printf("%-7s %-7s %-16s %-15s %s\n",
566 "ppid", "pid", "uid", "command",
567 "capabilities");
568 header = 1;
569 }
570 if (euid == 0) {
571 // Take short cut for this one
572 name = "root";
573 uid = 0;
574 } else if (euid != uid) {
575 // Only look up if name changed
576 p = getpwuid(euid);
577 uid = euid;
578 if (p)
579 name = p->pw_name;
580 else
581 name = NULL;
582 }
583
584 if (name) {
585 printf("%-7d %-7d %-16s %-15s ", ppid, pid,
586 name, safe_cmd);
587 } else
588 printf("%-7d %-7d %-16d %-15s ", ppid, pid,
589 uid, safe_cmd);
590 if (caps == CAPNG_PARTIAL) {
591 capng_print_caps_text(CAPNG_PRINT_STDOUT,
592 CAPNG_PERMITTED);
593 if (capng_have_capabilities(
594 CAPNG_SELECT_AMBIENT) > CAPNG_NONE)
595 printf(" @");
596 if (capng_have_capabilities(CAPNG_SELECT_BOUNDS)
597 > CAPNG_NONE)
598 printf(" +");
599 printf("\n");
600 } else {
601 printf("full");
602 if (capng_have_capabilities(
603 CAPNG_SELECT_AMBIENT) > CAPNG_NONE)
604 printf(" @");
605 if (capng_have_capabilities(CAPNG_SELECT_BOUNDS)
606 > CAPNG_NONE)
607 printf(" +");
608 printf("\n");
609 }
610 free(safe_cmd);
611 safe_cmd = NULL;
612 }
613 if (safe_cmd)
614 free(safe_cmd);
615 }
616 closedir(d);
617 if (tree_mode) {
618 print_tree(procs, proc_count);
619 for (i = 0; i < proc_count; i++) {
620 free(procs[i].cmd);
621 free(procs[i].caps_text);
622 }
623 free(procs);
624 }
625 return 0;
626 }