最近在做hgame2020-pwn的一道题findyourself中,官方wp给出了一条linux命令是exec 1>&0,不解其意,直接查找也找不到这条命令到底是干什么的,拐弯抹角地先了解了文件描述符,然后才了解了这条命令。
- 程序的原意是输入一个字符串s1,经过字符检查后执行如下三条语句:
close(1);close(2);system(&s1);
- 我们的目的是要得到shell,官方wp给的是此处可以输入串:
$0
然后可以执行新的命令exec 1>&0
以及其他以查看到flag - 那么这条语句是什么意思呢?其中的0和1是指什么呢?
- 0和1是linux下的文件描述符。
- 在Linux中一切皆文件,文件描述符(file descriptor)是内核为了高效管理已被打开的文件所创建的索引,是一个非负整数(通常是小整数),用于指代被打开的文件,所有执行I/O操作的系统调用都通过文件描述符。程序刚刚启动的时候,0是标准输入,1是标准输出,2是标准错误。如果此时去打开一个新的文件,它的文件描述符会是3。
- 标准输入输出的指向是默认的,我们可以修改它们的指向,也即重定位
- 举例子,可以用
exec 1>myoutput
把标准输出重定向到myoutput文件中,也可以用exec 0<myinput
把标准输入重定向到myinput文件中,而且,文件名字可以用&+文件描述符来代替。 - 那么问题到这里就解决了,三条语句中
close(1);close(2)
即把标准输出和标准错误输出关闭,然后我们可以执行exec 1>&0
,也就是把标准输出重定向到标准输入,因为默认打开一个终端后,0,1,2都指向同一个位置也就是当前终端,所以这条语句相当于重启了标准输出,此时就可以执行命令并且看得到输出了
- 补充:
$0
是指第一个参数,argv[0]指向可执行文件的路径,也即表示sh,执行这条命令也就是打开了新的shell,这里也可以用s\h
- 这条命令其实属于
exec
操作文件描述符,本质上即exec+重定向命令,只不过操作的是文件描述符 -
Duplicating File Descriptors
The redirection operator [n]<&word is used to duplicate input file descriptors. If word expands to one or more digits, the file descriptor denoted by n is made to be a copy of that file descriptor. If the digits in word do not specify a file descriptor open for input, a redirection error occurs. If word evaluates to -, file descriptor n is closed. If n is not specified, the standard input (file descriptor 0) is used.
The operator [n]>&word is used similarly to duplicate output file descriptors. If n is not specified, the standard output (file descriptor 1) is used. If the digits in word do not specify a file descriptor open for output, a redirection error occurs. As a special case, if n is omitted, and word does not expand to one or more digits, the standard output and standard error are redirected as described previously. - 参考
来源:CSDN
作者:rambler_w
链接:https://blog.csdn.net/xirenwang/article/details/104139866