Building 70 Projects ranging from beginner to advanced so anyone can — learn from, build upon, use as a reference, or even copy directly. Owned by my cybersecurity company 👇
Go aicertificationcloud-engineeringcybercybersecuritycybersecurity-analystcybersecurity-certificationcybersecurity-certificationscybersecurity-educationcybersecurity-jobscybersecurity-portfoliocybersecurity-projectscybersecurity-toolsgrchackinglearningpentestingproject-repositoryprojetcspython
feat(lisdex): B19 - tokenize agrees with /bin/sh, and the differential that proved it is now permanent
CarterPerez-dev5fad865ddd6c
diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-build/src/replay.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-build/src/replay.rsindex 3867ec61..8193e5fa 100644--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-build/src/replay.rs+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-build/src/replay.rs@@ -66,23 +66,51 @@ impl ReplayReport {}}+// The shell's default IFS, which is these three and nothing else. `char::is_whitespace` is+// Unicode-aware, so it split a token on U+00A0 that /bin/sh keeps whole.+const FIELD_SEPARATORS: [char; 3] = [' ', '\t', '\n'];++// Inside double quotes a backslash is only special before one of these, or a newline.+// Everywhere else it stands for itself, which is why `-DP="C:\dir\file"` must survive intact+// instead of replaying as `-DP=C:dirfile`.+const ESCAPABLE_IN_DOUBLE_QUOTES: [char; 4] = ['$', '`', '"', '\\'];++// Differential-tested against /bin/sh over a corpus of compile-command shapes. The oracle is+// only valid where parsing is pure word-splitting and quote removal, so the corpus carries no+// expansion, glob or operator: this splits words, it is deliberately NOT a shell.+//+// None means the command cannot be split at all because a quote is never closed. The shell+// calls that a syntax error and exits 2, and a caller that guessed instead would replay a+// command other than the one that was captured.#[must_use]-pub fn tokenize(command: &str) -> Vec<String> {+pub fn tokenize(command: &str) -> Option<Vec<String>> {let mut tokens = Vec::new();let mut current = String::new();let mut started = false;let mut single = false;let mut double = false;- let mut chars = command.chars();+ let mut chars = command.chars().peekable();while let Some(character) = chars.next() {match character {- '\\' if !single => {- if let Some(escaped) = chars.next() {+ '\\' if single => current.push('\\'),+ '\\' if double => match chars.peek() {+ Some('\n') => {+ chars.next();+ }+ Some(next) if ESCAPABLE_IN_DOUBLE_QUOTES.contains(next) => {+ current.push(*next);+ chars.next();+ }+ _ => current.push('\\'),+ },+ '\\' => match chars.next() {+ Some('\n') | None => {}+ Some(escaped) => {current.push(escaped);started = true;}- }+ },'\'' if !double => {single = !single;started = true;@@ -91,7 +119,7 @@ pub fn tokenize(command: &str) -> Vec<String> {double = !double;started = true;}- character if character.is_whitespace() && !single && !double => {+ character if FIELD_SEPARATORS.contains(&character) && !single && !double => {if started {tokens.push(std::mem::take(&mut current));started = false;@@ -103,18 +131,21 @@ pub fn tokenize(command: &str) -> Vec<String> {}}}+ if single || double {+ return None;+ }if started {tokens.push(current);}- tokens+ Some(tokens)}#[must_use]-pub fn argv(entry: &CompileCommand) -> Vec<String> {+pub fn argv(entry: &CompileCommand) -> Option<Vec<String>> {match (&entry.arguments, &entry.command) {- (Some(arguments), _) if !arguments.is_empty() => arguments.clone(),+ (Some(arguments), _) if !arguments.is_empty() => Some(arguments.clone()),(_, Some(command)) => tokenize(command),- _ => Vec::new(),+ _ => Some(Vec::new()),}}@@ -182,7 +213,7 @@ pub fn is_a_host_tool(path: &Path) -> bool {#[must_use]pub fn rewrite(entry: &CompileCommand, instrumentation: &Instrumentation) -> Option<CommandSpec> {- let argv = strip_launchers(argv(entry));+ let argv = strip_launchers(argv(entry)?);if argv.iter().any(|arg| FRONTEND_ONLY_ARGS.contains(&arg.as_str()))@@ -257,6 +288,18 @@ pub fn replay(let timeout = Duration::from_secs(REPLAY_TIMEOUT_SECS);let mut report = ReplayReport::default();for entry in entries {+ // Skipped and unsplittable are not the same thing, and collapsing them hides the+ // second: one is a command lisdex chose not to replay, the other is one it could not+ // read. A database it cannot read means an incomplete replay, and an incomplete+ // replay produces a library that is only partly instrumented.+ let Some(words) = argv(entry) else {+ report.failures.push(format!(+ "{}: the recorded command cannot be split into words because a quote is never \+ closed, so replaying it would compile something other than what was captured",+ entry.file+ ));+ continue;+ };let Some(spec) = rewrite(entry, instrumentation) else {report.skipped += 1;continue;@@ -264,7 +307,7 @@ pub fn replay(report.attempted += 1;let execution = process::run(&spec, timeout)?;if execution.success {- if let Some(stamp) = output_of(entry, &argv(entry))+ if let Some(stamp) = output_of(entry, &words).as_deref().and_then(libtool_stamp_of)&& refresh(&stamp).is_ok()@@ -294,15 +337,19 @@ mod tests {}}+ fn split(command: &str) -> Vec<String> {+ tokenize(command).unwrap()+ }+#[test]fn tokenizer_splits_on_whitespace() {- assert_eq!(tokenize("cc -c png.c"), vec!["cc", "-c", "png.c"]);+ assert_eq!(split("cc -c png.c"), vec!["cc", "-c", "png.c"]);}#[test]fn tokenizer_keeps_quoted_arguments_whole() {assert_eq!(- tokenize(r#"cc -DNAME="lib png" -c png.c"#),+ split(r#"cc -DNAME="lib png" -c png.c"#),vec!["cc", "-DNAME=lib png", "-c", "png.c"]);}@@ -310,7 +357,7 @@ mod tests {#[test]fn tokenizer_honours_single_quotes_and_backslashes() {assert_eq!(- tokenize(r#"cc -DPATH='/a b/c' -DQ=\"x\" png.c"#),+ split(r#"cc -DPATH='/a b/c' -DQ=\"x\" png.c"#),vec!["cc", "-DPATH=/a b/c", "-DQ=\"x\"", "png.c"]);}@@ -318,16 +365,80 @@ mod tests {#[test]fn tokenizer_preserves_empty_quoted_arguments() {assert_eq!(- tokenize(r#"cc -DEMPTY="" png.c"#),+ split(r#"cc -DEMPTY="" png.c"#),vec!["cc", "-DEMPTY=", "png.c"]);}+ #[test]+ fn a_windows_path_in_double_quotes_keeps_its_backslashes() {+ assert_eq!(+ split(r#"cc -DP="C:\dir\file""#),+ vec!["cc", r"-DP=C:\dir\file"],+ "the shell only treats a backslash as an escape inside double quotes when it \+ precedes one of $ ` \" or a backslash, so this replayed as -DP=C:dirfile"+ );+ }++ #[test]+ fn the_four_characters_a_backslash_does_escape_in_double_quotes_are_escaped() {+ assert_eq!(split(r#"cc "a\"b""#), vec!["cc", r#"a"b"#]);+ assert_eq!(split(r#"cc "a\\b""#), vec!["cc", r"a\b"]);+ assert_eq!(split(r#"cc "a\$b""#), vec!["cc", "a$b"]);+ assert_eq!(split("cc \"a\\`b\""), vec!["cc", "a`b"]);+ }++ #[test]+ fn a_backslash_inside_single_quotes_is_never_an_escape() {+ assert_eq!(+ split(r"cc -DP='C:\dir\file'"),+ vec!["cc", r"-DP=C:\dir\file"]+ );+ }++ #[test]+ fn only_the_shells_own_field_separators_split_a_word() {+ assert_eq!(+ split("cc -DA=one\u{00a0}two"),+ vec!["cc", "-DA=one\u{00a0}two"],+ "IFS is space, tab and newline; char::is_whitespace is Unicode-aware and split \+ this token in half"+ );+ assert_eq!(split("cc\t-c\nfoo.c"), vec!["cc", "-c", "foo.c"]);+ }++ #[test]+ fn a_command_whose_quote_is_never_closed_is_refused_rather_than_guessed() {+ assert_eq!(tokenize("cc -o 'unterminated"), None);+ assert_eq!(tokenize(r#"cc -o "unterminated"#), None);+ assert!(+ tokenize("cc -o 'closed' fine").is_some(),+ "a balanced command still splits"+ );+ }++ #[test]+ fn a_command_that_cannot_be_split_is_a_failure_and_not_a_skip() {+ let report = replay(+ &[entry("cc -c 'unterminated.c", "unterminated.c")],+ &Instrumentation::instrumented(),+ )+ .unwrap();+ assert_eq!(report.attempted, 0);+ assert_eq!(+ report.skipped, 0,+ "counting this as skipped would say lisdex chose not to replay it, when it could \+ not read it"+ );+ assert_eq!(report.failures.len(), 1);+ assert!(report.failures[0].contains("quote is never closed"));+ }+#[test]fn arguments_are_preferred_over_command() {let mut item = entry("cc -c wrong.c", "png.c");item.arguments = Some(vec!["cc".to_owned(), "-c".to_owned(), "png.c".to_owned()]);- assert_eq!(argv(&item), vec!["cc", "-c", "png.c"]);+ assert_eq!(argv(&item).unwrap(), vec!["cc", "-c", "png.c"]);}#[test]@@ -443,7 +554,7 @@ mod tests {let entries = load(&path).unwrap();assert_eq!(entries.len(), 2);assert_eq!(entries[1].output.as_deref(), Some("pngread.o"));- assert_eq!(argv(&entries[1])[0], "cc");+ assert_eq!(argv(&entries[1]).unwrap()[0], "cc");}#[test]diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-build/tests/tokenize_differential.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-build/tests/tokenize_differential.rsnew file mode 100644index 00000000..78370eb9--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-build/tests/tokenize_differential.rs@@ -0,0 +1,110 @@+// ©AngelaMos | 2026+// tokenize_differential.rs++use std::process::Command;++use lisdex_build::replay::tokenize;++const SHELL: &str = "/bin/sh";++// The oracle is the shell itself, because a hand-written table of expected splits only ever+// encodes what its author already believed. This one is valid ONLY for inputs whose parsing+// is pure word-splitting and quote removal, so the corpus carries no expansion, no glob and+// no operator: `tokenize` splits the words of a captured compile command and is deliberately+// not a shell. Four divergences were found this way, all four of them real.+fn shell_words(input: &str) -> Option<Vec<String>> {+ let run = Command::new(SHELL)+ .arg("-c")+ .arg(format!("printf '%s\\n' {input}"))+ .output()+ .ok()?;+ if !run.status.success() {+ return None;+ }+ let text = String::from_utf8_lossy(&run.stdout);+ let mut words: Vec<String> = text.lines().map(str::to_owned).collect();+ // `printf '%s\n'` with no arguments still writes one empty line.+ if words.len() == 1 && words[0].is_empty() {+ words.clear();+ }+ Some(words)+}++const CORPUS: &[&str] = &[+ "cc -c foo.c",+ "cc -c foo.c",+ "cc -o 'my file.o' foo.c",+ "cc -o \"my file.o\" foo.c",+ "cc -DNAME=value",+ "cc -DNAME='va lue'",+ "cc -DNAME=\"va lue\"",+ "cc -DP=\"C:\\dir\\file\"",+ "cc -DP='C:\\dir\\file'",+ "cc -DP=C:\\dir\\file",+ "cc -DQ=\"a\\\"b\"",+ "cc -DQ='a\"b'",+ "cc -DR=\"a\\\\b\"",+ "cc -DS=a\\ b",+ "cc ''",+ "cc \"\"",+ "cc a''b",+ "cc a\"\"b",+ "cc 'a'\"b\"c",+ "cc -I/usr/include -I'/opt/my lib/include'",+ "cc\t-c\tfoo.c",+ "cc -c foo.c\n",+ "cc -Wl,-rpath,'/opt/a b'",+ "cc -DT=\"it's\"",+ "cc -DU='say \"hi\"'",+ "cc -DV=\"tab\there\"",+ "cc --param=x=y",+ "cc -DW=\"\\n\"",+ "cc -DX='\\n'",+ "cc -DY=one\u{00a0}two",+ "cc -DZ=\"one\u{00a0}two\"",+];++#[test]+fn tokenize_agrees_with_the_shell_on_every_corpus_command() {+ let mut divergences = Vec::new();+ let mut checked = 0;+ for input in CORPUS {+ let Some(expected) = shell_words(input) else {+ // The shell refused to parse it, so it says nothing about word splitting.+ continue;+ };+ checked += 1;+ match tokenize(input) {+ Some(actual) if actual == expected => {}+ Some(actual) => {+ divergences.push(format!("{input:?}\n sh={expected:?}\n us={actual:?}"));+ }+ None => divergences.push(format!("{input:?} refused, but sh accepted it")),+ }+ }+ assert!(+ checked >= CORPUS.len() - 1,+ "the oracle went quiet: only {checked} of {} inputs were graded, so agreement would \+ be vacuous",+ CORPUS.len()+ );+ assert!(+ divergences.is_empty(),+ "tokenize disagrees with {SHELL} on {} of {checked} commands:\n{}",+ divergences.len(),+ divergences.join("\n")+ );+}++#[test]+fn the_shell_also_refuses_the_commands_tokenize_refuses() {+ for input in ["cc -o 'unterminated", "cc -o \"unterminated"] {+ assert_eq!(tokenize(input), None, "{input:?}");+ assert_eq!(+ shell_words(input),+ None,+ "{input:?} must be a syntax error for the shell too, or refusing it is our own \+ invention rather than the shell's rule"+ );+ }+}