bashrs 6.66.0

Rust-to-Shell transpiler for deterministic bootstrap scripts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
//! SEC017: Unsafe File Permissions (chmod 777)
//!
//! **Rule**: Detect chmod 777, 666, or other overly permissive modes
//!
//! **Why this matters**:
//! chmod 777 gives read/write/execute permissions to everyone (owner, group, world).
//! This is a severe security risk as any user can modify or execute the file.
//!
//! **Auto-fix**: Manual review required (appropriate permissions depend on context)
//!
//! ## Examples
//!
//! ❌ **CRITICAL VULNERABILITY**:
//! ```bash
//! chmod 777 /etc/passwd
//! chmod 666 ~/.ssh/id_rsa
//! chmod -R 777 /var/www
//! ```
//!
//! ✅ **SAFE ALTERNATIVES**:
//! ```bash
//! chmod 644 /etc/passwd    # Owner: rw-, Group: r--, World: r--
//! chmod 600 ~/.ssh/id_rsa  # Owner: rw-, Group: ---, World: ---
//! chmod 755 /var/www       # Owner: rwx, Group: r-x, World: r-x
//! ```

use crate::linter::{Diagnostic, LintResult, Severity, Span};

/// Dangerous file permission modes
const DANGEROUS_MODES: &[&str] = &[
    "777", // rwxrwxrwx - everyone can do everything
    "666", // rw-rw-rw- - everyone can read/write
    "664", // rw-rw-r-- - group can write (risky for sensitive files)
    "776", // rwxrwxrw- - world can write
    "677", // rw-rwxrwx - group/world can execute
];

/// Check for unsafe file permissions (chmod 777, 666, etc.)
pub fn check(source: &str) -> LintResult {
    let mut result = LintResult::new();

    for (line_num, line) in source.lines().enumerate() {
        // Look for chmod command
        if let Some(chmod_col) = find_command(line, "chmod") {
            // Check if line contains dangerous permissions
            for dangerous_mode in DANGEROUS_MODES {
                if contains_mode(line, dangerous_mode) {
                    let span = Span::new(line_num + 1, chmod_col + 1, line_num + 1, line.len());

                    let severity = match *dangerous_mode {
                        "777" | "666" => Severity::Error, // Critical
                        _ => Severity::Warning,           // High risk but not always critical
                    };

                    let diag = Diagnostic::new(
                        "SEC017",
                        severity,
                        format!(
                            "Unsafe file permissions: chmod {} grants excessive permissions - use principle of least privilege",
                            dangerous_mode
                        ),
                        span,
                    );
                    // NO AUTO-FIX: Correct permissions depend on context

                    result.add(diag);
                    break; // Only report once per line
                }
            }
        }
    }

    result
}

/// Find chmod command in a line (word boundary detection)
fn find_command(line: &str, cmd: &str) -> Option<usize> {
    if let Some(pos) = line.find(cmd) {
        // Check word boundaries
        let before_ok = if pos == 0 {
            true
        } else {
            let char_before = line.chars().nth(pos - 1);
            matches!(char_before, Some(' ' | '\t' | ';' | '&' | '|' | '(' | '\n'))
        };

        let after_idx = pos + cmd.len();
        let after_ok = if after_idx >= line.len() {
            true
        } else {
            let char_after = line.chars().nth(after_idx);
            matches!(char_after, Some(' ' | '\t' | ';' | '&' | '|' | ')'))
        };

        if before_ok && after_ok {
            return Some(pos);
        }
    }
    None
}

/// Check if line contains a specific permission mode
/// Check that the character boundary before `mode` in `word` is not a digit
fn is_mode_boundary_before(word: &str, pos: usize) -> bool {
    if pos == 0 {
        return true;
    }
    let char_before = word.chars().nth(pos - 1);
    !matches!(char_before, Some('0'..='9'))
}

/// Check that the character boundary after `mode` in `word` is not a digit
fn is_mode_boundary_after(word: &str, pos: usize, mode_len: usize) -> bool {
    let after_idx = pos + mode_len;
    if after_idx >= word.len() {
        return true;
    }
    let char_after = word.chars().nth(after_idx);
    !matches!(char_after, Some('0'..='9'))
}

