vsec 0.0.1

Detect secrets and in Rust codebases
Documentation
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
// src/filters/layer3_consequence.rs

use crate::models::{BlockSummary, Consequence, DangerousOp, FactorCategory, ScoreFactor};
use crate::simd::{self, patterns::prebuilt};
use quote::ToTokens;
use syn::{Block, Expr, Stmt};

/// Configuration for consequence analysis
#[derive(Debug, Clone)]
pub struct ConsequenceConfig {
    /// Function names that indicate logging (benign)
    pub logging_functions: Vec<String>,

    /// Function names that indicate auth operations (dangerous)
    pub auth_functions: Vec<String>,

    /// Function names that indicate process control (dangerous)
    pub process_functions: Vec<String>,

    /// Field names that indicate auth state (dangerous)
    pub auth_fields: Vec<String>,

    /// Score for empty/logging-only blocks
    pub benign_block_score: i32,

    /// Score for auth state changes
    pub auth_state_change_score: i32,

    /// Score for auth function calls
    pub auth_function_score: i32,

    /// Score for process control
    pub process_control_score: i32,
}

impl Default for ConsequenceConfig {
    fn default() -> Self {
        Self {
            logging_functions: vec![
                // Standard
                "println".into(),
                "print".into(),
                "eprintln".into(),
                "eprint".into(),
                "dbg".into(),
                "format".into(),
                "write".into(),
                "writeln".into(),
                // log crate
                "trace".into(),
                "debug".into(),
                "info".into(),
                "warn".into(),
                "error".into(),
                // tracing crate
                "trace!".into(),
                "debug!".into(),
                "info!".into(),
                "warn!".into(),
                "error!".into(),
                "event".into(),
                "span".into(),
                // slog
                "log".into(),
                "slog".into(),
            ],
            auth_functions: vec![
                // Authorization
                "authorize".into(),
                "authenticate".into(),
                "login".into(),
                "grant".into(),
                "permit".into(),
                "allow".into(),
                "verify_password".into(),
                "check_password".into(),
                "validate_token".into(),
                "verify_token".into(),
                // Access control
                "set_admin".into(),
                "make_admin".into(),
                "promote".into(),
                "elevate".into(),
                "escalate".into(),
                // Session
                "create_session".into(),
                "start_session".into(),
            ],
            process_functions: vec![
                // Exit
                "exit".into(),
                "abort".into(),
                "panic".into(),
                // Execution
                "exec".into(),
                "spawn".into(),
                "command".into(),
                "system".into(),
                "shell".into(),
            ],
            auth_fields: vec![
                "admin".into(),
                "is_admin".into(),
                "is_authenticated".into(),
                "authenticated".into(),
                "authorized".into(),
                "is_authorized".into(),
                "role".into(),
                "permission".into(),
                "permissions".into(),
                "privilege".into(),
                "privileges".into(),
                "access_level".into(),
                "is_superuser".into(),
                "superuser".into(),
                "is_root".into(),
            ],
            benign_block_score: -40,
            auth_state_change_score: 40,
            auth_function_score: 30,
            process_control_score: 20,
        }
    }
}

/// Consequence analyzer
pub struct ConsequenceAnalyzer {
    config: ConsequenceConfig,
}

impl ConsequenceAnalyzer {
    pub fn new(config: ConsequenceConfig) -> Self {
        Self { config }
    }

    /// Analyze a block and return the consequence summary
    pub fn analyze_block(&self, block: &Block) -> Consequence {
        let summary = self.summarize_block(block);
        let dangerous_ops = self.find_dangerous_ops(block);

        let is_benign = summary.is_empty || (summary.only_logging && dangerous_ops.is_empty());

        Consequence {
            block_summary: summary,
            dangerous_ops,
            is_benign,
        }
    }

