website-vulnerability-scanner 0.2.0

Cross-platform defensive website security & configuration scanner with GUI and CLI reports.
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
use std::path::PathBuf;
use std::process::ExitCode;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;

use anyhow::Context;
use clap::Parser;

use website_vulnerability_scanner::advisories;
use website_vulnerability_scanner::application;
use website_vulnerability_scanner::checks::parse_header_pair;
use website_vulnerability_scanner::diff;
use website_vulnerability_scanner::fix_config::ServerKind;
#[cfg(feature = "gui")]
use website_vulnerability_scanner::gui;
use website_vulnerability_scanner::models::{
    FailThreshold, ReportAudience, ScanConfig, ScanProfile,
};
use website_vulnerability_scanner::report::{html, json, markdown, sarif, terminal};
use website_vulnerability_scanner::rules;
use website_vulnerability_scanner::storage::{self, ProjectConfig};

#[derive(Debug, Parser)]
#[command(
    name = "web-vuln-scanner",
    version,
    about = "Defensive website security & configuration scanner with GUI and CLI reports"
)]
struct Cli {
    /// Target URLs or domains (e.g. `<https://example.com>` or `example.com`)
    #[arg(value_name = "URL")]
    targets: Vec<String>,

    /// Launch native GPU GUI window (default when invoked with no arguments)
    #[arg(long)]
    gui: bool,

    /// Scan profile (web for HTML websites, api for REST/JSON APIs)
    #[arg(long, value_enum, default_value_t = ScanProfile::Web)]
    profile: ScanProfile,

    /// Report view tailored by audience (executive, developer, security)
    #[arg(long, value_enum, default_value_t = ReportAudience::Developer)]
    view: ReportAudience,

    /// Project name or path to scanner-project.json configuration file
    #[arg(long, value_name = "NAME_OR_PATH")]
    project: Option<String>,

    /// Save completed run to local project history (~/.config/web-vuln-scanner)
    #[arg(long)]
    save_run: bool,

    /// Path to custom JSON rules database (can be specified multiple times)
    #[arg(short = 'r', long = "rules", value_name = "PATH")]
    rules_files: Vec<PathBuf>,

    /// Path to OpenAPI 3.x / Swagger 2.0 JSON spec file or same-origin URL
    #[arg(long, value_name = "PATH_OR_URL")]
    openapi: Option<String>,

    /// Path to custom JSON client-library advisories pack
    #[arg(long, value_name = "PATH")]
    advisories: Option<PathBuf>,

    /// Custom request header sent strictly to target origin (e.g. "Cookie: sid=...")
    #[arg(short = 'H', long = "header", value_name = "NAME:VALUE")]
    auth_headers: Vec<String>,

    /// Auth context label stored in reports & baselines (e.g. "authenticated-user")
    #[arg(long, value_name = "LABEL")]
    auth_context: Option<String>,

    /// Compare results against a previous JSON report file
    #[arg(long, value_name = "PATH")]
    baseline: Option<PathBuf>,

    /// Exit with code 2 if new or worsened issues appear compared to --baseline
    #[arg(long)]
    fail_on_regression: bool,

    /// Print ready-to-paste hardening config snippet (nginx, caddy, or apache)
    #[arg(long, value_enum)]
    fix_config: Option<ServerKind>,

    /// File containing target URLs (one per line, # comments ignored)
    #[arg(short, long, value_name = "PATH")]
    file: Option<PathBuf>,

    /// Save standalone HTML report to file
    #[arg(long, value_name = "PATH")]
    html: Option<PathBuf>,

    /// Save JSON report to file
    #[arg(long, value_name = "PATH")]
    json: Option<PathBuf>,

    /// Save Markdown report to file
    #[arg(long, value_name = "PATH")]
    md: Option<PathBuf>,

    /// Save SARIF v2.1.0 report to file (for GitHub Code Scanning / IDE)
    #[arg(long, value_name = "PATH")]
    sarif: Option<PathBuf>,

    /// HTTP/TLS request timeout in seconds
    #[arg(long, default_value_t = 10)]
    timeout: u64,

    /// Max concurrent probe requests
    #[arg(long, default_value_t = 6)]
    concurrency: usize,

    /// Max same-origin pages to crawl per site (1 = only given URL)
    #[arg(long, default_value_t = 10)]
    max_pages: usize,

    /// Maximum HTTP request budget per target scan
    #[arg(long, default_value_t = 120)]
    max_requests: usize,

