mkfifo (named pipes)

What is mkfifo?

If you're even a moderate Linux command line user, you must be aware of pipes, a fundamental command line feature that allows processes to communicate. Then there's a concept of named pipes (yeah, pipes with names, so that you can do more with pipes). The mkfifo command lets you create such named pipes.

How to use mkfifo

Example 1

In Linux, we can create a FIFO with the command mkfifo: (FIFO = first in first out)

$ mkfifo pipe1
$ ls -l
prw-r--r-- 1 cuau cuau 0 Oct 7 21:17 pipe1
# An named pipe can be recognized by the 'p' at the start of the privilege set

Here, we can see that our FIFO’s file type is indicated with the letter “p”.

This mechanism allows us to create more complex applications using our shell.

Named and anonymous pipes can be used together. Let’s create a reverse shell combining both FIFOs and pipes.

We’ll use the nc utility to create a client/server application, in which the “server” side will provide its shell, and the “client” side will be able to access it.

First, let’s install the netcat-openbsd package. We can install it on any Ubuntu/Debian system using:

$ sudo apt install netcat-openbsd

Next, let’s create a FIFO called fifo_reverse typing mkfifo fifo_reverse.

Then, let’s log in with two different users that will each act as a “client” (let’s say, “user1”) and as a “server” (let’s say, “user2”). Let’s run this pipeline on the user2 shell:

user2_prompt$ bash -i < fifo_reverse |& nc -l 127.0.0.1 1234 > fifo_reverse

"In this one-liner, the shell reads the content of our FIFO and passes it to an interactive Bash shell.

Next, both the stdout and the stderr of the interactive shell will be passed to the nc command, which will be listening at port 1234 of address 127.0.0.1.

And finally, when the “client” establishes a connection successfully, nc will write what is received to our FIFO, and the interactive shell will be able to execute what is received".

Now, using the user1 shell, let’s type:

user1_prompt$ nc 127.0.0.1 1234
user2_prompt$

Example 2

# terminal 1, creating the named pipe
MacBook-Pro-van-Michel:test michel$ mkfifo testPipe
MacBook-Pro-van-Michel:test michel$ echo "Hamburgers met korting" > testPipe # after this, the terminal will hang

# terminal 2
MacBook-Pro-van-Michel:test michel$ cat < testPipe 
Hamburgers met korting
MacBook-Pro-van-Michel:test michel$ 

References

Last updated