GithubHelp home page GithubHelp logo

kxxt / tracexec Goto Github PK

View Code? Open in Web Editor NEW
192.0 2.0 3.0 25.78 MB

Tracer for execve{,at} and pre-exec behavior, launcher for debuggers.

License: GNU General Public License v2.0

Rust 99.39% Handlebars 0.53% Makefile 0.06% Shell 0.02%
command-line-tool execve ptrace strace tracer tracexec debugger

tracexec's Introduction

tracexec

A small utility for tracing execve{,at} and pre-exec behavior.

tracexec helps you to figure out what and how programs get executed when you execute a command.

It's useful for debugging build systems, understanding what shell scripts actually do, figuring out what programs does a proprietary software run, etc.

Showcases

TUI mode with pseudo terminal

In TUI mode with a pseudo terminal, you can view the details of exec events and interact with the processes within the pseudo terminal at ease.

TUI demo

Tracing setuid binaries

With root privileges, you can also trace setuid binaries and see how they work. But do note that this is not compatible with seccomp-bpf optimization so it is much less performant.

sudo tracexec --user $(whoami) tui -t -- sudo ls

Tracing sudo ls

Nested setuid binary tracing is also possible: A real world use case is to trace extra-x86_64-build(Arch Linux's build tool that requires sudo):

Tracing extra-x86_64-build

In this real world example, we can easily see that _FORTIFY_SOURCE is redefined from 2 to 3, which lead to a compiler error.

Use tracexec as a debugger launcher

tracexec can also be used as a debugger launcher to make debugging programs easier. For example, it's not trivial or convenient to debug a program executed by a shell/python script(which can use pipes as stdio for the program). The following video shows how to use tracexec to launch gdb to detach two simple programs piped together by a shell script.

gdb-launcher.mp4

Please read the gdb-launcher example for more details.

Log mode

In log mode, by default, tracexec will print filename, argv and the diff of the environment variables and file descriptors.

example: tracexec log -- bash (In an interactive bash shell)

asciicast

Reconstruct the command line with --show-cmdline

$ tracexec log --show-cmdline -- <command>
# example:
$ tracexec log --show-cmdline -- firefox

asciicast

Try to reproduce stdio in the reconstructed command line

--stdio-in-cmdline and --fd-in-cmdline can be used to reproduce(hopefully) the stdio used by a process.

But do note that the result might be inaccurate when pipes, sockets, etc are involved.

tracexec log --show-cmdline --stdio-in-cmdline -- bash

asciicast

Show the interpreter indicated by shebang with --show-interpreter

And show the cwd with --show-cwd.

$ tracexec log --show-interpreter --show-cwd -- <command>
# example: Running Arch Linux makepkg
$ tracexec log --show-interpreter --show-cwd -- makepkg -f

asciicast

Installation

From source

Via cargo:

cargo install tracexec --bin tracexec

Arch Linux users can also install from the official repositories via pacman -S tracexec.

Binary

You can download the binary from the release page

Usage

General CLI help:

A small utility for tracing execve{,at} and pre-exec behavior

Usage: tracexec [OPTIONS] <COMMAND>

Commands:
  log   Run tracexec in logging mode
  tui   Run tracexec in TUI mode, stdin/out/err are redirected to /dev/null by default
  help  Print this message or the help of the given subcommand(s)

Options:
      --color <COLOR>  Control whether colored output is enabled. This flag has no effect on TUI mode. [default: auto] [possible values: auto, always, never]
  -C, --cwd <CWD>      Change current directory to this path before doing anything
  -u, --user <USER>    Run as user. This option is only available when running tracexec as root
  -h, --help           Print help
  -V, --version        Print version

TUI Mode:

Run tracexec in TUI mode, stdin/out/err are redirected to /dev/null by default

Usage: tracexec tui [OPTIONS] -- <CMD>...

Arguments:
  <CMD>...  command to be executed

Options:
      --seccomp-bpf <SECCOMP_BPF>
          Controls whether to enable seccomp-bpf optimization, which greatly improves performance [default: auto] [possible values: auto, on, off]
      --successful-only
          Only show successful calls
      --fd-in-cmdline
          [Experimental] Try to reproduce file descriptors in commandline. This might result in an unexecutable cmdline if pipes, sockets, etc. are involved.
      --stdio-in-cmdline
          [Experimental] Try to reproduce stdio in commandline. This might result in an unexecutable cmdline if pipes, sockets, etc. are involved.
      --resolve-proc-self-exe
          Resolve /proc/self/exe symlink
      --no-resolve-proc-self-exe
          Do not resolve /proc/self/exe symlink
      --tracer-delay <TRACER_DELAY>
          Delay between polling, in microseconds. The default is 500 when seccomp-bpf is enabled, otherwise 1.
      --show-all-events
          Set the default filter to show all events. This option can be used in combination with --filter-exclude to exclude some unwanted events.
      --filter <FILTER>
          Set the default filter for events. [default: warning,error,exec,tracee-exit]
      --filter-include <FILTER_INCLUDE>
          Aside from the default filter, also include the events specified here. [default: <empty>]
      --filter-exclude <FILTER_EXCLUDE>
          Exclude the events specified here from the default filter. [default: <empty>]
  -t, --tty
          Allocate a pseudo terminal and show it alongside the TUI
  -f, --follow
          Keep the event list scrolled to the bottom
      --terminate-on-exit
          Instead of waiting for the root child to exit, terminate when the TUI exits
      --kill-on-exit
          Instead of waiting for the root child to exit, kill when the TUI exits
  -A, --active-pane <ACTIVE_PANE>
          Set the default active pane to use when TUI launches [default: terminal] [possible values: terminal, events]
  -L, --layout <LAYOUT>
          Set the layout of the TUI when it launches [default: horizontal] [possible values: horizontal, vertical]
  -F, --frame-rate <FRAME_RATE>
          Set the frame rate of the TUI [default: 60.0]
  -D, --default-external-command <DEFAULT_EXTERNAL_COMMAND>
          Set the default external command to run when using "Detach, Stop and Run Command" feature in Hit Manager
  -b, --add-breakpoint <BREAKPOINTS>
          Add a new breakpoint to the tracer. This option can be used multiple times. The format is <syscall-stop>:<pattern-type>:<pattern>, where syscall-stop can be sysenter or sysexit, pattern-type can be argv-regex, in-filename or exact-filename. For example, sysexit:in-filename:/bash
  -h, --help
          Print help

Log Mode:

Run tracexec in logging mode

Usage: tracexec log [OPTIONS] -- <CMD>...

Arguments:
  <CMD>...  command to be executed

Options:
      --show-cmdline
          Print commandline that (hopefully) reproduces what was executed. Note: file descriptors are not handled for now.
      --show-interpreter
          Try to show script interpreter indicated by shebang
      --more-colors
          More colors
      --less-colors
          Less colors
      --foreground
          Set the terminal foreground process group to tracee. This option is useful when tracexec is used interactively.
      --no-foreground
          Do not set the terminal foreground process group to tracee
      --diff-fd
          Diff file descriptors with the original std{in/out/err}
      --no-diff-fd
          Do not diff file descriptors
      --show-fd
          Show file descriptors
      --no-show-fd
          Do not show file descriptors
      --diff-env
          Diff environment variables with the original environment
      --no-diff-env
          Do not diff environment variables
      --show-env
          Show environment variables
      --no-show-env
          Do not show environment variables
      --show-comm
          Show comm
      --no-show-comm
          Do not show comm
      --show-argv
          Show argv
      --no-show-argv
          Do not show argv
      --show-filename
          Show filename
      --no-show-filename
          Do not show filename
      --show-cwd
          Show cwd
      --no-show-cwd
          Do not show cwd
      --decode-errno
          Decode errno values
      --no-decode-errno
          Do not decode errno values
      --seccomp-bpf <SECCOMP_BPF>
          Controls whether to enable seccomp-bpf optimization, which greatly improves performance [default: auto] [possible values: auto, on, off]
      --successful-only
          Only show successful calls
      --fd-in-cmdline
          [Experimental] Try to reproduce file descriptors in commandline. This might result in an unexecutable cmdline if pipes, sockets, etc. are involved.
      --stdio-in-cmdline
          [Experimental] Try to reproduce stdio in commandline. This might result in an unexecutable cmdline if pipes, sockets, etc. are involved.
      --resolve-proc-self-exe
          Resolve /proc/self/exe symlink
      --no-resolve-proc-self-exe
          Do not resolve /proc/self/exe symlink
      --tracer-delay <TRACER_DELAY>
          Delay between polling, in microseconds. The default is 500 when seccomp-bpf is enabled, otherwise 1.
      --show-all-events
          Set the default filter to show all events. This option can be used in combination with --filter-exclude to exclude some unwanted events.
      --filter <FILTER>
          Set the default filter for events. [default: warning,error,exec,tracee-exit]
      --filter-include <FILTER_INCLUDE>
          Aside from the default filter, also include the events specified here. [default: <empty>]
      --filter-exclude <FILTER_EXCLUDE>
          Exclude the events specified here from the default filter. [default: <empty>]
  -o, --output <OUTPUT>
          Output, stderr by default. A single hyphen '-' represents stdout.
  -h, --help
          Print help

The recommended way to use tracexec is to create an alias with your favorite options in your bashrc:

alias tracex='tracexec log --show-cmdline --show-interpreter --show-children --show-filename --'
alias txtui='tracexec tui -t --'
# Now you can use
tracex <command>
txtui <command>

Known issues

  • Non UTF-8 strings are converted to UTF-8 in a lossy way, which means that the output may be inaccurate.
  • The output is not stable yet, which means that the output may change in the future.
  • Test coverage is not good enough.
  • The pseudo terminal can't pass through certain key combinations and terminal features.

Origin

This project was born out of the need to trace the execution of programs.

Initially I simply use strace -Y -f -qqq -s99999 -e trace=execve,execveat <command>.

But the output is still too verbose so that's why I created this project.

Credits

This project takes inspiration from strace and lurk.

tracexec's People

Contributors

kxxt avatar mend-bolt-for-github[bot] avatar orhun avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

tracexec's Issues

[Feature Request] MacOS support

Nice tool, but I am getting the following error on my Mac M1, how to fix it ?

➜  ~ cargo install tracexec --bin tracexec
    Updating crates.io index
  Downloaded tracexec v0.0.5
  Downloaded 1 crate (417.5 KB) in 0.06s
  Installing tracexec v0.0.5
    Updating crates.io index
  Downloaded backtrace v0.3.71
  Downloaded rustc-demangle v0.1.24
  Downloaded tracing-error v0.2.0
  Downloaded supports-color v2.1.0
  Downloaded serde v1.0.201
  Downloaded syn v2.0.61
  Downloaded object v0.32.2
  Downloaded gimli v0.28.1
  Downloaded color-eyre v0.6.3
  Downloaded seccompiler v0.4.0
  Downloaded cc v1.0.97
  Downloaded strum_macros v0.26.2
  Downloaded rustversion v1.0.16
  Downloaded owo-colors v3.5.0
  Downloaded num-traits v0.2.19
  Downloaded kxxt-owo-colors v4.0.0
  Downloaded autocfg v1.3.0
  Downloaded anstyle v1.0.7
  Downloaded addr2line v0.21.0
  Downloaded strum v0.26.2
  Downloaded shell-quote v0.5.0
  Downloaded proc-macro2 v1.0.82
  Downloaded pretty_env_logger v0.5.0
  Downloaded libc v0.2.154
  Downloaded is_ci v1.2.0
  Downloaded colorchoice v1.0.1
  Downloaded atoi v2.0.0
  Downloaded is_terminal_polyfill v1.70.0
  Downloaded color-spantrace v0.2.1
  Downloaded anstyle-query v1.0.3
  Downloaded anstyle-parse v0.2.4
  Downloaded anstream v0.6.14
  Downloaded 32 crates (3.2 MB) in 0.30s
   Compiling libc v0.2.154
   Compiling memchr v2.7.2
   Compiling once_cell v1.19.0
   Compiling cfg-if v1.0.0
   Compiling proc-macro2 v1.0.82
   Compiling unicode-ident v1.0.12
   Compiling regex-syntax v0.8.3
   Compiling lazy_static v1.4.0
   Compiling pin-project-lite v0.2.14
   Compiling sharded-slab v0.1.7
   Compiling utf8parse v0.2.1
   Compiling autocfg v1.3.0
   Compiling tracing-core v0.1.32
   Compiling thread_local v1.1.8
   Compiling aho-corasick v1.1.3
   Compiling cc v1.0.97
   Compiling rustversion v1.0.16
   Compiling tracing-subscriber v0.3.18
   Compiling tracing v0.1.40
   Compiling regex-automata v0.4.6
   Compiling backtrace v0.3.71
   Compiling num-traits v0.2.19
   Compiling anstyle-parse v0.2.4
   Compiling anstyle v1.0.7
   Compiling gimli v0.28.1
   Compiling anstyle-query v1.0.3
   Compiling is_terminal_polyfill v1.70.0
   Compiling eyre v0.6.12
   Compiling colorchoice v1.0.1
   Compiling quote v1.0.36
   Compiling syn v2.0.61
   Compiling is-terminal v0.4.12
   Compiling adler v1.0.2
   Compiling anstream v0.6.14
   Compiling miniz_oxide v0.7.2
   Compiling regex v1.10.4
   Compiling tracing-error v0.2.0
   Compiling object v0.32.2
   Compiling owo-colors v3.5.0
   Compiling addr2line v0.21.0
   Compiling heck v0.5.0
   Compiling log v0.4.21
   Compiling clap_lex v0.7.0
   Compiling termcolor v1.4.1
   Compiling is_ci v1.2.0
   Compiling humantime v2.1.0
   Compiling rustc-demangle v0.1.24
   Compiling strsim v0.11.1
   Compiling heck v0.4.1
   Compiling indenter v0.3.3
   Compiling clap_builder v4.5.2
   Compiling env_logger v0.10.2
   Compiling supports-color v2.1.0
   Compiling color-spantrace v0.2.1
   Compiling bstr v1.9.1
   Compiling bitflags v2.5.0
   Compiling atoi v2.0.0
   Compiling nix v0.27.1
   Compiling shell-quote v0.5.0
   Compiling kxxt-owo-colors v4.0.0
   Compiling strum_macros v0.26.2
   Compiling clap_derive v4.5.4
   Compiling color-eyre v0.6.3
   Compiling pretty_env_logger v0.5.0
   Compiling seccompiler v0.4.0
error[E0425]: cannot find value `SECCOMP_FILTER_FLAG_TSYNC` in crate `libc`
   --> /Users/andrewssobral/.cargo/registry/src/index.crates.io-6f17d22bba15001f/seccompiler-0.4.0/src/lib.rs:328:47
    |
328 |     apply_filter_with_flags(bpf_filter, libc::SECCOMP_FILTER_FLAG_TSYNC)
    |                                               ^^^^^^^^^^^^^^^^^^^^^^^^^ not found in `libc`

error[E0425]: cannot find function `prctl` in crate `libc`
   --> /Users/andrewssobral/.cargo/registry/src/index.crates.io-6f17d22bba15001f/seccompiler-0.4.0/src/lib.rs:347:29
    |
347 |     let rc = unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) };
    |                             ^^^^^ not found in `libc`

