codeint_lang_shell/
hazards.rs1mod bashisms;
2mod commands;
3mod secrets;
4mod strict_mode;
5
6use std::collections::BTreeSet;
7
8use codeint_model::HazardLine;
9
10use crate::dialect::ShellDialect;
11use crate::functions::ExtractedFunctions;
12use crate::lexer::ShellToken;
13
14pub const SHELL_HAZARD_RULES: &[&str] = &[
15 "missing-strict-mode",
16 "unquoted-variable",
17 "eval-with-variable",
18 "pipe-download-to-shell",
19 "unchecked-cd",
20 "unguarded-rm-rf",
21 "hardcoded-secret",
22 "read-without-r",
23 "posix-sh-bashism",
24 "insecure-tls-download",
25];
26
27pub fn hazard_line_rules() -> impl Iterator<Item = &'static str> {
28 SHELL_HAZARD_RULES.iter().copied()
29}
30
31pub(crate) fn evaluate(
32 tokens: &[ShellToken],
33 code_lines: &BTreeSet<u32>,
34 extracted: &ExtractedFunctions,
35 dialect: ShellDialect,
36 source: &str,
37) -> Vec<HazardLine> {
38 let mut hits: BTreeSet<(u32, &'static str)> = BTreeSet::new();
39 let strict = strict_mode::analyze(tokens, extracted, dialect, source);
40 if strict.has_top_level_code
41 && !strict.has_strict_mode
42 && let Some(&first_code_line) = code_lines.first()
43 {
44 hits.insert((first_code_line, "missing-strict-mode"));
45 }
46 let scope = if strict.has_errexit {
47 ErrexitScope::Uniform(true)
48 } else {
49 ErrexitScope::PerToken(&strict.errexit_tokens)
50 };
51 evaluate_stream(tokens, code_lines, scope, dialect, &mut hits);
52 hits.into_iter()
53 .map(|(line, rule)| HazardLine {
54 line,
55 rule: rule.to_owned(),
56 })
57 .collect()
58}
59
60#[derive(Clone, Copy)]
61pub(super) enum ErrexitScope<'a> {
62 Uniform(bool),
63 PerToken(&'a [bool]),
64}
65
66impl ErrexitScope<'_> {
67 pub(super) fn at(self, idx: usize) -> bool {
68 match self {
69 Self::Uniform(value) => value,
70 Self::PerToken(flags) => flags.get(idx).copied().unwrap_or(false),
71 }
72 }
73}
74
75fn evaluate_stream(
76 tokens: &[ShellToken],
77 code_lines: &BTreeSet<u32>,
78 scope: ErrexitScope<'_>,
79 dialect: ShellDialect,
80 hits: &mut BTreeSet<(u32, &'static str)>,
81) {
82 commands::check_stream(tokens, code_lines, scope, dialect, hits);
83 secrets::check_stream(tokens, code_lines, hits);
84 if dialect == ShellDialect::PosixSh {
85 bashisms::check_stream(tokens, code_lines, hits);
86 }
87 for (idx, tok) in tokens.iter().enumerate() {
88 for sub in &tok.sub_tokens {
89 let sub_scope = ErrexitScope::Uniform(scope.at(idx));
90 evaluate_stream(sub, code_lines, sub_scope, dialect, hits);
91 }
92 }
93}
94
95pub(super) fn emit_line(
96 line: u32,
97 rule: &'static str,
98 code_lines: &BTreeSet<u32>,
99 hits: &mut BTreeSet<(u32, &'static str)>,
100) {
101 if code_lines.contains(&line) {
102 hits.insert((line, rule));
103 }
104}