    /// Analyze a consequence and return scoring factors
    pub fn score(&self, consequence: &Consequence) -> Vec<ScoreFactor> {
        let mut factors = Vec::new();

        // Benign blocks reduce score
        if consequence.is_benign {
            if consequence.block_summary.is_empty {
                factors.push(ScoreFactor::new(
                    "empty_block",
                    FactorCategory::Consequence,
                    self.config.benign_block_score,
                    "Comparison consequence is an empty block",
                ));
            } else if consequence.block_summary.only_logging {
                factors.push(ScoreFactor::new(
                    "logging_only",
                    FactorCategory::Consequence,
                    self.config.benign_block_score,
                    "Comparison only triggers logging/printing",
                ));
            }
        }

        // Dangerous operations raise score
        for op in &consequence.dangerous_ops {
            match op {
                DangerousOp::AuthStateChange { field } => {
                    factors.push(
                        ScoreFactor::new(
                            "auth_state_change",
                            FactorCategory::Consequence,
                            self.config.auth_state_change_score,
                            "Comparison triggers auth state modification",
                        )
                        .with_evidence(format!("Field: {}", field)),
                    );
                }
                DangerousOp::AuthFunctionCall { function } => {
                    factors.push(
                        ScoreFactor::new(
                            "auth_function_call",
                            FactorCategory::Consequence,
                            self.config.auth_function_score,
                            "Comparison triggers auth-related function",
                        )
                        .with_evidence(format!("Function: {}", function)),
                    );
                }
                DangerousOp::ProcessControl { function } => {
                    factors.push(
                        ScoreFactor::new(
                            "process_control",
                            FactorCategory::Consequence,
                            self.config.process_control_score,
                            "Comparison triggers process control",
                        )
                        .with_evidence(format!("Function: {}", function)),
                    );
                }
                DangerousOp::DatabaseOp { operation } => {
                    factors.push(
                        ScoreFactor::new(
                            "database_op",
                            FactorCategory::Consequence,
                            25,
                            "Comparison triggers database operation",
                        )
                        .with_evidence(format!("Operation: {}", operation)),
                    );
                }
                DangerousOp::NetworkOp { operation } => {
                    factors.push(
                        ScoreFactor::new(
                            "network_op",
                            FactorCategory::Consequence,
                            20,
                            "Comparison triggers network operation",
                        )
                        .with_evidence(format!("Operation: {}", operation)),
                    );
                }
                DangerousOp::FileSystemOp { operation } => {
                    factors.push(
                        ScoreFactor::new(
                            "filesystem_op",
                            FactorCategory::Consequence,
                            15,
                            "Comparison triggers filesystem operation",
                        )
                        .with_evidence(format!("Operation: {}", operation)),
                    );
                }
                DangerousOp::CryptoOp { operation } => {
                    factors.push(
                        ScoreFactor::new(
                            "crypto_op",
                            FactorCategory::Consequence,
                            20,
                            "Comparison triggers cryptographic operation",
                        )
                        .with_evidence(format!("Operation: {}", operation)),
                    );
                }
            }
        }

        factors
    }

    fn summarize_block(&self, block: &Block) -> BlockSummary {
        let is_empty = block.stmts.is_empty();

        let mut only_logging = true;
        let mut has_return = false;
        let mut has_early_exit = false;
        let mut has_mutation = false;
        let mut function_calls = Vec::new();
        let mut field_assignments = Vec::new();

        for stmt in &block.stmts {
            match stmt {
                Stmt::Expr(expr, _) => {
                    self.analyze_expr(
                        expr,
                        &mut only_logging,
                        &mut has_return,
                        &mut has_early_exit,
                        &mut has_mutation,
                        &mut function_calls,
                        &mut field_assignments,
                    );
                }
                Stmt::Local(syn::Local {
                    init: Some(syn::LocalInit { expr, .. }),
                    ..
                }) => {
                    self.analyze_expr(
                        expr.as_ref(),
                        &mut only_logging,
                        &mut has_return,
                        &mut has_early_exit,
                        &mut has_mutation,
                        &mut function_calls,
                        &mut field_assignments,
                    );
                }
                Stmt::Item(_) => {
                    only_logging = false;
                }
                _ => {}
            }
        }

        // If there are any non-logging function calls, it's not only logging
        if function_calls.iter().any(|f| !self.is_logging_function(f)) {
            only_logging = false;
        }

        BlockSummary {
            is_empty,
            only_logging,
            has_return,
            has_early_exit,
            has_mutation,
            function_calls,
            field_assignments,
        }
    }