    /// Skip exposed metadata/file checks (/.git/HEAD, /.env, etc.)
    #[arg(long)]
    skip_paths: bool,

    /// Skip DNS CAA / SPF / DMARC checks
    #[arg(long)]
    skip_dns: bool,

    /// Skip active legacy TLS 1.0 / 1.1 handshake probe
    #[arg(long)]
    no_legacy_tls: bool,

    /// Skip anonymous parity probe when auth headers are set
    #[arg(long)]
    no_unauth_check: bool,

    /// Hide passed checks in terminal output
    #[arg(long)]
    hide_passes: bool,

    /// Disable colored terminal output
    #[arg(long)]
    no_color: bool,

    /// Exit with code 2 if any finding meets or exceeds this severity
    #[arg(long, value_enum)]
    fail_on: Option<FailThreshold>,
}

async fn run_cli(cli: Cli) -> anyhow::Result<ExitCode> {
    if cli.no_color {
        colored::control::set_override(false);
    }

    let mut project_cfg: Option<ProjectConfig> = None;
    let mut project_name = "default".to_string();
    if let Some(proj_arg) = &cli.project {
        let p = PathBuf::from(proj_arg);
        if proj_arg.ends_with(".json") || p.exists() {
            let loaded = ProjectConfig::load_from(&p)
                .with_context(|| format!("failed to load project file: {}", p.display()))?;
            project_name = loaded.name.clone();
            project_cfg = Some(loaded);
        } else {
            project_name = proj_arg.clone();
        }
    }

    let mut targets = cli.targets;
    if let Some(file_path) = &cli.file {
        let content = std::fs::read_to_string(file_path)
            .with_context(|| format!("failed to read targets file: {}", file_path.display()))?;
        for line in content.lines() {
            let trimmed = line.trim();
            if !trimmed.is_empty() && !trimmed.starts_with('#') {
                targets.push(trimmed.to_string());
            }
        }
    }
    if targets.is_empty() {
        if let Some(cfg) = &project_cfg {
            targets.extend(cfg.targets.clone());
        }
    }

    if targets.is_empty() {
        anyhow::bail!(
            "No targets specified. Pass a URL (e.g. `web-vuln-scanner https://example.com`), `--file targets.txt`, `--project scanner-project.json`, or `--gui`."
        );
    }

    let mut rule_paths = cli.rules_files.clone();
    if let Some(cfg) = &project_cfg {
        if let Some(rf) = &cfg.rules_file {
            let rp = PathBuf::from(rf);
            if !rule_paths.contains(&rp) {
                rule_paths.push(rp);
            }
        }
    }
    let custom_rules = if rule_paths.is_empty() {
        Vec::new()
    } else {
        rules::load_rules_from_paths(&rule_paths)
            .context("failed to load custom JSON rules database")?
    };

    let adv_path_opt = cli.advisories.clone().or_else(|| {
        project_cfg
            .as_ref()
            .and_then(|c| c.advisories_path.as_ref().map(PathBuf::from))
    });
    let custom_advisories = if let Some(ap) = adv_path_opt {
        advisories::load_advisories_pack(&ap)
            .context("failed to load custom JSON advisories pack")?
    } else {
        Vec::new()
    };

    let mut parsed_headers = Vec::with_capacity(cli.auth_headers.len());
    for raw_hdr in &cli.auth_headers {
        parsed_headers.push(parse_header_pair(raw_hdr)?);
    }

    let baseline_report =
        if let Some(base_path) = &cli.baseline {
            Some(diff::load_baseline(base_path).with_context(|| {
                format!("failed to load baseline JSON: {}", base_path.display())
            })?)
        } else {
            None
        };

    let auth_context = cli.auth_context.unwrap_or_else(|| {
        if let Some(cfg) = &project_cfg {
            cfg.auth_context.clone()
        } else if parsed_headers.is_empty() {
            "anonymous".to_string()
        } else {
            "custom-headers".to_string()
        }
    });

    let config = if let Some(cfg) = &project_cfg {
        let mut sc = cfg.to_scan_config(custom_rules, parsed_headers);
        sc.auth_context = auth_context;
        sc.custom_advisories = custom_advisories;
        if let Some(oa) = &cli.openapi {
            sc.openapi_path = Some(oa.clone());
        }
        if cli.max_requests != 120 {
            sc.max_requests = cli.max_requests.max(1);
        }
        if cli.skip_paths {
            sc.skip_paths = true;
        }
        if cli.skip_dns {
            sc.skip_dns = true;
        }
        if cli.no_legacy_tls {
            sc.check_legacy_tls = false;
        }
        if cli.no_unauth_check {
            sc.check_unauth_access = false;
        }
        sc
    } else {
        ScanConfig {
            timeout_secs: cli.timeout.max(1),
            concurrency: cli.concurrency.max(1),
            max_pages: cli.max_pages.max(1),
            max_requests: cli.max_requests.max(1),
            profile: cli.profile,
            skip_paths: cli.skip_paths,
            skip_dns: cli.skip_dns,
            auth_context,
            openapi_path: cli.openapi.clone(),
            custom_rules,
            custom_advisories,
            auth_headers: parsed_headers,
            check_legacy_tls: !cli.no_legacy_tls,
            check_unauth_access: !cli.no_unauth_check,
            ..ScanConfig::default()
        }
    };

    let cancel_flag = Arc::new(AtomicBool::new(false));
    let multi = application::run_multi_scan(&targets, &config, cancel_flag, None).await;

    let report_diff = baseline_report
        .as_ref()
        .map(|base| diff::compare_reports(base, &multi));

    terminal::print_terminal_report(
        &multi,
        !cli.hide_passes,
        report_diff.as_ref(),
        cli.fix_config,
        cli.view,
    );

    if cli.save_run {
        let data_dir = storage::default_data_dir();
        let rec = storage::save_run(&data_dir, &project_name, &multi)
            .context("failed to persist scan run")?;
        println!(
            "Saved run '{}' for project '{}' in {}",
            rec.run_id,
            rec.project,
            data_dir.display()
        );
    }

    if let Some(path) = &cli.html {
        let rendered = html::render_html_for_view(&multi, cli.view, report_diff.as_ref());
        std::fs::write(path, rendered)
            .with_context(|| format!("failed to write HTML report to {}", path.display()))?;
        println!("HTML report saved: {}", path.display());
    }

    if let Some(path) = &cli.json {
        let rendered = json::render_json(&multi)?;
        std::fs::write(path, rendered)
            .with_context(|| format!("failed to write JSON report to {}", path.display()))?;
        println!("JSON report saved: {}", path.display());
    }

    if let Some(path) = &cli.md {
        let rendered = markdown::render_markdown_for_view(&multi, cli.view, report_diff.as_ref());
        std::fs::write(path, rendered)
            .with_context(|| format!("failed to write Markdown report to {}", path.display()))?;
        println!("Markdown report saved: {}", path.display());
    }

    if let Some(path) = &cli.sarif {
        let rendered = sarif::render_sarif(&multi)?;
        std::fs::write(path, rendered)
            .with_context(|| format!("failed to write SARIF report to {}", path.display()))?;
        println!("SARIF report saved: {}", path.display());
    }

    if cli.fail_on_regression {
        if let Some(d) = &report_diff {
            if d.has_new_regressions() {
                return Ok(ExitCode::from(2));
            }
        }
    }

    if let Some(threshold) = cli.fail_on {
        let breached = multi
            .reports
            .iter()
            .flat_map(|r| r.findings.iter())
            .any(|f| threshold.matches(f.severity));
        if breached {
            return Ok(ExitCode::from(2));
        }
    }

    Ok(ExitCode::SUCCESS)
}

