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
// src/filters/layer4_rhs.rs

use crate::models::{ComparisonSide, FactorCategory, ScoreFactor, VariableSource};
use crate::simd::{self, patterns::prebuilt};

/// Configuration for RHS analysis
#[derive(Debug, Clone)]
pub struct RhsConfig {
    /// Variable names that suggest routing/commands (reduce score)
    pub command_like_names: Vec<String>,

    /// Variable names that suggest auth data (increase score)
    pub auth_like_names: Vec<String>,

    /// Variable names that suggest user input (increase score)
    pub input_like_names: Vec<String>,

    /// Function/method names that suggest external input
    pub external_input_functions: Vec<String>,

    /// Score modifier for command-like variables
    pub command_score_mod: i32,

    /// Score modifier for auth-like variables
    pub auth_score_mod: i32,

    /// Score modifier for user input
    pub input_score_mod: i32,

    /// Score modifier for external input functions
    pub external_input_score_mod: i32,
}

impl Default for RhsConfig {
    fn default() -> Self {
        Self {
            command_like_names: vec![
                // Commands/Actions
                "cmd".into(),
                "command".into(),
                "action".into(),
                "op".into(),
                "operation".into(),
                "verb".into(),
                "method".into(),
                // Modes
                "mode".into(),
                "type".into(),
                "kind".into(),
                "variant".into(),
                // Arguments
                "arg".into(),
                "args".into(),
                "argument".into(),
                "argv".into(),
                "flag".into(),
                "flags".into(),
                "option".into(),
                "opt".into(),
                // Routing
                "route".into(),
                "path".into(),
                "endpoint".into(),
                "uri".into(),
                "url".into(),
                "resource".into(),
                // Protocol
                "message_type".into(),
                "msg_type".into(),
                "event_type".into(),
                "packet_type".into(),
                "frame_type".into(),
                // Configuration/Settings
                "interval".into(),
                "qos".into(),
                "cert".into(),
                "dir".into(),
                "format".into(),
                "level".into(),
                "timeout".into(),
                "port".into(),
                "host".into(),
            ],
            auth_like_names: vec![
                // Tokens
                "token".into(),
                "auth_token".into(),
                "access_token".into(),
                "bearer".into(),
                "jwt".into(),
                "session_token".into(),
                // Passwords
                "password".into(),
                "passwd".into(),
                "pwd".into(),
                "pass".into(),
                "secret".into(),
                "credential".into(),
                "credentials".into(),
                // Keys
                "key".into(),
                "api_key".into(),
                "apikey".into(),
                "secret_key".into(),
                "private_key".into(),
                "signing_key".into(),
                // Auth
                "auth".into(),
                "authorization".into(),
                "authenticate".into(),
                // Hash
                "hash".into(),
                "digest".into(),
                "signature".into(),
            ],
            input_like_names: vec![
                "input".into(),
                "user_input".into(),
                "request".into(),
                "req".into(),
                "payload".into(),
                "body".into(),
                "data".into(),
                "content".into(),
                "query".into(),
                "params".into(),
                "form".into(),
            ],
            external_input_functions: vec![
                // HTTP
                "header".into(),
                "get_header".into(),
                "headers".into(),
                "query".into(),
                "query_param".into(),
                "param".into(),
                "form".into(),
                "body".into(),
                "json".into(),
                // Environment
                "env".into(),
                "var".into(),
                "env_var".into(),
                "getenv".into(),
                // File
                "read".into(),
                "read_to_string".into(),
                "read_line".into(),
                // Network
                "recv".into(),
                "receive".into(),
                // User input
                "stdin".into(),
                "readline".into(),
            ],
            command_score_mod: -30,
            auth_score_mod: 25,
            input_score_mod: 15,
            external_input_score_mod: 20,
        }
    }
}

/// RHS analyzer
pub struct RhsAnalyzer {
    config: RhsConfig,
}

impl RhsAnalyzer {
    pub fn new(config: RhsConfig) -> Self {
        Self { config }
    }

    /// Analyze the variable side of a comparison
    pub fn analyze(&self, variable: &ComparisonSide) -> Vec<ScoreFactor> {
        let mut factors = Vec::new();

        // Analyze based on type of variable
        match variable {
            ComparisonSide::Variable { name, source } => {
                factors.extend(self.analyze_variable_name(name));
                if let Some(src) = source {
                    factors.extend(self.analyze_variable_source(src));
                }
            }
            ComparisonSide::FieldAccess { base, field } => {
                factors.extend(self.analyze_variable_name(field));
                factors.extend(self.analyze_variable_name(base));
            }
            ComparisonSide::MethodCall {
                receiver,
                method,
                args,
            } => {
                factors.extend(self.analyze_method_call(receiver, method, args));
            }
            ComparisonSide::FunctionCall { path, args } => {
                factors.extend(self.analyze_function_call(path, args));
            }
            _ => {}
        }

        factors
    }

    fn analyze_variable_name(&self, name: &str) -> Vec<ScoreFactor> {
        let mut factors = Vec::new();

        // Use SIMD-accelerated pattern matchers (O(n) instead of O(n*m))
        // Check for command-like names (reduce suspicion)
        if prebuilt::command_like().is_match(name) {
            factors.push(
                ScoreFactor::new(
                    "rhs_command_like",
                    FactorCategory::RightHandSide,
                    self.config.command_score_mod,
                    "Variable name suggests routing/command handling",
                )
                .with_evidence(format!("Variable: {}", name)),
            );
        }

        // Check for auth-like names (increase suspicion)
        if prebuilt::auth_like().is_match(name) {
            factors.push(
                ScoreFactor::new(
                    "rhs_auth_like",
                    FactorCategory::RightHandSide,
                    self.config.auth_score_mod,
                    "Variable name suggests authentication data",
                )
                .with_evidence(format!("Variable: {}", name)),
            );
        }

        // Check for input-like names
        if prebuilt::input_like().is_match(name) {
            factors.push(
                ScoreFactor::new(
                    "rhs_input_like",
                    FactorCategory::RightHandSide,
                    self.config.input_score_mod,
                    "Variable name suggests user/external input",
                )
                .with_evidence(format!("Variable: {}", name)),
            );
        }

        factors
    }