    fn analyze_expr(
        &self,
        expr: &Expr,
        only_logging: &mut bool,
        has_return: &mut bool,
        has_early_exit: &mut bool,
        has_mutation: &mut bool,
        function_calls: &mut Vec<String>,
        field_assignments: &mut Vec<String>,
    ) {
        match expr {
            Expr::Return(_) => {
                *has_return = true;
                *has_early_exit = true;
            }
            Expr::Break(_) | Expr::Continue(_) => {
                *has_early_exit = true;
            }
            Expr::Assign(assign) => {
                *has_mutation = true;
                *only_logging = false;
                if let Expr::Field(field) = &*assign.left {
                    if let Expr::Path(_) = &*field.base {
                        let field_name = field.member.to_token_stream().to_string();
                        field_assignments.push(field_name);
                    }
                }
            }
            Expr::Call(call) => {
                let func_name = self.extract_function_name(&call.func);
                function_calls.push(func_name.clone());
                if !self.is_logging_function(&func_name) {
                    *only_logging = false;
                }
            }
            Expr::MethodCall(call) => {
                let method_name = call.method.to_string();
                function_calls.push(method_name.clone());
                if !self.is_logging_function(&method_name) {
                    *only_logging = false;
                }
            }
            Expr::Macro(mac) => {
                let macro_name = mac
                    .mac
                    .path
                    .segments
                    .last()
                    .map(|s| s.ident.to_string())
                    .unwrap_or_default();
                function_calls.push(macro_name.clone());
                if !self.is_logging_function(&macro_name) {
                    *only_logging = false;
                }
            }
            Expr::Block(block) => {
                for stmt in &block.block.stmts {
                    if let Stmt::Expr(e, _) = stmt {
                        self.analyze_expr(
                            e,
                            only_logging,
                            has_return,
                            has_early_exit,
                            has_mutation,
                            function_calls,
                            field_assignments,
                        );
                    }
                }
            }
            _ => {
                *only_logging = false;
            }
        }
    }

    fn extract_function_name(&self, func: &Expr) -> String {
        match func {
            Expr::Path(path) => path
                .path
                .segments
                .last()
                .map(|s| s.ident.to_string())
                .unwrap_or_else(|| "unknown".to_string()),
            _ => "unknown".to_string(),
        }
    }

    // Pattern-based function matching using SIMD-accelerated pattern matcher
    fn is_logging_function(&self, name: &str) -> bool {
        // Use SIMD-accelerated lowercase
        let lower = simd::to_ascii_lowercase(name);

        // Use prebuilt logging functions pattern matcher (O(n) instead of O(n*m))
        if prebuilt::logging_functions().is_match(name) {
            return true;
        }

        // Or ends with common suffixes
        if lower.ends_with("_log") || lower.ends_with("_trace") {
            return true;
        }

        // Or matches user-configured patterns
        self.config
            .logging_functions
            .iter()
            .any(|f| lower == simd::to_ascii_lowercase(f))
    }

    /// Check if function is known to be safe (conservative approach)
    #[allow(dead_code)]
    fn is_known_safe(&self, name: &str) -> bool {
        let lower = name.to_lowercase();

        // Only consider functions explicitly safe if they match known patterns
        let safe_patterns = [
            "assert",
            "expect",
            "unwrap",
            "clone",
            "to_string",
            "into",
            "default",
            "new",
            "from",
            "try_from",
            "try_into",
            "len",
            "is_empty",
            "contains",
            "get",
            "first",
            "last",
            "format",
            "display",
            "debug",
        ];

        safe_patterns.iter().any(|p| lower.contains(p))
    }

