gqlprobe 1.0.0

Fast GraphQL security scanner - schema-aware introspection, injection, DoS, CSRF, auth bypass, SARIF
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
//! Scanner orchestrator for GraphQL security testing.

use std::collections::HashSet;
use std::sync::Arc;
use std::time::Duration;

use anyhow::Result;
use hickory_resolver::TokioResolver;
use scanclient::{HttpConfig, ScanClient};
use secfinding::Finding;
use tokio::sync::Semaphore;
use tokio::time::timeout;
use tracing::{debug, error, info, warn};

use crate::baseline;
use crate::context::{ModuleRun, ScanContext};
use crate::modules::attack::{default_registry, registry_for_ids, AttackModule};
use crate::schema;

/// Configuration for scanning operations.
#[derive(Debug, Clone)]
pub struct ScanConfig {
    /// Maximum time for the entire scan.
    pub global_timeout_secs: u64,
    /// Maximum time for any single module.
    pub module_timeout_secs: u64,
    /// Maximum number of concurrent modules.
    pub max_concurrency: usize,
    /// HTTP client configuration.
    pub http_config: HttpConfig,
    /// When true, skip schema discovery (faster, generic probes only).
    pub skip_schema_discovery: bool,
}

impl Default for ScanConfig {
    fn default() -> Self {
        Self {
            global_timeout_secs: 300,
            module_timeout_secs: 60,
            max_concurrency: 5,
            http_config: HttpConfig::default(),
            skip_schema_discovery: false,
        }
    }
}

impl ScanConfig {
    /// Validate the configuration.
    ///
    /// # Errors
    /// Returns an error if limits are out of range.
    pub fn validate(&self) -> Result<()> {
        if self.max_concurrency == 0 {
            anyhow::bail!("max_concurrency must be greater than 0. Fix: set max_concurrency between 1 and 256");
        }
        if self.max_concurrency > 256 {
            anyhow::bail!(
                "max_concurrency must be at most 256. Fix: set max_concurrency between 1 and 256"
            );
        }
        // module_timeout_secs == 0 disables per-module timeouts (run until global deadline).
        if self.global_timeout_secs == 0 {
            anyhow::bail!("global_timeout_secs must be greater than 0. Fix: set global_timeout_secs to a positive number of seconds");
        }
        Ok(())
    }
}

/// GraphQL security scanner.
pub struct Scanner {
    client: ScanClient,
    target: String,
    config: ScanConfig,
    modules: Vec<Arc<dyn AttackModule>>,
}

