Debian Codegraph @

fuzz/fuzz_targets/fuzz_cksum.rs

raw
1 // This file is part of the uutils coreutils package.
2 //
3 // For the full copyright and license information, please view the LICENSE
4 // file that was distributed with this source code.
5
6 // spell-checker:ignore chdir
7
8 #![no_main]
9 use libfuzzer_sys::fuzz_target;
10 use rand::RngExt;
11 use std::env::temp_dir;
12 use std::ffi::OsString;
13 use std::fs::{self, File};
14 use std::io::{self, Write};
15 use std::process::Command;
16 use uu_cksum::uumain;
17 use uufuzz::{
18 CommandResult, compare_result, generate_and_run_uumain, generate_random_file,
19 generate_random_string,
20 pretty_print::{print_or_empty, print_test_begin},
21 replace_fuzz_binary_name, run_gnu_cmd,
22 };
23
24 static CMD_PATH: &str = "cksum";
25
26 fn generate_cksum_args() -> Vec<String> {
27 let mut rng = rand::rng();
28 let mut args = Vec::new();
29
30 let digests = [
31 "sysv", "bsd", "crc", "md5", "sha1", "sha224", "sha256", "sha384", "sha512", "blake2b",
32 "sm3",
33 ];
34 let digest_opts = [
35 "--base64",
36 "--raw",
37 "--tag",
38 "--untagged",
39 "--text",
40 "--binary",
41 ];
42
43 if rng.random_bool(0.3) {
44 args.push("-a".to_string());
45 args.push(digests[rng.random_range(0..digests.len())].to_string());
46 }
47
48 if rng.random_bool(0.2) {
49 args.push(digest_opts[rng.random_range(0..digest_opts.len())].to_string());
50 }
51
52 if rng.random_bool(0.15) {
53 args.push("-l".to_string());
54 args.push(rng.random_range(8..513).to_string());
55 }
56
57 if rng.random_bool(0.05) {
58 for _ in 0..rng.random_range(0..3) {
59 args.push(format!("file_{}", generate_random_string(5)));
60 }
61 } else {
62 args.push("-c".to_string());
63 }
64
65 if rng.random_bool(0.25)
66 && let Ok(file_path) = generate_random_file()
67 {
68 args.push(file_path);
69 }
70
71 if args.is_empty() || !args.iter().any(|arg| arg.starts_with("file_")) {
72 args.push("-a".to_string());
73 args.push(digests[rng.random_range(0..digests.len())].to_string());
74
75 if let Ok(file_path) = generate_random_file() {
76 args.push(file_path);
77 }
78 }
79
80 args
81 }
82
83 fn generate_checksum_file(algo: &str, file_path: &str, digest_opts: &[&str]) -> io::Result<String> {
84 let checksum_file_path = temp_dir().join("checksum_file");
85 let mut cmd = Command::new(CMD_PATH);
86 cmd.arg("-a").arg(algo);
87
88 for opt in digest_opts {
89 cmd.arg(opt);
90 }
91
92 cmd.arg(file_path);
93 let output = cmd.output()?;
94
95 let mut checksum_file = File::create(&checksum_file_path)?;
96 checksum_file.write_all(&output.stdout)?;
97
98 Ok(checksum_file_path.to_str().unwrap().to_string())
99 }
100
101 fn select_random_digest_opts<'a>(
102 rng: &mut rand::rngs::ThreadRng,
103 digest_opts: &'a [&'a str],
104 ) -> Vec<&'a str> {
105 digest_opts
106 .iter()
107 .filter(|_| rng.random_bool(0.5))
108 .copied()
109 .collect()
110 }
111
112 fuzz_target!(|_data: &[u8]| {
113 let cksum_args = generate_cksum_args();
114 let mut args = vec![OsString::from("cksum")];
115 args.extend(cksum_args.iter().map(OsString::from));
116
117 if let Ok(file_path) = generate_random_file() {
118 let algo = cksum_args
119 .iter()
120 .position(|arg| arg == "-a")
121 .map_or("md5", |index| &cksum_args[index + 1]);
122
123 let all_digest_opts = ["--base64", "--raw", "--tag", "--untagged"];
124 let mut rng = rand::rng();
125 let selected_digest_opts = select_random_digest_opts(&mut rng, &all_digest_opts);
126
127 if let Ok(checksum_file_path) =
128 generate_checksum_file(algo, &file_path, &selected_digest_opts)
129 {
130 print_test_begin(format!("cksum {args:?}"));
131
132 if let Ok(content) = fs::read_to_string(&checksum_file_path) {
133 println!("File content ({checksum_file_path})");
134 print_or_empty(&content);
135 } else {
136 eprintln!("Error reading the checksum file.");
137 }
138 let mut rust_result = generate_and_run_uumain(&args, uumain, None);
139
140 let gnu_result = match run_gnu_cmd(CMD_PATH, &args[1..], false, None) {
141 Ok(result) => result,
142 Err(error_result) => {
143 eprintln!("Failed to run GNU command:");
144 eprintln!("Stderr: {}", error_result.stderr);
145 eprintln!("Exit Code: {}", error_result.exit_code);
146 CommandResult {
147 stdout: String::new(),
148 stderr: error_result.stderr,
149 exit_code: error_result.exit_code,
150 }
151 }
152 };
153
154 // Lower the number of false positives caused by binary names
155 replace_fuzz_binary_name("cksum", &mut rust_result);
156
157 compare_result(
158 "cksum",
159 &format!("{:?}", &args[1..]),
160 None,
161 &rust_result,
162 &gnu_result,
163 false,
164 );
165 }
166 }
167 });