/// Check if `word` contains `mode` as a standalone token (not part of a larger number)
fn word_contains_standalone_mode(word: &str, mode: &str) -> bool {
    if let Some(pos) = word.find(mode) {
        is_mode_boundary_before(word, pos) && is_mode_boundary_after(word, pos, mode.len())
    } else {
        false
    }
}

fn contains_mode(line: &str, mode: &str) -> bool {
    for word in line.split_whitespace() {
        if word == mode || word == format!("-R {}", mode) || word.ends_with(&format!(" {}", mode)) {
            return true;
        }
        if word.contains(mode) && word_contains_standalone_mode(word, mode) {
            return true;
        }
    }
    false
}

#[cfg(test)]
mod tests {
    use super::*;

    // RED Phase: Write failing tests first

    #[test]
    fn test_SEC017_detects_chmod_777() {
        let script = "chmod 777 /etc/passwd";
        let result = check(script);

        assert_eq!(result.diagnostics.len(), 1);
        let diag = &result.diagnostics[0];
        assert_eq!(diag.code, "SEC017");
        assert_eq!(diag.severity, Severity::Error);
        assert!(diag.message.contains("777"));
    }

    #[test]
    fn test_SEC017_detects_chmod_666() {
        let script = "chmod 666 sensitive.txt";
        let result = check(script);

        assert_eq!(result.diagnostics.len(), 1);
        let diag = &result.diagnostics[0];
        assert_eq!(diag.code, "SEC017");
        assert_eq!(diag.severity, Severity::Error);
    }

    #[test]
    fn test_SEC017_detects_chmod_recursive_777() {
        let script = "chmod -R 777 /var/www";
        let result = check(script);

        assert_eq!(result.diagnostics.len(), 1);
        assert_eq!(result.diagnostics[0].code, "SEC017");
    }

