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
//! Template system for CERT-X-GEN
//!
//! Provides abstractions for multi-language template support.
use crate::error::{Error, Result};
use crate::types::{Context, Finding, Protocol, Target, TemplateMetadata};
use async_trait::async_trait;
use std::path::Path;
/// A discovered file that could not be loaded, or is a helper rather than a template.
#[derive(Debug)]
pub struct TemplateLoadIssue {
/// File or directory inspected during discovery.
pub path: std::path::PathBuf,
/// Load failure; `None` identifies a skipped non-template file.
pub error: Option<String>,
}
/// Directory discovery results, including files that were not loaded.
#[derive(Default)]
#[allow(missing_debug_implementations)]
pub struct TemplateLoadReport {
/// Successfully loaded templates.
pub templates: Vec<Box<dyn Template>>,
/// Load failures and skipped helper files.
pub issues: Vec<TemplateLoadIssue>,
}
impl TemplateLoadReport {
/// Combine discovery results from another directory.
pub fn append(&mut self, mut other: Self) {
self.templates.append(&mut other.templates);
self.issues.append(&mut other.issues);
}
}
/// Minimum wall-clock budget for [`Template::prepare`], in seconds.
///
/// A first build can download and compile dependencies (a gRPC Go template
/// takes ~30s on a cold Go cache), which says nothing about the target, so it
/// is not held to the probe's own `--timeout`.
pub const TEMPLATE_BUILD_TIMEOUT_FLOOR_SECS: u64 = 300;
/// Template trait that all templates must implement
#[async_trait]
pub trait Template: Send + Sync {
/// Whether this engine accounts for all outbound target requests. Subprocess
/// engines cannot observe arbitrary template networking and default to unknown.
fn measures_network_requests(&self) -> bool {
false
}
/// Whether this template needs the authenticated JS probe engine.
fn is_js_probe(&self) -> bool {
false
}
/// Get template metadata
fn metadata(&self) -> &TemplateMetadata;
/// Execute the template against a target
async fn execute(&self, target: &Target, context: &Context) -> Result<Vec<Finding>>;
/// Execute and additionally return whatever execution status the template
/// declared for itself.
///
/// Additive by construction: the default implementation delegates to
/// [`Template::execute`] and declares nothing, so every existing `Template`
/// impl keeps compiling and behaving identically. Engines that understand
/// the probe contract override this to surface "ran but refuted".
async fn execute_with_status(
&self,
target: &Target,
context: &Context,
) -> Result<(Vec<Finding>, crate::engine::common::TemplateReport)> {
let findings = self.execute(target, context).await?;
Ok((findings, crate::engine::common::TemplateReport::default()))
}
/// Build whatever the template needs before it can run: compile it, fetch
/// its dependencies.
///
/// The executor calls this OUTSIDE the per-template execution timeout,
/// under its own build budget ([`TEMPLATE_BUILD_TIMEOUT_FLOOR_SECS`] or the
/// execution timeout, whichever is larger), so a cold first build -- a Go
/// template downloading and compiling its modules -- is not reported as the
/// probe timing out. Additive: the default does nothing, and an engine that
/// does not override it still builds lazily inside `execute`.
// @comment -- "optional pre-execution build phase, run by the executor outside the probe timeout under a separate build budget"
async fn prepare(&self) -> Result<()> {
Ok(())
}
/// Validate the template
fn validate(&self) -> Result<()> {
Ok(())
}
/// Get supported protocols
fn supported_protocols(&self) -> Vec<Protocol> {
vec![Protocol::Http, Protocol::Https]
}
/// Get template name
fn name(&self) -> &str {
&self.metadata().name
}
/// Get template ID
fn id(&self) -> &str {
&self.metadata().id
}
}
/// Template engine trait
#[async_trait]
pub trait TemplateEngine: Send + Sync {
/// Load a template from file
async fn load_template(&self, path: &Path) -> Result<Box<dyn Template>>;
/// Validate a template
async fn validate_template(&self, template: &dyn Template) -> Result<()>;
/// Execute a template
async fn execute_template(
&self,
template: &dyn Template,
target: &Target,
context: &Context,
) -> Result<Vec<Finding>>;
/// Get supported protocols
fn supported_protocols(&self) -> Vec<Protocol>;
/// Get engine name
fn name(&self) -> &str;
/// Check if engine supports a file
fn supports_file(&self, path: &Path) -> bool;
}
/// Template loader for managing multiple template engines
#[allow(missing_debug_implementations)]
pub struct TemplateLoader {
engines: Vec<Box<dyn TemplateEngine>>,
}
impl TemplateLoader {
/// Create a new template loader
pub fn new() -> Self {
Self {
engines: Vec::new(),
}
}
/// Register a template engine
pub fn register_engine(&mut self, engine: Box<dyn TemplateEngine>) {
self.engines.push(engine);
}
/// Load a template from file
pub async fn load_template(&self, path: &Path) -> Result<Box<dyn Template>> {
for engine in &self.engines {
if engine.supports_file(path) {
let template = engine.load_template(path).await?;
engine.validate_template(template.as_ref()).await?;
return Ok(template);
}
}
Err(Error::TemplateNotFound(path.display().to_string()))
}
/// Check if a file has a valid template extension
fn is_valid_template_file(path: &Path) -> bool {
if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
matches!(
ext,
"yaml" | "yml" | // YAML templates
"py" | // Python
"js" | // JavaScript
"rs" | // Rust
"c" | // C
"cpp" | "cc" | "cxx" | // C++
"java" | // Java
"go" | // Go
"rb" | // Ruby
"pl" | // Perl
"php" | // PHP
"sh" | "bash" // Shell
)
} else {
false
}
}
/// Recognise template identity metadata without executing the file. Code
/// helpers with ordinary tag variables are not template declarations.
fn has_template_metadata(path: &Path) -> Result<bool> {
let content = std::fs::read_to_string(path)?;
if matches!(
path.extension().and_then(|e| e.to_str()),
Some("yaml" | "yml")
) {
return match serde_yaml::from_str::<serde_yaml::Value>(&content) {
Ok(value) => Ok(value
.as_mapping()
.is_some_and(|map| map.contains_key("id") || map.contains_key("name"))),
// A malformed candidate must be reported as a load error, not
// silently reclassified as a helper.
Err(e) => Err(e.into()),
};
}
let metadata = crate::engine::common::parse_metadata_from_comments(&content);
Ok(metadata.id.is_some() || metadata.name.is_some())
}
/// Load all templates from a directory
pub fn load_templates_from_dir<'a>(
&'a self,
dir: &'a Path,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<Vec<Box<dyn Template>>>> + 'a>>
{
Box::pin(async move { Ok(self.discover_templates(dir).await?.templates) })
}
/// Discover templates and retain every load failure and skipped helper.
pub fn discover_templates<'a>(
&'a self,
dir: &'a Path,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<TemplateLoadReport>> + 'a>> {
Box::pin(async move {
let mut report = TemplateLoadReport::default();
if !dir.exists() {
return Err(Error::FileNotFound(dir.to_path_buf()));
}
let entries = std::fs::read_dir(dir)
.map_err(|e| Error::config(format!("Failed to read template directory: {}", e)))?;
let mut entries = entries.collect::<std::io::Result<Vec<_>>>()?;
entries.sort_by_key(|entry| entry.path());
for entry in entries {
let path = entry.path();
if path.is_file() {
// Only attempt to load files with valid template extensions
if !Self::is_valid_template_file(&path) {
tracing::trace!("Skipping non-template file: {}", path.display());
continue;
}
let loaded = match Self::has_template_metadata(&path) {
Ok(true) => self.load_template(&path).await.map(Some),
Ok(false) => Ok(None),
Err(e) => Err(e),
};
match loaded {
Ok(Some(template)) => report.templates.push(template),
Ok(None) => report.issues.push(TemplateLoadIssue { path, error: None }),
Err(e) => {
tracing::warn!("Failed to load template {}: {}", path.display(), e);
report.issues.push(TemplateLoadIssue {
path,
error: Some(e.to_string()),
});
}
}
} else if path.is_dir() {
// Skip build artifact directories, disabled templates, and skeleton templates
if let Some(dir_name) = path.file_name().and_then(|n| n.to_str()) {
if matches!(
dir_name,
"target"
| "node_modules"
| ".git"
| "__pycache__"
| "_disabled"
| "skeleton"
) {
tracing::trace!("Skipping excluded directory: {}", path.display());
continue;
}
}
// Recursively load templates from subdirectories
match self.discover_templates(&path).await {
Ok(sub_report) => report.append(sub_report),
Err(e) => {
tracing::warn!(
"Failed to load templates from {}: {}",
path.display(),
e
);
report.issues.push(TemplateLoadIssue {
path,
error: Some(e.to_string()),
});
}
}
}
}
Ok(report)
})
}
/// Get all registered engines
pub fn engines(&self) -> &[Box<dyn TemplateEngine>] {
&self.engines
}
}
impl Default for TemplateLoader {
fn default() -> Self {
Self::new()
}
}
/// Template filter for selecting templates
#[derive(Debug, Clone, Default)]
pub struct TemplateFilter {
/// Filter by template IDs
pub ids: Vec<String>,
/// Filter by tags
pub tags: Vec<String>,
/// Filter by severity
pub severities: Vec<crate::types::Severity>,
/// Filter by language
pub languages: Vec<crate::types::TemplateLanguage>,
/// Exclude template IDs
pub exclude_ids: Vec<String>,
/// Filter by batch group (e.g. "auth-context", "endpoint-params")
pub batch_group: Option<String>,
}
impl TemplateFilter {
/// Create a new empty filter
pub fn new() -> Self {
Self::default()
}
/// Check if a template matches the filter
pub fn matches(&self, template: &dyn Template) -> bool {
let metadata = template.metadata();
// Check ID filter (supports both template ID and file path)
if !self.ids.is_empty() {
let matches_id = self.ids.iter().any(|filter_id| {
// Exact ID match (case-insensitive)
if metadata.id.eq_ignore_ascii_case(filter_id) {
return true;
}
// Check if the file path ends with the filter (for path-based matching)
let file_path_str = metadata.file_path.to_string_lossy();
if file_path_str.ends_with(filter_id) {
return true;
}
// Check if filter is a full or partial path that matches
// Normalize both paths for comparison
let normalized_filter = filter_id.replace('\\', "/");
let normalized_path = file_path_str.replace('\\', "/");
if normalized_path.ends_with(&normalized_filter) {
return true;
}
// Check if the file name (without extension) matches the filter
if let Some(file_name) = metadata.file_path.file_stem() {
if file_name.to_string_lossy().eq_ignore_ascii_case(filter_id) {
return true;
}
}
false
});
if !matches_id {
return false;
}
}
// Check exclusion (supports wildcards)
for exclude_pattern in &self.exclude_ids {
if metadata.id.contains(exclude_pattern) || exclude_pattern.contains(&metadata.id) {
return false;
}
// Check file path for exclusion
let file_path_str = metadata.file_path.to_string_lossy();
if file_path_str.contains(exclude_pattern) {
return false;
}
}
// Check tags
if !self.tags.is_empty() {
let has_matching_tag = self.tags.iter().any(|tag| metadata.tags.contains(tag));
if !has_matching_tag {
return false;
}
}
// Check severity
if !self.severities.is_empty() && !self.severities.contains(&metadata.severity) {
return false;
}
// Check language
if !self.languages.is_empty() && !self.languages.contains(&metadata.language) {
return false;
}
// Check batch group
if let Some(ref bg) = self.batch_group {
let template_bg = metadata.batch_group.as_deref().unwrap_or("");
if !template_bg.eq_ignore_ascii_case(bg) {
return false;
}
}
true
}
/// Filter a list of templates
pub fn filter<'a>(&self, templates: &'a [Box<dyn Template>]) -> Vec<&'a Box<dyn Template>> {
templates
.iter()
.filter(|t| self.matches(t.as_ref()))
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::{AuthorInfo, Severity, TemplateLanguage};
use chrono::Utc;
use std::path::PathBuf;
struct MockTemplate {
metadata: TemplateMetadata,
}
#[async_trait]
impl Template for MockTemplate {
fn metadata(&self) -> &TemplateMetadata {
&self.metadata
}
async fn execute(&self, _target: &Target, _context: &Context) -> Result<Vec<Finding>> {
Ok(Vec::new())
}
}
fn create_test_template(id: &str, tags: Vec<String>, severity: Severity) -> Box<dyn Template> {
Box::new(MockTemplate {
metadata: TemplateMetadata {
id: id.to_string(),
name: format!("Test Template {}", id),
author: AuthorInfo {
name: "Test Author".to_string(),
email: None,
github: None,
},
severity,
description: "Test template".to_string(),
cve_ids: Vec::new(),
cwe_ids: Vec::new(),
cvss_score: None,
tags,
language: TemplateLanguage::Yaml,
file_path: PathBuf::from("test.yaml"),
created: Utc::now(),
updated: Utc::now(),
version: "1.0".to_string(),
confidence: None,
context_vars: Vec::new(),
vuln_class: None,
hypothesis_tags: Vec::new(),
batch_group: None,
auto_probe: false,
allow_nonzero_exit: false,
oracles: Vec::new(),
target_kinds: Vec::new(),
},
})
}
#[test]
fn test_template_filter() {
let templates = vec![
create_test_template("CVE-2024-1", vec!["rce".to_string()], Severity::Critical),
create_test_template("CVE-2024-2", vec!["sqli".to_string()], Severity::High),
create_test_template("CVE-2024-3", vec!["xss".to_string()], Severity::Medium),
];
let mut filter = TemplateFilter::new();
filter.tags.push("rce".to_string());
let filtered = filter.filter(&templates);
assert_eq!(filtered.len(), 1);
assert_eq!(filtered[0].id(), "CVE-2024-1");
}
#[test]
fn test_template_filter_severity() {
let templates = vec![
create_test_template("CVE-2024-1", Vec::new(), Severity::Critical),
create_test_template("CVE-2024-2", Vec::new(), Severity::High),
create_test_template("CVE-2024-3", Vec::new(), Severity::Medium),
];
let mut filter = TemplateFilter::new();
filter.severities.push(Severity::Critical);
filter.severities.push(Severity::High);
let filtered = filter.filter(&templates);
assert_eq!(filtered.len(), 2);
}
#[test]
fn test_template_filter_exclusion() {
let templates = vec![
create_test_template("CVE-2024-1", Vec::new(), Severity::Critical),
create_test_template("CVE-2024-2", Vec::new(), Severity::High),
];
let mut filter = TemplateFilter::new();
filter.exclude_ids.push("CVE-2024-1".to_string());
let filtered = filter.filter(&templates);
assert_eq!(filtered.len(), 1);
assert_eq!(filtered[0].id(), "CVE-2024-2");
}
}