extrace.c 9.76 KB
Newer Older
1 2 3 4 5
/* extrace - trace exec() calls system-wide
 *
 * Requires CONFIG_CONNECTOR=y and CONFIG_PROC_EVENTS=y.
 * Requires root or "setcap cap_net_admin+ep extrace".
 *
6
 * Usage: extrace [-deflq] [-o FILE] [-p PID|CMD...]
7 8 9
 * default: show all exec(), globally
 * -p PID   only show exec() descendant of PID
 * CMD...   run CMD... and only show exec() descendant of it
10
 * -o FILE  log to FILE instead of standard output
11 12
 * -d       print cwd of process
 * -e       print environment of process
13
 * -f       flat output: no indentation
Christian Neukirchen's avatar
Christian Neukirchen committed
14 15
 * -l       print full path of argv[0]
 * -q       don't print exec() arguments
16
 *
Leah Neukirchen's avatar
Leah Neukirchen committed
17
 * Copyright (C) 2014-2016 Leah Neukirchen <leah@vuxu.org>
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
 *
 * hacked from sources of:
 */
/* exec-notify, so you can watch your acrobat reader or vim executing "bash -c"
 * commands ;-)
 * Requires some 2.6.x Linux kernel with proc connector enabled.
 *
 * $  cc -Wall -ansi -pedantic -std=c99 exec-notify.c
 *
 * (C) 2007-2010 Sebastian Krahmer <krahmer@suse.de> original netlink handling
 * stolen from an proc-connector example, copyright folows:
 */
/* Copyright (C) Matt Helsley, IBM Corp. 2005
 * Derived from fcctl.c by Guillaume Thouvenin
 * Original copyright notice follows:
 *
 * Copyright (C) 2005 BULL SA.
 * Written by Guillaume Thouvenin <guillaume.thouvenin@bull.net>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

#define _XOPEN_SOURCE 700

#include <fcntl.h>
#include <limits.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <sys/socket.h>
#include <sys/types.h>
64
#include <sys/wait.h>
65 66 67 68 69 70 71 72 73

#include <linux/connector.h>
#include <linux/netlink.h>
#include <linux/cn_proc.h>

#define max(x,y) ((y)<(x)?(x):(y))
#define min(x,y) ((y)>(x)?(x):(y))

#define SEND_MESSAGE_LEN (NLMSG_LENGTH(sizeof (struct cn_msg) + \
Christian Neukirchen's avatar
Christian Neukirchen committed
74
                                       sizeof (enum proc_cn_mcast_op)))
75
#define RECV_MESSAGE_LEN (NLMSG_LENGTH(sizeof (struct cn_msg) + \
Christian Neukirchen's avatar
Christian Neukirchen committed
76
                                       sizeof (struct proc_event)))
77 78 79 80 81 82 83

#define SEND_MESSAGE_SIZE    (NLMSG_SPACE(SEND_MESSAGE_LEN))
#define RECV_MESSAGE_SIZE    (NLMSG_SPACE(RECV_MESSAGE_LEN))

#define BUFF_SIZE (max(max(SEND_MESSAGE_SIZE, RECV_MESSAGE_SIZE), 1024))
#define MIN_RECV_SIZE (min(SEND_MESSAGE_SIZE, RECV_MESSAGE_SIZE))

84
#define CMDLINE_MAX 32768
85 86
pid_t parent = 1;
int flat = 0;
87
int run = 0;
Christian Neukirchen's avatar
Christian Neukirchen committed
88 89
int full_path = 0;
int show_args = 1;
90
int show_cwd = 0;
91
int show_env = 0;
92 93
FILE *output;
sig_atomic_t quit = 0;
94

95
static int
96 97 98 99 100 101
pid_depth(pid_t pid)
{
  pid_t ppid = 0;
  FILE *f;
  char name[PATH_MAX];
  int d;
102

103 104 105
  snprintf(name, sizeof name, "/proc/%d/stat", pid);

  if ((f = fopen(name, "r"))) {
106 107
    if (fscanf(f, "%*d (%*[^)]) %*c %d", &ppid) < 0)
      ppid = 0;
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
    fclose(f);
  }

  if (ppid == parent)
    return 0;

  if (ppid == 0)
    return -1;  /* a parent we are not interested in */

  d = pid_depth(ppid);
  if (d == -1)
    return -1;

  return d+1;
}

124 125 126
static void
sigint(int sig)
{
Christian Neukirchen's avatar
Christian Neukirchen committed
127
  (void)sig;
128 129 130 131 132 133
  quit = 1;
}

static void
sigchld(int sig)
{
Christian Neukirchen's avatar
Christian Neukirchen committed
134
  (void)sig;
135 136 137 138 139
  while (waitpid(-1, NULL, WNOHANG) > 0)
    ;
  quit = 1;
}