impl Scanner {
    /// All built-in module IDs in execution order.
    pub fn all_module_ids() -> &'static [&'static str] {
        &[
            "GQL-001", "GQL-002", "GQL-003", "GQL-004", "GQL-005", "GQL-006", "GQL-007", "GQL-008",
            "GQL-009", "GQL-010", "GQL-011", "GQL-012", "GQL-013", "GQL-014",
        ]
    }

    /// Human-readable module catalog for `--list-modules`.
    pub fn module_catalog() -> &'static [(&'static str, &'static str)] {
        &[
            ("GQL-001", "Introspection enabled"),
            ("GQL-002", "Query depth DoS"),
            ("GQL-003", "Batching abuse"),
            ("GQL-004", "Field suggestion enumeration"),
            ("GQL-005", "Directive abuse"),
            ("GQL-006", "GraphQL injection"),
            ("GQL-007", "CSRF"),
            ("GQL-008", "Subscription abuse"),
            ("GQL-009", "Information disclosure"),
            ("GQL-010", "Authentication bypass"),
            ("GQL-011", "Alias abuse"),
            ("GQL-012", "Schema permission audit"),
            ("GQL-013", "IDOR / BOLA probe (schema-aware)"),
            ("GQL-014", "Rate-limit burst probe"),
        ]
    }

    /// Create a new scanner for the given target URL.
    ///
    /// # Errors
    /// Returns an error if the HTTP client cannot be created.
    pub fn new(target: impl Into<String>) -> Result<Self> {
        Self::with_config(target, ScanConfig::default())
    }

    /// Create a scanner with a custom configuration.
    ///
    /// # Errors
    /// Returns an error if the HTTP client cannot be created or if the
    /// configuration is invalid.
    pub fn with_config(target: impl Into<String>, config: ScanConfig) -> Result<Self> {
        config.validate()?;
        let target = target.into();
        let resolver = Arc::new(TokioResolver::builder_tokio()?.build());
        let client = ScanClient::new(config.http_config.clone(), resolver)?;

        Ok(Self {
            client,
            target,
            config,
            modules: default_registry(),
        })
    }

    /// Run all detection modules and return aggregated findings.
    pub async fn scan(&self) -> Result<Vec<Finding>> {
        info!("Starting GraphQL security scan for {}", self.target);

        let setup_timeout = Duration::from_secs(self.config.module_timeout_secs)
            .min(Duration::from_secs(self.config.global_timeout_secs));

        let (baseline, schema) = if self.config.skip_schema_discovery {
            let b =
                match timeout(setup_timeout, baseline::capture(&self.client, &self.target)).await {
                    Ok(Ok(b)) => b,
                    Ok(Err(e)) => {
                        warn!("Baseline capture failed: {}", e);
                        baseline::EndpointBaseline::default()
                    }
                    Err(_) => {
                        warn!(
                            "Baseline capture timed out after {}s",
                            setup_timeout.as_secs()
                        );
                        baseline::EndpointBaseline::default()
                    }
                };
            (b, None)
        } else {
            let b = timeout(setup_timeout, baseline::capture(&self.client, &self.target));
            let s = timeout(setup_timeout, schema::discover(&self.client, &self.target));
            let (baseline_result, schema_result) = tokio::join!(b, s);

            let baseline = match baseline_result {
                Ok(Ok(b)) => b,
                Ok(Err(e)) => {
                    warn!("Baseline capture failed: {}", e);
                    baseline::EndpointBaseline::default()
                }
                Err(_) => {
                    warn!(
                        "Baseline capture timed out after {}s",
                        setup_timeout.as_secs()
                    );
                    baseline::EndpointBaseline::default()
                }
            };

            let schema = match schema_result {
                Ok(Ok(s)) => s,
                Ok(Err(e)) => {
                    warn!("Schema discovery failed: {}", e);
                    None
                }
                Err(_) => {
                    warn!(
                        "Schema discovery timed out after {}s",
                        setup_timeout.as_secs()
                    );
                    None
                }
            };
            (baseline, schema)
        };

        let ctx = ScanContext::new(&self.target, schema, baseline);

        let semaphore = Arc::new(Semaphore::new(self.config.max_concurrency));
        let mut handles = Vec::new();

        for module in &self.modules {
            let permit = semaphore.clone().acquire_owned().await?;
            let module_id = module.id().to_string();
            let module_name = module.name().to_string();
            let client = self.client.clone();
            let ctx = ctx.clone();
            let module = Arc::clone(module);
            let timeout_duration = if self.config.module_timeout_secs == 0 {
                Duration::from_secs(self.config.global_timeout_secs)
            } else {
                Duration::from_secs(self.config.module_timeout_secs)
            };

            let handle = tokio::spawn(async move {
                let _permit = permit;
                debug!("Running module {}: {}", module_id, module_name);

                let run = ModuleRun {
                    client: &client,
                    ctx: &ctx,
                };

                let result = timeout(timeout_duration, module.detect(&run)).await;

                match result {
                    Ok(Ok(findings)) => {
                        debug!(
                            "Module {} completed with {} findings",
                            module_id,
                            findings.len()
                        );
                        findings
                    }
                    Ok(Err(e)) => {
                        error!("Module {} failed: {}", module_id, e);
                        Vec::new()
                    }
                    Err(_) => {
                        error!(
                            "Module {} timed out after {}s",
                            module_id,
                            timeout_duration.as_secs()
                        );
                        Vec::new()
                    }
                }
            });

            handles.push(handle);
        }

        let global_timeout = Duration::from_secs(self.config.global_timeout_secs)
            .min(Duration::from_secs(u64::from(u32::MAX)));
        let deadline = tokio::time::Instant::now() + global_timeout;
        let mut all_findings = Vec::new();
        let mut timed_out = false;

        while !handles.is_empty() {
            let mut i = 0;
            while i < handles.len() {
                if handles[i].is_finished() {
                    let handle = handles.remove(i);
                    match handle.await {
                        Ok(findings) => all_findings.extend(findings),
                        Err(e) => error!("Task join error: {}", e),
                    }
                } else {
                    i += 1;
                }
            }

            if tokio::time::Instant::now() >= deadline {
                for h in handles {
                    h.abort();
                }
                timed_out = true;
                break;
            }

            if !handles.is_empty() {
                tokio::time::sleep(Duration::from_millis(50)).await;
            }
        }

        if timed_out {
            warn!(
                "Global scan timeout exceeded ({}s); returning partial findings",
                self.config.global_timeout_secs
            );
        }

        let deduped = Self::deduplicate_findings(all_findings);
        info!("Scan complete: {} unique findings", deduped.len());
        Ok(deduped)
    }

    /// Deduplicate findings by `(title, target)` and sort by severity descending.
    pub fn deduplicate_findings(findings: Vec<Finding>) -> Vec<Finding> {
        let mut seen = HashSet::with_capacity(findings.len());
        let mut unique = Vec::with_capacity(findings.len());

        for finding in findings {
            let key = (finding.title().to_string(), finding.target().to_string());
            if seen.insert(key) {
                unique.push(finding);
            }
        }

        unique.sort_by_key(|a| std::cmp::Reverse(a.severity()));
        unique
    }

    /// Return the target URL.
    pub fn target(&self) -> &str {
        &self.target
    }

    /// Return the scan configuration.
    pub fn config(&self) -> &ScanConfig {
        &self.config
    }

    /// Return the number of registered detection modules.
    pub fn module_count(&self) -> usize {
        self.modules.len()
    }

    /// Return the module IDs.
    pub fn module_ids(&self) -> Vec<&'static str> {
        self.modules.iter().map(|m| m.id()).collect()
    }
}

