xref: /cloud-hypervisor/fuzz/fuzz_targets/block.rs (revision eea9bcea38e0c5649f444c829f3a4f9c22aa486c)
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_util::{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     )
64     .unwrap();
65 
66     // Setup the virt queue with the input bytes
67     let q = setup_virt_queue(queue_data.try_into().unwrap());
68 
69     // Setup the guest memory with the input bytes
70     let mem = GuestMemoryMmap::from_ranges(&[(GuestAddress(0), MEM_SIZE)]).unwrap();
71     if mem.write_slice(mem_bytes, GuestAddress(0 as u64)).is_err() {
72         return;
73     }
74     let guest_memory = GuestMemoryAtomic::new(mem);
75 
76     let evt = EventFd::new(0).unwrap();
77     let queue_evt = unsafe { EventFd::from_raw_fd(libc::dup(evt.as_raw_fd())) };
78 
79     // Kick the 'queue' event before activate the block device
80     queue_evt.write(1).unwrap();
81 
82     block
83         .activate(
84             guest_memory,
85             Arc::new(NoopVirtioInterrupt {}),
86             vec![(0, q, evt)],
87         )
88         .ok();
89 
90     // Wait for the events to finish and block device worker thread to return
91     block.wait_for_epoll_threads();
92 });
93 
94 fn memfd_create(name: &ffi::CStr, flags: u32) -> Result<RawFd, io::Error> {
95     let res = unsafe { libc::syscall(libc::SYS_memfd_create, name.as_ptr(), flags) };
96 
97     if res < 0 {
98         Err(io::Error::last_os_error())
99     } else {
100         Ok(res as RawFd)
101     }
102 }
103 
104 pub struct NoopVirtioInterrupt {}
105 
106 impl VirtioInterrupt for NoopVirtioInterrupt {
107     fn trigger(&self, _int_type: VirtioInterruptType) -> std::result::Result<(), std::io::Error> {
108         Ok(())
109     }
110 }
111 
112 fn setup_virt_queue(bytes: &[u8; QUEUE_DATA_SIZE]) -> Queue {
113     let mut q = Queue::new(QUEUE_SIZE).unwrap();
114     q.set_next_avail(bytes[0] as u16); // 'u8' is enough given the 'QUEUE_SIZE' is small
115     q.set_next_used(bytes[1] as u16);
116     q.set_event_idx(bytes[2] % 2 != 0);
117     q.set_size(bytes[3] as u16 % QUEUE_SIZE);
118 
119     q.try_set_desc_table_address(GuestAddress(DESC_TABLE_ADDR))
120         .unwrap();
121     q.try_set_avail_ring_address(GuestAddress(AVAIL_RING_ADDR))
122         .unwrap();
123     q.try_set_used_ring_address(GuestAddress(USED_RING_ADDR))
124         .unwrap();
125     q.set_ready(true);
126 
127     q
128 }
129