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
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
//! GraphQL injection detection module (GQL-006).
//!
//! Detects SQL, `NoSQL`, and command injection vulnerabilities via GraphQL
//! arguments and variables. GraphQL input is often passed directly to
//! backend databases or shell commands without proper sanitization.
//!
//! # Attack Description
//!
//! Attackers inject malicious payloads into GraphQL query arguments:
//! ```graphql
//! query {
//!   user(id: "1' OR '1'='1") {
//!     name
//!   }
//! }
//! ```
//!
//! # Detection Method
//!
//! 1. Send common SQL/NoSQL/command injection payloads in arguments
//! 2. Analyze error responses for backend system leakage
//! 3. Report if injection appears possible
//!
//! # Remediation
//!
//! - Use parameterized queries / prepared statements
//! - Validate and sanitize all GraphQL inputs
//! - Implement input type constraints (scalars, enums)

use anyhow::Result;
use scanclient::reqwest::header::CONTENT_TYPE;
use scanclient::ScanClient;

use crate::context::ScanContext;
use crate::schema::SchemaGraph;
use secfinding::{Evidence, Finding, FindingKind, Severity};
use serde_json::json;
use tracing::{debug, trace};

/// SQL injection payloads to test via GraphQL arguments.
pub const SQL_PAYLOADS: &[&str] = &[
    "' OR '1'='1",
    "' AND 1=1--",
    "' AND 1=2--",
    "1' OR '1'='1' --",
    "admin'--",
    "' UNION SELECT null,null--",
];

/// `NoSQL` injection payloads to test via GraphQL arguments.
const NOSQL_PAYLOADS: &[&str] = &[
    r#"{"$gt": ""}"#,
    r#"{"$ne": null}"#,
    r#"{"$exists": true}"#,
    r#"{"$regex": ".*"}"#,
];

/// Command injection payloads to test via GraphQL arguments.
pub const CMD_PAYLOADS: &[&str] = &["; id", "| id", "$(id)", "`id`"];

/// SQL error indicators in responses.
/// Generic indicators like "syntax error" are excluded to avoid false
/// positives from GraphQL parse errors.
pub const SQL_INDICATORS: &[&str] = &[
    "sql syntax",
    "mysql",
    "postgresql",
    "sqlite",
    "ora-",
    "sql server",
    "near \"\"",
    "you have an error in your sql",
];

/// GraphQL parse error indicators - responses matching these without DB-specific
/// keywords are treated as GraphQL-level errors, not backend injection evidence.
pub const GRAPHQL_PARSE_INDICATORS: &[&str] = &["expected", "unexpected", "parse error"];

/// `NoSQL` error indicators in responses.
pub const NOSQL_INDICATORS: &[&str] = &[
    "mongoerror",
    "e_query",
    "bson",
    "invalid bson",
    "cannot parse",
];

/// Command injection error indicators in responses.
pub const CMD_INDICATORS: &[&str] = &[
    "sh: ",
    "command not found",
    "syntax error near unexpected token",
    "bin/bash",
    "bin/sh",
    "permission denied",
];

/// Produce a SQL-injection-style payload of an arbitrary byte length.
///
/// Repeats the classic tautology `' OR '1'='1` to reach the requested length.
/// This simulates an attacker sending a long, syntactically valid SQL fragment
/// through a GraphQL string argument in order to probe for unsanitized
/// pass-through to a relational database.
///
/// # Attack vector
///
/// GraphQL resolvers often forward argument strings directly to SQL queries.
/// A payload that is long enough to bypass naive length checks but still
/// syntactically valid can reveal whether the backend performs proper
/// parameterization.
pub fn generate_injection_query(length: usize) -> String {
    let chunk = "' OR '1'='1";
    let mut payload = String::with_capacity(length);
    while payload.len() + chunk.len() <= length {
        payload.push_str(chunk);
    }
    let remaining = length.saturating_sub(payload.len());
    payload.push_str(&chunk[..remaining.min(chunk.len())]);
    payload.truncate(length);
    payload
}