    fn analyze_variable_source(&self, source: &VariableSource) -> Vec<ScoreFactor> {
        let mut factors = Vec::new();

        let (score, reason) = match source {
            VariableSource::Parameter => (10, "Value comes from function parameter"),
            VariableSource::Environment => (20, "Value comes from environment variable"),
            VariableSource::Header => (25, "Value comes from HTTP header"),
            VariableSource::QueryParam => (20, "Value comes from query parameter"),
            VariableSource::RequestBody => (20, "Value comes from request body"),
            VariableSource::FileRead => (15, "Value comes from file read"),
            VariableSource::Stdin => (25, "Value comes from user input"),
            VariableSource::Database => (15, "Value comes from database"),
            VariableSource::Unknown => (0, "Unknown source"),
        };

        if score > 0 {
            factors.push(
                ScoreFactor::new("rhs_source", FactorCategory::RightHandSide, score, reason)
                    .with_evidence(format!("Source: {:?}", source)),
            );
        }

        factors
    }

    fn analyze_method_call(
        &self,
        receiver: &str,
        method: &str,
        _args: &[String],
    ) -> Vec<ScoreFactor> {
        let mut factors = Vec::new();
        // Use SIMD-accelerated lowercase
        let lower_method = simd::to_ascii_lowercase(method);

        // Check if method suggests external input
        if self
            .config
            .external_input_functions
            .iter()
            .any(|f| lower_method.contains(f))
        {
            factors.push(
                ScoreFactor::new(
                    "rhs_external_input",
                    FactorCategory::RightHandSide,
                    self.config.external_input_score_mod,
                    "Value comes from external input method",
                )
                .with_evidence(format!("{}.{}()", receiver, method)),
            );
        }

        // Check receiver name too
        factors.extend(self.analyze_variable_name(receiver));

        factors
    }

    fn analyze_function_call(&self, path: &str, _args: &[String]) -> Vec<ScoreFactor> {
        let mut factors = Vec::new();
        // Use SIMD-accelerated lowercase
        let lower_path = simd::to_ascii_lowercase(path);

        // Check if function suggests external input
        if self
            .config
            .external_input_functions
            .iter()
            .any(|f| lower_path.contains(f))
        {
            factors.push(
                ScoreFactor::new(
                    "rhs_external_function",
                    FactorCategory::RightHandSide,
                    self.config.external_input_score_mod,
                    "Value comes from external input function",
                )
                .with_evidence(format!("Function: {}", path)),
            );
        }

        // Special cases for common patterns
        if lower_path.contains("env::var") || lower_path.contains("std::env") {
            factors.push(ScoreFactor::new(
                "rhs_env_var",
                FactorCategory::RightHandSide,
                15,
                "Value comes from environment variable",
            ));
        }

        factors
    }

    /// Determine if the comparison looks like routing/dispatch
    pub fn looks_like_routing(&self, variable: &ComparisonSide) -> bool {
        let name = match variable {
            ComparisonSide::Variable { name, .. } => Some(name.as_str()),
            ComparisonSide::FieldAccess { field, .. } => Some(field.as_str()),
            _ => None,
        };

        if let Some(n) = name {
            // Use SIMD-accelerated pattern matcher
            prebuilt::command_like().is_match(n)
        } else {
            false
        }
    }

    /// Determine if the comparison looks like auth checking
    pub fn looks_like_auth(&self, variable: &ComparisonSide) -> bool {
        let name = match variable {
            ComparisonSide::Variable { name, .. } => Some(name.as_str()),
            ComparisonSide::FieldAccess { field, .. } => Some(field.as_str()),
            _ => None,
        };

        if let Some(n) = name {
            // Use SIMD-accelerated pattern matcher
            prebuilt::auth_like().is_match(n)
        } else {
            false
        }
    }
}

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

    #[test]
    fn test_command_variable_reduces_score() {
        let analyzer = RhsAnalyzer::new(RhsConfig::default());
        let var = ComparisonSide::Variable {
            name: "command".into(),
            source: None,
        };
        let factors = analyzer.analyze(&var);
        let total: i32 = factors.iter().map(|f| f.contribution).sum();
        assert!(total < 0, "command variable should reduce score");
    }

    #[test]
    fn test_token_variable_increases_score() {
        let analyzer = RhsAnalyzer::new(RhsConfig::default());
        let var = ComparisonSide::Variable {
            name: "auth_token".into(),
            source: None,
        };
        let factors = analyzer.analyze(&var);
        let total: i32 = factors.iter().map(|f| f.contribution).sum();
        assert!(total > 0, "auth_token variable should increase score");
    }

    #[test]
    fn test_header_method_increases_score() {
        let analyzer = RhsAnalyzer::new(RhsConfig::default());
        let var = ComparisonSide::MethodCall {
            receiver: "request".into(),
            method: "header".into(),
            args: vec!["Authorization".into()],
        };
        let factors = analyzer.analyze(&var);
        let total: i32 = factors.iter().map(|f| f.contribution).sum();
        assert!(total > 0, "header() call should increase score");
    }
}