    #[test]
    fn test_SEC017_safe_chmod_755() {
        let script = "chmod 755 script.sh";
        let result = check(script);

        // 755 is safe (rwxr-xr-x)
        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_SEC017_safe_chmod_644() {
        let script = "chmod 644 config.conf";
        let result = check(script);

        // 644 is safe (rw-r--r--)
        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_SEC017_safe_chmod_600() {
        let script = "chmod 600 ~/.ssh/id_rsa";
        let result = check(script);

        // 600 is safe (rw-------)
        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_SEC017_no_false_positive_comment() {
        let script = "# chmod 777 is dangerous";
        let result = check(script);

        // Should detect even in comments for documentation
        // This is acceptable for security education
    }

    #[test]
    fn test_SEC017_multiple_dangerous_chmod() {
        let script = r#"
chmod 777 /tmp/file1
chmod 666 /tmp/file2
        "#;
        let result = check(script);

        assert_eq!(result.diagnostics.len(), 2);
    }

    #[test]
    fn test_SEC017_no_auto_fix() {
        let script = "chmod 777 file.txt";
        let result = check(script);

        assert_eq!(result.diagnostics.len(), 1);
        let diag = &result.diagnostics[0];
        assert!(diag.fix.is_none(), "SEC017 should not provide auto-fix");
    }

    #[test]
    fn test_SEC017_detects_664_as_warning() {
        let script = "chmod 664 shared.txt";
        let result = check(script);

        assert_eq!(result.diagnostics.len(), 1);
        let diag = &result.diagnostics[0];
        assert_eq!(diag.severity, Severity::Warning); // Not critical but risky
    }

    // ===== Additional tests for coverage =====

    #[test]
    fn test_SEC017_detects_776() {
        let script = "chmod 776 /tmp/shared";
        let result = check(script);

        assert_eq!(result.diagnostics.len(), 1);
        assert_eq!(result.diagnostics[0].severity, Severity::Warning);
    }

    #[test]
    fn test_SEC017_detects_677() {
        let script = "chmod 677 script.sh";
        let result = check(script);

        assert_eq!(result.diagnostics.len(), 1);
        assert_eq!(result.diagnostics[0].severity, Severity::Warning);
    }

    #[test]
    fn test_SEC017_no_chmod_command() {
        let script = "echo 777 is a number";
        let result = check(script);

        // Should not detect 777 without chmod
        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_SEC017_chmod_with_other_options() {
        let script = "chmod -v 777 file.txt";
        let result = check(script);

        assert_eq!(result.diagnostics.len(), 1);
    }

    #[test]
    fn test_SEC017_chmod_in_pipeline() {
        let script = "echo test | chmod 777 -";
        let result = check(script);

        // chmod in pipeline
        assert_eq!(result.diagnostics.len(), 1);
    }

    #[test]
    fn test_SEC017_chmod_after_semicolon() {
        let script = "ls; chmod 777 file.txt";
        let result = check(script);

        assert_eq!(result.diagnostics.len(), 1);
    }

    #[test]
    fn test_SEC017_chmod_after_and() {
        let script = "test -f file && chmod 777 file";
        let result = check(script);

        assert_eq!(result.diagnostics.len(), 1);
    }

    #[test]
    fn test_SEC017_chmod_in_subshell() {
        let script = "(chmod 777 file.txt)";
        let result = check(script);

        assert_eq!(result.diagnostics.len(), 1);
    }

    #[test]
    fn test_SEC017_no_false_positive_1777() {
        // 1777 is sticky bit + 777, but we should be smart about this
        let script = "chmod 1777 /tmp";
        let result = check(script);

        // The 777 pattern should not match within 1777
        // Note: This depends on implementation - if we detect 777 substring, it might match
        // For now, let's verify the behavior
        assert!(result.diagnostics.len() <= 1);
    }

    #[test]
    fn test_SEC017_empty_script() {
        let script = "";
        let result = check(script);

        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_SEC017_whitespace_only() {
        let script = "   \n\t  \n  ";
        let result = check(script);

        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_find_command_no_match() {
        let result = find_command("echo hello", "chmod");
        assert!(result.is_none());
    }

    #[test]
    fn test_find_command_at_start() {
        let result = find_command("chmod 755 file", "chmod");
        assert_eq!(result, Some(0));
    }

    #[test]
    fn test_find_command_after_whitespace() {
        let result = find_command("  chmod 755 file", "chmod");
        assert_eq!(result, Some(2));
    }

    #[test]
    fn test_find_command_not_word_boundary() {
        // mychmod should not match chmod
        let result = find_command("mychmod 777 file", "chmod");
        assert!(result.is_none());
    }

    #[test]
    fn test_contains_mode_exact() {
        assert!(contains_mode("chmod 777 file", "777"));
        assert!(contains_mode("chmod 666 file", "666"));
    }

    #[test]
    fn test_contains_mode_with_recursive() {
        assert!(contains_mode("chmod -R 777 /dir", "777"));
    }

    #[test]
    fn test_contains_mode_not_found() {
        assert!(!contains_mode("chmod 755 file", "777"));
    }
}

#[cfg(test)]
mod property_tests {
    use super::*;
    use proptest::prelude::*;

    proptest! {
        #![proptest_config(proptest::test_runner::Config::with_cases(10))]
        #[test]
        fn prop_sec017_never_panics(s in ".*") {
            let _ = check(&s);
        }

        #[test]
        fn prop_sec017_safe_modes_no_warnings(
            mode in "(600|644|755|700)",
            file in "[a-z/]{1,20}",
        ) {
            let cmd = format!("chmod {} {}", mode, file);
            let result = check(&cmd);
            // Safe modes should not trigger warnings
            prop_assert_eq!(result.diagnostics.len(), 0);
        }

        #[test]
        fn prop_sec017_dangerous_modes_detected(
            mode in "(777|666)",
            file in "[a-z/]{1,20}",
        ) {
            let cmd = format!("chmod {} {}", mode, file);
            let result = check(&cmd);
            // Dangerous modes should always be detected
            prop_assert!(!result.diagnostics.is_empty());
            prop_assert_eq!(result.diagnostics[0].code.as_str(), "SEC017");
        }
    }
}