/// Query templates to test injection across common argument patterns.
const INJECTION_TEMPLATES: &[&str] = &[
    r#"query InjectionTest {{ user(id: "{}") {{ name }} }}"#,
    r#"query InjectionTest {{ search(query: "{}") {{ results }} }}"#,
    r#"query InjectionTest {{ users(filter: "{}") {{ name }} }}"#,
    r#"query InjectionTest {{ items(query: "{}") {{ id }} }}"#,
    r#"query InjectionTest {{ user(email: "{}") {{ name }} }}"#,
];

/// Test for injection vulnerabilities via GraphQL arguments.
///
/// Sends common injection payloads in query arguments and analyzes
/// error responses for signs of backend system leakage.
///
/// # Arguments
///
/// * `client` - The HTTP client for making requests
/// * `url` - The target GraphQL endpoint URL
///
/// # Returns
///
/// Returns findings if injection vulnerabilities are detected.
///
/// # Errors
///
/// Returns an error if HTTP requests fail critically.
/// Run injection checks using schema-derived argument targets when available.
pub async fn test_with_context(client: &ScanClient, ctx: &ScanContext) -> Result<Vec<Finding>> {
    test_inner(client, ctx.url(), ctx.schema.as_ref()).await
}

/// Test for injection vulnerabilities via GraphQL arguments.
pub async fn test(client: &ScanClient, url: &str) -> Result<Vec<Finding>> {
    test_inner(client, url, None).await
}

async fn test_inner(
    client: &ScanClient,
    url: &str,
    schema: Option<&SchemaGraph>,
) -> Result<Vec<Finding>> {
    let mut findings = Vec::new();

    debug!("Testing GraphQL injection on {}", url);

    let templates: Vec<String> = if let Some(s) = schema {
        if s.injectable_args.is_empty() {
            INJECTION_TEMPLATES
                .iter()
                .map(|t| (*t).to_string())
                .collect()
        } else {
            s.injectable_args
                .iter()
                .map(|a| {
                    if a.is_mutation {
                        format!(
                            r#"mutation InjectionTest {{ {}({}: "{{}}") {{ __typename }} }}"#,
                            a.field, a.arg
                        )
                    } else {
                        format!(
                            r#"query InjectionTest {{ {}({}: "{{}}") {{ __typename }} }}"#,
                            a.field, a.arg
                        )
                    }
                })
                .collect()
        }
    } else {
        INJECTION_TEMPLATES
            .iter()
            .map(|t| (*t).to_string())
            .collect()
    };

    let template_refs: Vec<&str> = templates.iter().map(String::as_str).collect();

    // Test SQL injection payloads across multiple argument patterns
    'sql_loop: for template in &template_refs {
        for payload in SQL_PAYLOADS {
            match send_injection_test(client, url, payload, template).await? {
                InjectionResult::Vulnerable(category, evidence) => {
                    trace!("SQL injection indicator found with payload: {}", payload);
                    findings.push(create_finding(
                        url,
                        &format!("GraphQL {category} Injection Detected"),
                        &format!(
                            "The GraphQL endpoint appears vulnerable to {category} injection. \
                             A test payload in a query argument triggered a backend error response."
                        ),
                        Severity::Critical,
                        &format!(
                            "Use parameterized queries for all {category} operations. \
                             Validate and sanitize GraphQL inputs before passing them to backend systems."
                        ),
                        Some(&evidence),
                    )?);
                    break 'sql_loop; // One finding per category is sufficient
                }
                InjectionResult::Safe => {}
                InjectionResult::Error(e) => {
                    debug!("Injection test error for payload '{}': {}", payload, e);
                }
            }
        }
    }

    // Test NoSQL injection payloads across multiple argument patterns
    'nosql_loop: for template in &template_refs {
        for payload in NOSQL_PAYLOADS {
            match send_injection_test(client, url, payload, template).await? {
                InjectionResult::Vulnerable(category, evidence) => {
                    trace!("NoSQL injection indicator found with payload: {}", payload);
                    findings.push(create_finding(
                        url,
                        &format!("GraphQL {category} Injection Detected"),
                        &format!(
                            "The GraphQL endpoint appears vulnerable to {category} injection. \
                             A NoSQL payload in a query argument triggered a backend error response."
                        ),
                        Severity::High,
                        "Use parameterized queries for `NoSQL` operations. Validate JSON inputs strictly.",
                        Some(&evidence),
                    )?);
                    break 'nosql_loop;
                }
                InjectionResult::Safe => {}
                InjectionResult::Error(e) => {
                    debug!("NoSQL test error for payload '{}': {}", payload, e);
                }
            }
        }
    }

    // Test command injection payloads across multiple argument patterns
    'cmd_loop: for template in &template_refs {
        for payload in CMD_PAYLOADS {
            match send_injection_test(client, url, payload, template).await? {
                InjectionResult::Vulnerable(category, evidence) => {
                    trace!(
                        "Command injection indicator found with payload: {}",
                        payload
                    );
                    findings.push(create_finding(
                        url,
                        &format!("GraphQL {category} Injection Detected"),
                        &format!(
                            "The GraphQL endpoint appears vulnerable to {category} injection. \
                             A shell metacharacter payload triggered a backend error response."
                        ),
                        Severity::High,
                        "Never pass GraphQL arguments to shell commands. Use allow-lists and strict input validation.",
                        Some(&evidence),
                    )?);
                    break 'cmd_loop;
                }
                InjectionResult::Safe => {}
                InjectionResult::Error(e) => {
                    debug!("Command test error for payload '{}': {}", payload, e);
                }
            }
        }
    }

    debug!(
        "GraphQL injection test complete: {} findings",
        findings.len()
    );
    Ok(findings)
}