/// Builder for configuring a [`Scanner`].
#[derive(Default)]
pub struct ScannerBuilder {
    target: Option<String>,
    config: ScanConfig,
    modules: Option<Vec<Arc<dyn AttackModule>>>,
}

impl std::fmt::Debug for ScannerBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ScannerBuilder")
            .field("target", &self.target)
            .field("config", &self.config)
            .field("modules", &self.modules.as_ref().map(|m| m.len()))
            .finish()
    }
}

impl ScannerBuilder {
    /// Create a new scanner builder.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the target URL.
    #[must_use]
    pub fn target(mut self, target: impl Into<String>) -> Self {
        self.target = Some(target.into());
        self
    }

    /// Set the global timeout in seconds.
    #[must_use]
    pub fn global_timeout(mut self, secs: u64) -> Self {
        self.config.global_timeout_secs = secs;
        self
    }

    /// Set the per-module timeout in seconds.
    #[must_use]
    pub fn module_timeout(mut self, secs: u64) -> Self {
        self.config.module_timeout_secs = secs;
        self
    }

    /// Set the maximum concurrency.
    #[must_use]
    pub fn max_concurrency(mut self, max: usize) -> Self {
        self.config.max_concurrency = max;
        self
    }

    /// Set HTTP configuration.
    #[must_use]
    pub fn http_config(mut self, config: HttpConfig) -> Self {
        self.config.http_config = config;
        self
    }

    /// Skip introspection-based schema discovery.
    #[must_use]
    pub fn skip_schema_discovery(mut self, skip: bool) -> Self {
        self.config.skip_schema_discovery = skip;
        self
    }

    /// Select specific modules by ID (e.g. `["GQL-001", "GQL-002"]`).
    #[must_use]
    pub fn modules(mut self, ids: &[&str]) -> Self {
        self.modules = Some(registry_for_ids(ids));
        self
    }

    /// Build the scanner.
    pub fn build(self) -> Result<Scanner> {
        self.config.validate()?;
        let target = self
            .target
            .ok_or_else(|| anyhow::anyhow!("target is required"))?;
        let mut scanner = Scanner::with_config(target, self.config)?;
        if let Some(modules) = self.modules {
            scanner.modules = modules;
        }
        Ok(scanner)
    }
}