xref: /cloud-hypervisor/fuzz/fuzz_targets/block.rs (revision 2571e59438597f53aa4993cd70d6462fe1364ba7)
1 // Copyright 2018 The Chromium OS Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 //
5 // Copyright © 2022 Intel Corporation
6 //
7 // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause
8 
9 #![no_main]
10 
11 use block::{async_io::DiskFile, raw_sync::RawFileDiskSync};
12 use libfuzzer_sys::fuzz_target;
13 use seccompiler::SeccompAction;
14 use std::ffi;
15 use std::fs::File;
16 use std::io;
17 use std::os::unix::io::{AsRawFd, FromRawFd, RawFd};
18 use std::path::PathBuf;
19 use std::sync::Arc;
20 use virtio_devices::{Block, VirtioDevice, VirtioInterrupt, VirtioInterruptType};
21 use virtio_queue::{Queue, QueueT};
22 use vm_memory::{bitmap::AtomicBitmap, Bytes, GuestAddress, GuestMemoryAtomic};
23 use vmm_sys_util::eventfd::{EventFd, EFD_NONBLOCK};
24 
25 type GuestMemoryMmap = vm_memory::GuestMemoryMmap<AtomicBitmap>;
26 
27 const QUEUE_DATA_SIZE: usize = 4;
28 const MEM_SIZE: usize = 256 * 1024 * 1024;
29 // Max entries in the queue.
30 const QUEUE_SIZE: u16 = 256;
31 // Guest physical address for descriptor table.
32 const DESC_TABLE_ADDR: u64 = 0;
33 const DESC_TABLE_SIZE: u64 = 16_u64 * QUEUE_SIZE as u64;
34 // Guest physical address for available ring
35 const AVAIL_RING_ADDR: u64 = DESC_TABLE_ADDR + DESC_TABLE_SIZE;
36 const AVAIL_RING_SIZE: u64 = 6_u64 + 2 * QUEUE_SIZE as u64;
37 // Guest physical address for used ring (requires to 4-bytes aligned)
38 const USED_RING_ADDR: u64 = (AVAIL_RING_ADDR + AVAIL_RING_SIZE + 3) & !3_u64;
39 
40 fuzz_target!(|bytes| {
41     if bytes.len() < QUEUE_DATA_SIZE || bytes.len() > (QUEUE_DATA_SIZE + MEM_SIZE) {
42         return;
43     }
44 
45     let queue_data = &bytes[..QUEUE_DATA_SIZE];
46     let mem_bytes = &bytes[QUEUE_DATA_SIZE..];
47 
48     // Create a virtio-block device backed by a synchronous raw file
49     let shm = memfd_create(&ffi::CString::new("fuzz").unwrap(), 0).unwrap();
50     let disk_file: File = unsafe { File::from_raw_fd(shm) };
51     let qcow_disk = Box::new(RawFileDiskSync::new(disk_file)) as Box<dyn DiskFile>;
52     let mut block = Block::new(
53         "tmp".to_owned(),
54         qcow_disk,
55         PathBuf::from(""),
56         false,
57         false,
58         2,
59         256,
60         SeccompAction::Allow,
61         None,
62         EventFd::new(EFD_NONBLOCK).unwrap(),
63         None,
64     )
65     .unwrap();
66 
67     // Setup the virt queue with the input bytes
68     let q = setup_virt_queue(queue_data.try_into().unwrap());
69 
70     // Setup the guest memory with the input bytes
71     let mem = GuestMemoryMmap::from_ranges(&[(GuestAddress(0), MEM_SIZE)]).unwrap();
72     if mem.write_slice(mem_bytes, GuestAddress(0 as u64)).is_err() {
73         return;
74     }
75     let guest_memory = GuestMemoryAtomic::new(mem);
76 
77     let evt = EventFd::new(0).unwrap();
78     let queue_evt = unsafe { EventFd::from_raw_fd(libc::dup(evt.as_raw_fd())) };
79 
80     // Kick the 'queue' event before activate the block device
81     queue_evt.write(1).unwrap();
82 
83     block
84         .activate(
85             guest_memory,
86             Arc::new(NoopVirtioInterrupt {}),
87             vec![(0, q, evt)],
88         )
89         .ok();
90 
91     // Wait for the events to finish and block device worker thread to return
92     block.wait_for_epoll_threads();
93 });
94 
95 fn memfd_create(name: &ffi::CStr, flags: u32) -> Result<RawFd, io::Error> {
96     let res = unsafe { libc::syscall(libc::SYS_memfd_create, name.as_ptr(), flags) };
97 
98     if res < 0 {
99         Err(io::Error::last_os_error())
100     } else {
101         Ok(res as RawFd)
102     }
103 }
104 
105 pub struct NoopVirtioInterrupt {}
106 
107 impl VirtioInterrupt for NoopVirtioInterrupt {
108     fn trigger(&self, _int_type: VirtioInterruptType) -> std::result::Result<(), std::io::Error> {
109         Ok(())
110     }
111 }
112 
113 fn setup_virt_queue(bytes: &[u8; QUEUE_DATA_SIZE]) -> Queue {
114     let mut q = Queue::new(QUEUE_SIZE).unwrap();
115     q.set_next_avail(bytes[0] as u16); // 'u8' is enough given the 'QUEUE_SIZE' is small
116     q.set_next_used(bytes[1] as u16);
117     q.set_event_idx(bytes[2] % 2 != 0);
118     q.set_size(bytes[3] as u16 % QUEUE_SIZE);
119 
120     q.try_set_desc_table_address(GuestAddress(DESC_TABLE_ADDR))
121         .unwrap();
122     q.try_set_avail_ring_address(GuestAddress(AVAIL_RING_ADDR))
123         .unwrap();
124     q.try_set_used_ring_address(GuestAddress(USED_RING_ADDR))
125         .unwrap();
126     q.set_ready(true);
127 
128     q
129 }
130