/// Outcome of a single injection probe against a GraphQL argument.
///
/// The scanner sends a malicious payload embedded in a query template and
/// classifies the server's response to determine whether the payload reached
/// a vulnerable backend system.
#[derive(Debug)]
pub enum InjectionResult {
    /// The response contained backend-specific error indicators, suggesting the
    /// payload was processed by a database or shell rather than rejected at the
    /// GraphQL layer.
    ///
    /// The first string is the injection category (`SQL`, `NoSQL`, or `Command`);
    /// the second string is the raw response body (or an excerpt) used as
    /// evidence.
    Vulnerable(String, String),
    /// The server did not leak any backend error indicators. This is returned
    /// when the response is clean, contains only GraphQL parse/validation
    /// errors, or returns successful data without backend leakage.
    Safe,
    /// The HTTP request or response parsing failed in a way that prevents a
    /// confident security conclusion.
    Error(String),
}

/// Distinguish GraphQL parse/validation errors from backend injection evidence.
///
/// Security heuristic: if the response contains generic GraphQL keywords such
/// as "expected", "unexpected", or "parse error" **and** lacks any
/// database-specific or shell-specific indicators, the error almost certainly
/// originated in the GraphQL parser/validator rather than a downstream system.
///
/// This reduces false positives when a malformed payload triggers a syntax
/// error before it ever reaches the backend database or command executor.
///
/// # When to rely on it
///
/// Call this before checking for `SQL_INDICATORS`, `NOSQL_INDICATORS`, or
/// `CMD_INDICATORS`. If this function returns `true`, the response should be
/// treated as `Safe` regardless of whether it also happens to contain
/// superficially suspicious strings.
pub fn is_likely_graphql_parse_error(body: &str) -> bool {
    let b = body.to_lowercase();
    let has_parse_indicator = GRAPHQL_PARSE_INDICATORS.iter().any(|&ind| b.contains(ind));
    let has_db_indicator = SQL_INDICATORS.iter().any(|&ind| b.contains(ind))
        || NOSQL_INDICATORS.iter().any(|&ind| b.contains(ind))
        || CMD_INDICATORS.iter().any(|&ind| b.contains(ind));
    has_parse_indicator && !has_db_indicator
}