#[cfg(feature = "gui")]
fn launch_native_gui(initial: Option<String>) -> ExitCode {
    if let Err(err) = gui::launch_gui(initial) {
        eprintln!("{err}");
        return ExitCode::FAILURE;
    }
    ExitCode::SUCCESS
}

#[cfg(not(feature = "gui"))]
fn launch_native_gui(_initial: Option<String>) -> ExitCode {
    eprintln!(
        "Error: This binary was compiled without GUI support (headless `--no-default-features` build). Pass a target URL or `--help`."
    );
    ExitCode::FAILURE
}

fn main() -> ExitCode {
    #[cfg(windows)]
    {
        let _ = colored::control::set_virtual_terminal(true);
    }

    let args: Vec<std::ffi::OsString> = std::env::args_os().collect();
    if args.len() <= 1 {
        return launch_native_gui(None);
    }

    let cli = Cli::parse();
    if cli.gui {
        let initial = if cli.targets.is_empty() {
            None
        } else {
            Some(cli.targets.join(", "))
        };
        return launch_native_gui(initial);
    }

    let rt = tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
        .expect("Failed to initialize Tokio runtime");

    match rt.block_on(run_cli(cli)) {
        Ok(code) => code,
        Err(err) => {
            eprintln!("Error: {err:#}");
            ExitCode::FAILURE
        }
    }
}