Command groups

Sometimes you'll want to run multiple commands, and take action if any of them complete. For example, the MATCHSTREAM command matches streams and ports, but a payload may need to match multiple streams on multiple ports.

The wait command

Bash includes a built-in command, wait, which waits for a backgrounded command to complete.

By default, wait will pause until all backgrounded commands are complete, however by using wait -n, it will end when any backgrounded command completes.

The pkill command

The pkill command simplifies dealing with groups of processes.

While it has many options, we'll be using the -P option, which kills all subprocesses of a shell.

Coupled with the Bash variable $$ which expands to the process ID of the current shell, this lets us automatically kill all background processes of the current group:

pkill -P $$

Putting it together

Combing wait -n and pkill allows us to run any number of background commands, and immediately respond if any of them finish.

We then use pkill to kill the rest of the commands that are still running.



# Title: Command group demo
# Description: Jail the device instantly if it attempts to do HTTP basic auth or meterpreter

# Bridge mode

# Run the commands as a group
    # Run MATCHSTREAM and MATCHPORT in the background
    MATCHSTREAM eth0 TCP 80 'Basic-Auth:' &
    MATCHPORT eth0 ANY 4444 &
    # Wait for any command to complete
    wait -n
    # Kill any remaining commands
    pkill -P $$

# If we get to here, MATCHSTREAM or MATCHPORT has completed

# Go into jail mode

Last updated