    /// Pattern-based auth function detection using SIMD-accelerated pattern matcher
    #[allow(dead_code)]
    fn is_auth_function(&self, name: &str) -> bool {
        // Use prebuilt auth functions pattern matcher (O(n) instead of O(n*m))
        if prebuilt::auth_functions().is_match(name) {
            return true;
        }

        // Also check config-provided auth functions
        let lower = simd::to_ascii_lowercase(name);
        self.config
            .auth_functions
            .iter()
            .any(|f| lower.contains(&simd::to_ascii_lowercase(f)))
    }

    fn find_dangerous_ops(&self, block: &Block) -> Vec<DangerousOp> {
        let mut ops = Vec::new();

        for stmt in &block.stmts {
            self.find_dangerous_ops_in_stmt(stmt, &mut ops);
        }

        ops
    }

    fn find_dangerous_ops_in_stmt(&self, stmt: &Stmt, ops: &mut Vec<DangerousOp>) {
        match stmt {
            Stmt::Expr(expr, _) => {
                self.find_dangerous_ops_in_expr(expr, ops);
            }
            Stmt::Local(local) => {
                if let Some(init) = &local.init {
                    self.find_dangerous_ops_in_expr(&init.expr, ops);
                }
            }
            _ => {}
        }
    }

    fn find_dangerous_ops_in_expr(&self, expr: &Expr, ops: &mut Vec<DangerousOp>) {
        match expr {
            Expr::Assign(assign) => {
                // Check if assigning to an auth-related field
                if let Expr::Field(field) = &*assign.left {
                    let field_name = field.member.to_token_stream().to_string();

                    // Use prebuilt auth fields pattern matcher
                    if prebuilt::auth_fields().is_match(&field_name) {
                        ops.push(DangerousOp::AuthStateChange { field: field_name });
                    }
                }
            }
            Expr::Call(call) => {
                let func_name = self.extract_function_name(&call.func);

                // Use prebuilt auth functions pattern matcher
                if prebuilt::auth_functions().is_match(&func_name) {
                    ops.push(DangerousOp::AuthFunctionCall { function: func_name });
                } else if prebuilt::process_functions().is_match(&func_name) {
                    ops.push(DangerousOp::ProcessControl { function: func_name });
                }
            }
            Expr::MethodCall(call) => {
                let method_name = call.method.to_string();

                // Use prebuilt pattern matchers
                if prebuilt::auth_functions().is_match(&method_name) {
                    ops.push(DangerousOp::AuthFunctionCall {
                        function: method_name,
                    });
                } else if prebuilt::process_functions().is_match(&method_name) {
                    ops.push(DangerousOp::ProcessControl {
                        function: method_name,
                    });
                }
            }
            Expr::Block(block) => {
                for stmt in &block.block.stmts {
                    self.find_dangerous_ops_in_stmt(stmt, ops);
                }
            }
            _ => {}
        }
    }
}

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

    #[test]
    fn test_empty_block_is_benign() {
        let analyzer = ConsequenceAnalyzer::new(ConsequenceConfig::default());
        let block: Block = parse_quote! { {} };
        let consequence = analyzer.analyze_block(&block);
        assert!(consequence.is_benign);
    }

    #[test]
    fn test_println_only_is_benign() {
        let analyzer = ConsequenceAnalyzer::new(ConsequenceConfig::default());
        let block: Block = parse_quote! {{
            println!("authenticated");
        }};
        let consequence = analyzer.analyze_block(&block);
        assert!(consequence.is_benign);
    }

    #[test]
    fn test_auth_state_change_is_dangerous() {
        let analyzer = ConsequenceAnalyzer::new(ConsequenceConfig::default());
        let block: Block = parse_quote! {{
            state.is_admin = true;
        }};
        let consequence = analyzer.analyze_block(&block);
        assert!(!consequence.is_benign);
        assert!(consequence
            .dangerous_ops
            .iter()
            .any(|op| { matches!(op, DangerousOp::AuthStateChange { .. }) }));
    }
}