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