error[E0425]: cannot find value `PR_SET_NO_NEW_PRIVS` in crate `libc`
   --> /Users/andrewssobral/.cargo/registry/src/index.crates.io-6f17d22bba15001f/seccompiler-0.4.0/src/lib.rs:347:41
    |
347 |     let rc = unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) };
    |                                         ^^^^^^^^^^^^^^^^^^^ not found in `libc`

error[E0425]: cannot find value `SYS_seccomp` in crate `libc`
   --> /Users/andrewssobral/.cargo/registry/src/index.crates.io-6f17d22bba15001f/seccompiler-0.4.0/src/lib.rs:363:19
    |
363 |             libc::SYS_seccomp,
    |                   ^^^^^^^^^^^ not found in `libc`

error[E0308]: mismatched types
   --> /Users/andrewssobral/.cargo/registry/src/index.crates.io-6f17d22bba15001f/seccompiler-0.4.0/src/lib.rs:376:38
    |
376 |         return Err(Error::ThreadSync(rc));
    |                    ----------------- ^^ expected `i64`, found `i32`
    |                    |
    |                    arguments to this enum variant are incorrect
    |
note: tuple variant defined here
   --> /Users/andrewssobral/.cargo/registry/src/index.crates.io-6f17d22bba15001f/seccompiler-0.4.0/src/lib.rs:242:5
    |