/// Send a single injection payload embedded in a GraphQL query template.
///
/// The payload is JSON-escaped and inserted into the template, then sent as a
/// standard GraphQL POST request. The response body is analyzed for backend
/// error leakage.
///
/// # Returns
///
/// - [`InjectionResult::Vulnerable`] when the response contains database- or
///   shell-specific error keywords, indicating the payload likely reached a
///   vulnerable backend.
/// - [`InjectionResult::Safe`] when no backend indicators are present or when
///   the response is classified as a GraphQL-level parse error.
/// - [`InjectionResult::Error`] when the HTTP request itself fails.
pub async fn send_injection_test(
    client: &ScanClient,
    url: &str,
    payload: &str,
    template: &str,
) -> Result<InjectionResult> {
    let escaped = serde_json::to_string(payload)
        .unwrap_or_else(|_| format!("\"{}\"", payload.replace('"', "\\\"")));
    let query = template.replace("{}", &escaped);
    let body = json!({ "query": query });
    let request = client
        .request(scanclient::reqwest::Method::POST, url)
        .header(CONTENT_TYPE, "application/json")
        .body(body.to_string());

    match client.execute(request).await {
        Ok(resp) => {
            let body_text = resp.body_text().unwrap_or("").to_lowercase();

            // Skip GraphQL-level parse errors that don't indicate backend injection
            if is_likely_graphql_parse_error(&body_text) {
                return Ok(InjectionResult::Safe);
            }

            // Check for SQL indicators
            for indicator in SQL_INDICATORS {
                if body_text.contains(indicator) {
                    return Ok(InjectionResult::Vulnerable("SQL".to_string(), body_text));
                }
            }

            // Check for `NoSQL` indicators
            for indicator in NOSQL_INDICATORS {
                if body_text.contains(indicator) {
                    return Ok(InjectionResult::Vulnerable("NoSQL".to_string(), body_text));
                }
            }

            // Check for command injection indicators
            for indicator in CMD_INDICATORS {
                if body_text.contains(indicator) {
                    return Ok(InjectionResult::Vulnerable(
                        "Command".to_string(),
                        body_text,
                    ));
                }
            }

            Ok(InjectionResult::Safe)
        }
        Err(e) => Ok(InjectionResult::Error(e.to_string())),
    }
}

/// Build a [`Finding`] for an injection vulnerability discovered by this module.
///
/// The finding is tagged with:
/// - **GQL-ID / scanner**: `gqlprobe`
/// - **Kind**: [`FindingKind::Vulnerability`]
/// - **Tags**: `graphql`, `injection`
/// - **CWE**: `CWE-943` (Improper Neutralization of Special Elements in Data
///   Query Logic)
///
/// When `evidence_body` is provided, the first 1 000 characters of the response
/// are attached as raw evidence.
///
/// # Arguments
///
/// * `url` - The target GraphQL endpoint URL.
/// * `title` - Human-readable title (e.g. *GraphQL SQL Injection Detected*).
/// * `detail` - Description of the vulnerability and its security impact.
/// * `severity` - [`Severity::Critical`] for SQL injection, [`Severity::High`]
///   for `NoSQL` and command injection.
/// * `remediation` - Recommended fix.
/// * `evidence_body` - Optional raw response excerpt.
pub fn create_finding(
    url: &str,
    title: &str,
    detail: &str,
    severity: Severity,
    remediation: &str,
    evidence_body: Option<&str>,
) -> Result<Finding> {
    let mut builder = Finding::builder("gqlprobe", url, severity)
        .title(title)
        .detail(detail)
        .kind(FindingKind::Vulnerability)
        .tag("graphql")
        .tag("injection")
        .cwe("CWE-943") // Improper Neutralization of Special Elements in Data Query Logic
        .remediation(remediation);

    if let Some(body) = evidence_body {
        let excerpt = if body.chars().count() > 1000 {
            format!(
                "{}...[truncated]",
                body.chars().take(1000).collect::<String>()
            )
        } else {
            body.to_string()
        };
        builder = builder.evidence(Evidence::raw(excerpt));
    }

    Ok(builder.build()?)
}