140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
static void
print_shquoted(const char *s)
{
  if (*s && !strpbrk(s,
                     "\001\002\003\004\005\006\007\010"
                     "\011\012\013\014\015\016\017\020"
                     "\021\022\023\024\025\026\027\030"
                     "\031\032\033\034\035\036\037\040"
                     "`^#*[]=|\\?${}()'\"<>&;\177")) {
    fprintf(output, "%s", s);
    return;
  }

  putc('\'', output);
  for (; *s; s++)
    if (*s == '\'')
      fprintf(output, "'\\''");
    else if (*s == '\n')
      fprintf(output, "'$'\\n''");
    else
      putc(*s, output);
  putc('\'', output);
}

164
static void
165 166 167
handle_msg(struct cn_msg *cn_hdr)
{
  char cmdline[CMDLINE_MAX], name[PATH_MAX];
Christian Neukirchen's avatar
Christian Neukirchen committed
168
  char exe[PATH_MAX];
169
  char cwd[PATH_MAX];
Christian Neukirchen's avatar
Christian Neukirchen committed
170
  char *argvrest;
171

Christian Neukirchen's avatar
Christian Neukirchen committed
172
  int r = 0, r2 = 0, r3 = 0, fd, d;
173
  struct proc_event *ev = (struct proc_event *)cn_hdr->data;
174
  pid_t pid = ev->event_data.exec.process_pid;
175 176

  if (ev->what == PROC_EVENT_EXEC) {
177
    d = pid_depth(pid);
178 179 180
    if (d < 0)
      return;

181
    snprintf(name, sizeof name, "/proc/%d/cmdline", pid);
182 183 184 185 186 187 188

    memset(&cmdline, 0, sizeof cmdline);
    fd = open(name, O_RDONLY);
    if (fd > 0) {
      r = read(fd, cmdline, sizeof cmdline);
      close(fd);

189 190 191
      if (r > 0)
        cmdline[r] = 0;

Christian Neukirchen's avatar
Christian Neukirchen committed
192
      if (full_path) {
193
        snprintf(name, sizeof name, "/proc/%d/exe", pid);
Christian Neukirchen's avatar
Christian Neukirchen committed
194 195 196 197 198
        r2 = readlink(name, exe, sizeof exe);
        if (r2 > 0)
          exe[r2] = 0;
      }

199
      argvrest = strchr(cmdline, 0) + 1;
200
    }
201

202
    if (show_cwd) {
203
      snprintf(name, sizeof name, "/proc/%d/cwd", pid);
204 205 206 207 208
      r3 = readlink(name, cwd, sizeof cwd);
      if (r3 > 0)
        cwd[r3] = 0;
    }

209 210
    if (!flat)
      fprintf(output, "%*s", 2*d, "");
211
    fprintf(output, "%d ", pid);
Christian Neukirchen's avatar
Christian Neukirchen committed
212 213 214 215
    if (show_cwd) {
      print_shquoted(cwd);
      fprintf(output, " %% ");
    }
216 217 218

    if (full_path)
      print_shquoted(exe);
Christian Neukirchen's avatar
Christian Neukirchen committed
219
    else
220 221 222 223 224 225 226 227 228 229 230 231 232
      print_shquoted(cmdline);

    if (show_args && r > 0) {
      while (argvrest - cmdline < r) {
        putc(' ', output);
        print_shquoted(argvrest);
        argvrest = strchr(argvrest, 0)+1;
      }
    }

    if (r == sizeof cmdline)
      fprintf(output, "... <truncated>");

233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
    if (show_env) {
      FILE *env;
      fprintf(output, "  ");
      snprintf(name, sizeof name, "/proc/%d/environ", pid);
      if ((env = fopen(name, "r"))) {
        char *line = 0, *eq = 0;
        size_t linelen = 0;
        while (getdelim(&line, &linelen, '\0', env) >= 0) {
          putc(' ', output);
          if ((eq = strchr(line, '='))) {
            /* print split so = doesn't trigger escaping.  */
            *eq = 0;
            print_shquoted(line);
            putc('=', output);
            print_shquoted(eq+1);
          } else {
            /* weird env entry without equal sign.  */
            print_shquoted(line);
          }
        }
        free(line);
        fclose(env);
      } else {
        fprintf(output, " -");
      }
    }

Christian Neukirchen's avatar
Christian Neukirchen committed
260
    fprintf(output, "\n");
261
    fflush(output);
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
  }
}