242 |     ThreadSync(libc::c_long),
    |     ^^^^^^^^^^
help: you can convert an `i32` to an `i64`
    |
376 |         return Err(Error::ThreadSync(rc.into()));
    |                                        +++++++

Some errors have detailed explanations: E0308, E0425.
For more information about an error, try `rustc --explain E0308`.
error: could not compile `seccompiler` (lib) due to 5 previous errors
warning: build failed, waiting for other jobs to finish...
error: failed to compile `tracexec v0.0.5`, intermediate artifacts can be found at `/var/folders/4y/0hm48z794zd2d15cwsg10kcm0000gn/T/cargo-install2rFoLE`.
To reuse those artifacts with a future compilation, set the environment variable `CARGO_TARGET_DIR` to that path.
➜  ~

Track process start/duration/stop times

This fits pretty well into the build system analysis scenario - let's say you want to build the Linux kernel, you have a big process tree and need to find what takes the most time (to optimize/disable these areas). It would be nice to track how long each process takes.

[Feature] Profile

Allow users to load settings from ~/.config/tracexec/config.toml.

[Feature] Setting custom baseline env

For the following use case:

Something works on machine A but doesn't work on machine B.

A user might want to capture the baseline environment fro machine A and run tracexec on machine B with the baseline env from machine A.

