深入理解File descriptor(附pwnable-fd解题步骤)

0x01 前言

首先我们先普及一下什么是File descriptor?

维基百科中说:is an abstract indicator (handle) used to access a file or other input/output resource
一个文件或其他输入/输出资源的抽象指示符
深入理解File descriptor(附pwnable-fd解题步骤)

在操作系统中可以这样去理解:

深入理解File descriptor(附pwnable-fd解题步骤)
进程(数值+指针)->系统(文件表中一系列操作)->引节点表(描述文件系统对象)
那么进程中的file descriptor的这个数值其实就是 is an abstract indicator (handle) used to access a file or other input/output resource 然后他是指向相应的file table

0x02 走进File descriptor

我们来看

深入理解File descriptor(附pwnable-fd解题步骤)
四个file descriptor的值会以此增加,他们只想不同的操作
那么为什么从3开始?是不是巧合?012去哪呢?
在证明0、1、2的去向之前,我们先看一下file descriptor值的分配规则:
深入理解File descriptor(附pwnable-fd解题步骤)
fd0与fd1从3开始依次递增,我们刚才的第二个问题就不是巧合,然后我们把fd0的句柄close掉,也就说刚才的3关闭了,重新开始一个fd2,发现fd2的值为3,而不是5,也就是占用了刚才关闭的fd0的值

我们就不妨这么猜测,如下图

深入理解File descriptor(附pwnable-fd解题步骤)
假如继续fd3=open,那么fd3值为5,也就是在红色区域
那么我们可以初步得出一个结论,分配原则:寻找没有被占用的最低的值,然后去占用
那么我们证实我们的结论和探寻0、1、2在哪?
其实
深入理解File descriptor(附pwnable-fd解题步骤)

那么,我们关闭stdin标准输入来看下会发生什么?

深入理解File descriptor(附pwnable-fd解题步骤)
运行fd后直接输入数值,两次不一样,也就是标准输入被关闭,in自动填充一个随机值
继续关闭stdout
深入理解File descriptor(附pwnable-fd解题步骤)
输入hello后,没有执行printf输出函数,然后我们将stdout关闭调,新开一个fd,按照我们之前的推断那么fd值应该为1
深入理解File descriptor(附pwnable-fd解题步骤)

0x03 pwnable-fd

把结论进行验证,使得对file descriptor更深刻了,我们来做一下pwnable的fd题目巩固一下:

ssh连上后,cat fd.c
深入理解File descriptor(附pwnable-fd解题步骤)
深入理解File descriptor(附pwnable-fd解题步骤)
只需要让buf的值为 LETMEWIN 即可cat flag,buf的是read()函数从fd中获取的,fd又是atoi(argv[1]) - 0x1234得来的,可以控制。
那么根据我们刚才学习的file descriptor的知识,只需要让fd为0,那么buf的值就是可以通过输入控制的,计算可以知道argv[1]的值4660
深入理解File descriptor(附pwnable-fd解题步骤)
虽然flag得到了,为了学习pwn,练习写一下exp
深入理解File descriptor(附pwnable-fd解题步骤)
深入理解File descriptor(附pwnable-fd解题步骤)

0x04 尾记

想学习二进制的pwn弟弟还需要努力,希望我的小白学习经验记录下来可以帮助更多和我一样的小白。

另见:http://bey0nd.xyz/2020/02/07/1/