int
main(int argc, char *argv[])
{
  int sk_nl;
  struct sockaddr_nl my_nla, kern_nla, from_nla;
  socklen_t from_nla_len;
  char buff[BUFF_SIZE];
  struct nlmsghdr *nl_hdr, *nlh;
  struct cn_msg *cn_hdr;
  enum proc_cn_mcast_op *mcop_msg;
  size_t recv_len = 0;
  int rc = -1, opt;

278 279
  output = stdout;

280
  while ((opt = getopt(argc, argv, "+deflo:p:qw")) != -1)
281
    switch (opt) {
282
    case 'd': show_cwd = 1; break;
283
    case 'e': show_env = 1; break;
284
    case 'f': flat = 1; break;
Christian Neukirchen's avatar
Christian Neukirchen committed
285
    case 'l': full_path = 1; break;
286
    case 'p': parent = atoi(optarg); break;
Christian Neukirchen's avatar
Christian Neukirchen committed
287
    case 'q': show_args = 0; break;
288 289 290 291 292 293
    case 'o':
      output = fopen(optarg, "w");
      if (!output) {
        perror("fopen");
        exit(1);
      }
294 295
      break;
    case 'w': /* obsoleted, ignore */; break;
296 297
    default: goto usage;
    }
298 299

  if (parent != 1 && optind != argc) {
300
usage:
301
    fprintf(stderr, "Usage: extrace [-deflq] [-o FILE] [-p PID|CMD...]\n");
302
    exit(1);
303
  }
304 305 306

  sk_nl = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_CONNECTOR);
  if (sk_nl == -1) {
307
    perror("socket sk_nl error");
308 309 310 311 312 313
    exit(1);
  }

  my_nla.nl_family = AF_NETLINK;
  my_nla.nl_groups = CN_IDX_PROC;
  my_nla.nl_pid = getpid();
314

315 316 317
  kern_nla.nl_family = AF_NETLINK;
  kern_nla.nl_groups = CN_IDX_PROC;
  kern_nla.nl_pid = 1;
318

319 320 321 322 323 324 325
  if (bind(sk_nl, (struct sockaddr *)&my_nla, sizeof my_nla) == -1) {
    perror("binding sk_nl error");
    goto close_and_exit;
  }
  nl_hdr = (struct nlmsghdr *)buff;
  cn_hdr = (struct cn_msg *)NLMSG_DATA(nl_hdr);
  mcop_msg = (enum proc_cn_mcast_op*)&cn_hdr->data[0];
326

327 328
  memset(buff, 0, sizeof buff);
  *mcop_msg = PROC_CN_MCAST_LISTEN;
329

330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
  nl_hdr->nlmsg_len = SEND_MESSAGE_LEN;
  nl_hdr->nlmsg_type = NLMSG_DONE;
  nl_hdr->nlmsg_flags = 0;
  nl_hdr->nlmsg_seq = 0;
  nl_hdr->nlmsg_pid = getpid();

  cn_hdr->id.idx = CN_IDX_PROC;
  cn_hdr->id.val = CN_VAL_PROC;
  cn_hdr->seq = 0;
  cn_hdr->ack = 0;
  cn_hdr->len = sizeof (enum proc_cn_mcast_op);

  if (send(sk_nl, nl_hdr, nl_hdr->nlmsg_len, 0) != nl_hdr->nlmsg_len) {
    printf("failed to send proc connector mcast ctl op!\n");
    goto close_and_exit;
  }
346

347 348 349 350
  if (*mcop_msg == PROC_CN_MCAST_IGNORE) {
    rc = 0;
    goto close_and_exit;
  }
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373

  if (optind != argc) {
    pid_t child;

    parent = getpid();
    signal(SIGCHLD, sigchld);

    child = fork();
    if (child == -1) {
      perror("fork");
      goto close_and_exit;
    }
    if (child == 0) {
      execvp(argv[optind], argv+optind);
      perror("execvp");
      goto close_and_exit;
    }
  }

  signal(SIGINT, sigint);

  rc = 0;
  while (!quit) {
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
    memset(buff, 0, sizeof buff);
    from_nla_len = sizeof from_nla;
    nlh = (struct nlmsghdr *)buff;
    memcpy(&from_nla, &kern_nla, sizeof from_nla);
    recv_len = recvfrom(sk_nl, buff, BUFF_SIZE, 0,
                        (struct sockaddr *)&from_nla, &from_nla_len);
    if (from_nla.nl_pid != 0 || recv_len < 1)
      continue;

    while (NLMSG_OK(nlh, recv_len)) {
      if (nlh->nlmsg_type == NLMSG_NOOP)
        continue;
      if (nlh->nlmsg_type == NLMSG_ERROR || nlh->nlmsg_type == NLMSG_OVERRUN)
        break;

      handle_msg(NLMSG_DATA(nlh));

      if (nlh->nlmsg_type == NLMSG_DONE)
        break;
      nlh = NLMSG_NEXT(nlh, recv_len);
    }
  }

close_and_exit:
  close(sk_nl);
  return rc;
}