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