[Feature] Option to display relative path instead of full path

Displaying full path takes significant large spaces in the TUI. Sometimes relative paths are easier to reason about and more concise.

But this would generate incorrect information if chroots are involved. So putting a warning somewhere is desired.

[Feature] allow external debugger to attach

Use case:

I have an app my-app and another app B. There's a bug that occurs only when B executes my-app. I want to directly debug my-app when executing B.

And BTW it's very painful to debug multi-process applications in gdb.

How:

  • Add breakpoints on exec(e.g. break when exec my-app)
  • Ask if launching external debugger on breakpoint hit
  • Detach from the tracee to be debugged and launch external debugger(e.g. gdb in a new window) and let it attach to tracee.

Unresolved questions:

  • Is this compatible with seccomp-bpf optimization?
  • How could we transfer ptrace from tracexec to external debugger?
  • Should the breakpoint be triggered on syscall enter stop or syscall exit stop?

Caveats:

  • Further exec events will not be available for the detached tracee.

Alternative

Maybe I could implement gdb server protocol in tracexec and let gdb as a client connect to it. This way further exec events can also be traced.

[Feature] Option to use external terminal emulator

Currently the pseudo term inside tracexec isn't feature complete. But it's already very helpful for using it on remote servers where X11/Wayland isn't available.

But if X11/Wayland is available, It would be nice to launch a separate terminal emulator that is feature complete. This means that the current monolith architecture need to be refactored into a client/server model because we need to spawn a worker process inside the new terminal emulator.

IPC can be hard so I am labeling this feature as low-priority

[Performance] Optimize memory usage

For now there's lots of clones involved in the code. We could use something like https://github.com/thomcc/arcstr to optimize the memory footprint.

The tui can already handle 100000 events with a very low idle cpu usage without hassle thanks to the complex multi-layer cache system I implemented. But the memory usage doesn't look nice to me (total ram 16GB).

image

[Feature] Custom theme for TUI

Currently TUI is already theme-able at compile time. It would be nice to theme it at runtime by loading configuration files(TOML should be fine). And I want to make several themes.

Note that themes can also be installed system-wide.

[Feature] Edit baseline environment in TUI

Sometimes the built-in terminal is not enough, and people might want to run tracexec tui -- konsole.

But konsole and the new shell session brings many changes into the environment, thus making the env diff more noisy.

It would be great to let people to change the baseline environment at runtime to make the environment diff more readable.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.