Post

(shell) pipe

  • pipe란?
    • 한 프로세스의 stdout을 다른 프로세스의 stdin으로 연결하는 IPC 방법이다.
파이프 한 개(r, w 한 쌍) 당 한 쪽 방향으로만 사용할 수 있다.
1
2
3
4
5
6
↓ docking!                   ↓
-------pipe-------   ---------process---------    -------pipe-------
w       ->       r ⇒ stdin              stdout ⇒ w       ->       r
-------pipe-------   ---------process---------    -------pipe-------

이름없는 파이프
1
2
3
echo .... | File
( ...; cat ) | File

A | File : A의 표준 출력을 File의 표준 입력으로 연결한다.

fifo ( named pipe )

fifo ( named pipe )는 anonymous communication channel인 그냥 pipe와 달리 pipe에 이름이 있고 파일 형태로 접근한다. 아래의 경우 실제로 디렉토리에 파이프 이름인 f라는 특수파일이 생성된다. f를 통해 target에 표준입력 할 수 있다.

1
2
3
4
$ rm -f /tmp/f; mkfifo /tmp/f
$ ./target < /tmp/f &
$ cat printfile > /tmp/f

&를 이용해 표준 입력 연결을 백그라운드로 돌려놓았다.

etc

Control operators:

1
2
& && ( ) ; ;; | || <newline>

Redirection operators:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
< > >| << >> <& >& <<- <>

#### [n] 생략하면 stdout이 대상이다.
[n]>> file  Append standard output (or n) to file.
[n]<> file  Open file for reading and writing on standard input (or n).


#### & means whatever follows is a file descriptor, not a filename.
[n1]>&fd    Redirect standard output (or n1) to fd.
[n1]>n2     Redirect standard output (or n1) to n2.




> /dev/null 2>&1   stdout(1)을 /dev/null로 보내고, stderr(2)를 stdout(1)로 보내라 (즉 둘 다 null로 간다)

stdin과 pipe

입력을 stdin으로 받는 경우 주로 pipe를 이용해 입력하게 되는데, 대상 프로그램에서 쉘을 실행하는 경우 쉘이 실행되자 마자 EOF(Ctrl+D)가 쉘에 전달되어 쉘이 바로 종료된다. ( )로 묶고 마지막에 ; cat을 붙여주면 쉘이 종료되지 않는다.

1
2
(python -c 'print "shellcode"' ; cat ) | ./target

cat을 인자 없이 사용해 보면 계속 입력 대기하고 있다가 이를 출력하는 동작을 한다. 그래서 쉘이 실행되고 나서도 파이프로 cat과 연결되어 있으면 쉘이 종료되지 않는다.

This post is licensed under CC BY 4.0 by the author.