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
//! CSRF detection module (GQL-007).
//!
//! Detects cross-site request forgery vulnerabilities in GraphQL endpoints.
//! GraphQL endpoints that accept GET requests or don't enforce Content-Type
//! are vulnerable to CSRF attacks.
//!
//! # Attack Description
//!
//! 1. GET-based CSRF: `<img src="https://api.example.com/graphql?query=mutation{...}">`
//! 2. Content-Type bypass: Send POST with `text/plain` instead of `application/json`
//! 3. Missing anti-CSRF tokens allow forged requests from attacker sites
//!
//! # Detection Method
//!
//! 1. Send GET request with query parameter
//! 2. Send POST with non-JSON Content-Type
//! 3. Check for missing Origin/Referer validation
//!
//! # Remediation
//!
//! - Reject GET requests for state-changing operations
//! - Strictly enforce `Content-Type: application/json`
//! - Implement CSRF tokens or `SameSite` cookie policies
//! - Validate Origin/Referer headers

use anyhow::Result;

use scanclient::reqwest::header::{CONTENT_TYPE, ORIGIN, REFERER};
use scanclient::ScanClient;
use secfinding::{Finding, FindingKind, Severity};
use serde_json::json;
use tracing::{debug, trace};

use crate::context::ScanContext;

/// Simple probe query for CSRF tests.
pub const PROBE_QUERY: &str = "{ __typename }";

/// Sensitive mutations that should not be accepted via GET or without proper CSRF protection.
pub const SENSITIVE_MUTATIONS: &[&str] = &[
    "deleteUser",
    "updateUser",
    "createAdmin",
    "deleteAll",
    "resetPassword",
    "changeRole",
];

/// Test for CSRF vulnerabilities in GraphQL endpoints.
///
/// Checks if the endpoint accepts GET requests, allows non-JSON
/// Content-Type headers, or lacks Origin/Referer validation.
///
/// # Arguments
///
/// * `client` - The HTTP client for making requests
/// * `url` - The target GraphQL endpoint URL
///
/// # Returns
///
/// Returns findings if CSRF vulnerabilities are detected.
///
/// # Errors
///
/// Returns an error if HTTP requests fail critically.
pub async fn test_with_context(client: &ScanClient, ctx: &ScanContext) -> Result<Vec<Finding>> {
    test(client, ctx.url()).await
}

/// Test for CSRF vulnerabilities.
pub async fn test(client: &ScanClient, url: &str) -> Result<Vec<Finding>> {
    let mut findings = Vec::new();

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

    // Test 1: GET-based query execution
    match test_get_request(client, url).await? {
        CsrfResult::Vulnerable(detail) => {
            findings.push(create_finding(
                url,
                "GraphQL GET-Based Query Execution",
                &format!(
                    "The GraphQL endpoint accepts queries via GET requests. \
                     Note: GET support for queries is GraphQL spec compliant. \
                     This is primarily a concern if mutations are also accepted via GET. {detail}"
                ),
                Severity::Low,
                "Reject GET requests for state-changing operations (mutations). \
                 If only queries are served over GET, ensure this is intentional.",
            )?);
        }
        CsrfResult::Safe => {
            trace!("GET requests properly rejected or return no data");
        }
        CsrfResult::Error(e) => {
            debug!("GET request test error: {}", e);
        }
    }

    // Test 2: Content-Type bypass
    match test_content_type_bypass(client, url).await? {
        CsrfResult::Vulnerable(detail) => {
            findings.push(create_finding(
                url,
                "GraphQL Content-Type Enforcement Missing",
                &format!(
                    "The GraphQL endpoint accepts requests with non-JSON Content-Type. {detail}"
                ),
                Severity::Medium,
                "Strictly enforce Content-Type: application/json on all GraphQL requests.",
            )?);
        }
        CsrfResult::Safe => {
            trace!("Content-Type properly enforced");
        }
        CsrfResult::Error(e) => {
            debug!("Content-Type test error: {}", e);
        }
    }

    // Test 3: Missing Origin validation
    match test_origin_validation(client, url).await? {
        CsrfResult::Vulnerable(detail) => {
            findings.push(create_finding(
                url,
                "GraphQL Origin/Referer Validation Missing",
                &format!(
                    "The GraphQL endpoint processes requests from arbitrary origins. {detail}"
                ),
                Severity::Medium,
                "Validate Origin and Referer headers. Reject requests from unexpected origins.",
            )?);
        }
        CsrfResult::Safe => {
            trace!("Origin/Referer validation present");
        }
        CsrfResult::Error(e) => {
            debug!("Origin validation test error: {}", e);
        }
    }

    // Test 4: CORS preflight misconfiguration
    match test_preflight(client, url).await? {
        CsrfResult::Vulnerable(detail) => {
            findings.push(create_finding(
                url,
                "GraphQL CORS Preflight Misconfiguration",
                &format!(
                    "The GraphQL endpoint's CORS preflight response allows arbitrary origins. {detail}"
                ),
                Severity::Medium,
                "Restrict Access-Control-Allow-Origin to trusted origins. Do not use '*' for authenticated endpoints.",
            )?);
        }
        CsrfResult::Safe => {
            trace!("CORS preflight properly configured");
        }
        CsrfResult::Error(e) => {
            debug!("Preflight test error: {}", e);
        }
    }

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

/// Outcome of a single CSRF probe.
///
/// Each variant maps to a concrete security condition observed during
/// the test, telling the scanner whether the endpoint accepted a
/// cross-origin or malformed request.
#[derive(Debug)]
pub enum CsrfResult {
    /// The endpoint accepted the cross-origin or malformed request.
    ///
    /// Returned when the server processes a GET query, a POST with an
    /// unexpected Content-Type, or a request from an arbitrary Origin.
    /// This indicates missing CSRF defenses and is reported as a finding.
    Vulnerable(String),
    /// The endpoint rejected the probe or did not expose the expected behavior.
    ///
    /// Returned when the server returns errors, empty data, or CORS
    /// blocks. This is the desired state for state-changing and
    /// sensitive operations.
    Safe,
    /// The probe could not complete due to a transport or parsing failure.
    ///
    /// Returned when the HTTP request fails or the response is
    /// unreadable. Errors are logged but not reported as findings to
    /// avoid false positives from transient failures.
    Error(String),
}

/// Probe whether the GraphQL endpoint executes queries submitted via GET.
///
/// GET-based query execution is a CSRF enabler because an attacker
/// can embed a malicious URL in an `<img>` tag or a link and trick a
/// victim's browser into executing it in the context of their
/// authenticated session. If mutations are also accepted via GET, the
/// impact is even higher.
///
/// Returns `CsrfResult::Vulnerable` when a GET request to
/// `url?query={__typename}` returns valid GraphQL data without
/// errors. Returns `Safe` when the request is rejected or returns
/// no data. Returns `Error` on network or parse failures.
pub async fn test_get_request(client: &ScanClient, url: &str) -> Result<CsrfResult> {
    let get_url = format!("{}?query={}", url, PROBE_QUERY.replace(' ', ""));

    let request = client.request(scanclient::reqwest::Method::GET, &get_url);

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

            if status.is_success() && body_text.contains("data") && body_text.contains("__typename")
            {
                return Ok(CsrfResult::Vulnerable(
                    "GET request returned valid GraphQL data.".to_string(),
                ));
            }

            if status.is_success()
                && !body_text.contains("error")
                && body_text.contains("__typename")
            {
                return Ok(CsrfResult::Vulnerable(
                    "GET request executed without error.".to_string(),
                ));
            }

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

/// Probe whether the endpoint accepts POST requests with non-JSON Content-Type headers.
///
/// Browsers can send cross-origin POSTs with `text/plain` or
/// `application/x-www-form-urlencoded` without a preflight check.
/// If the GraphQL server accepts these types, an attacker can forge
/// state-changing requests from a malicious page using a simple HTML
/// form.
///
/// Returns `CsrfResult::Vulnerable` when either Content-Type variant
/// is accepted and returns valid GraphQL data. Returns `Safe` when
/// both are rejected. Returns `Error` on network or parse failures.
pub async fn test_content_type_bypass(client: &ScanClient, url: &str) -> Result<CsrfResult> {
    let body = json!({ "query": PROBE_QUERY });
    let body_str = body.to_string();

    // Test with text/plain
    let request = client
        .request(scanclient::reqwest::Method::POST, url)
        .header(CONTENT_TYPE, "text/plain")
        .body(body_str.clone());

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

            if resp.status().is_success()
                && body_text.contains("data")
                && body_text.contains("__typename")
            {
                return Ok(CsrfResult::Vulnerable(
                    "Request with Content-Type: text/plain was accepted.".to_string(),
                ));
            }
        }
        Err(e) => {
            return Ok(CsrfResult::Error(e.to_string()));
        }
    }

    // Test with application/x-www-form-urlencoded
    let request = client
        .request(scanclient::reqwest::Method::POST, url)
        .header(CONTENT_TYPE, "application/x-www-form-urlencoded")
        .body(body_str);

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

            if resp.status().is_success()
                && body_text.contains("data")
                && body_text.contains("__typename")
            {
                return Ok(CsrfResult::Vulnerable(
                    "Request with Content-Type: application/x-www-form-urlencoded was accepted."
                        .to_string(),
                ));
            }

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

/// Probe whether the endpoint processes requests from an arbitrary Origin.
///
/// A well-hardened GraphQL API should reject or ignore requests that
/// originate from unexpected domains. If the server processes a
/// request carrying `Origin: https://example.com`, it may be
/// vulnerable to cross-site request forgery because any malicious
/// site can embed an equivalent request.
///
/// Returns `CsrfResult::Vulnerable` when the forged-origin request
/// receives a successful GraphQL response. Returns `Safe` when the
/// request is rejected or the response contains CORS/CSRF error
/// indicators. Returns `Error` on network or parse failures.
pub async fn test_origin_validation(client: &ScanClient, url: &str) -> Result<CsrfResult> {
    let body = json!({ "query": PROBE_QUERY });
    let request = client
        .request(scanclient::reqwest::Method::POST, url)
        .header(CONTENT_TYPE, "application/json")
        .header(ORIGIN, "https://example.com")
        .header(REFERER, "https://example.com/page.html")
        .body(body.to_string());

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

            if resp.status().is_success()
                && body_text.contains("data")
                && body_text.contains("__typename")
            {
                return Ok(CsrfResult::Vulnerable(
                    "Request with malicious Origin/Referer headers was processed.".to_string(),
                ));
            }

            // Check if rejected specifically for origin (CORS or CSRF block)
            if resp.status().as_u16() == 403
                || body_text.contains("origin")
                || body_text.contains("cors")
                || body_text.contains("csrf")
            {
                return Ok(CsrfResult::Safe);
            }

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

/// Probe the CORS preflight response for dangerous wildcard configurations.
///
/// An `OPTIONS` preflight that returns `Access-Control-Allow-Origin: *`
/// for an authenticated endpoint removes the browser's same-origin
/// protection and allows any website to make cross-origin requests
/// with the victim's credentials.
///
/// Returns `CsrfResult::Vulnerable` only when a wildcard origin is
/// explicitly returned. Origin echoing (common for CDNs) is
/// deliberately not flagged to reduce false positives. Returns
/// `Safe` when no wildcard is present or the preflight fails.
/// Returns `Error` on network or parse failures.
pub async fn test_preflight(client: &ScanClient, url: &str) -> Result<CsrfResult> {
    let request = client.request(scanclient::reqwest::Method::OPTIONS, url);
    match client.execute(request).await {
        Ok(resp) => {
            if resp.status().is_success() {
                if let Some(origin) = resp.header_value("Access-Control-Allow-Origin") {
                    if origin == "*" {
                        return Ok(CsrfResult::Vulnerable(
                            "CORS preflight allows all origins (wildcard).".to_string(),
                        ));
                    }
                    // Do NOT flag simply because the server echoes the Origin header
                    // - many CDNs and public APIs do this legitimately.
                }
            }
            Ok(CsrfResult::Safe)
        }
        Err(e) => Ok(CsrfResult::Error(e.to_string())),
    }
}

/// Build a standardized `Finding` for a detected CSRF weakness.
///
/// The finding is tagged with `graphql` and `csrf` so that downstream
/// reporting and dashboards can filter and group results. It is mapped
/// to `CWE-352` (Cross-Site Request Forgery) for compliance alignment.
///
/// `severity` is passed through from the caller because CSRF impact
/// varies: GET-based query support is typically `Low`, while missing
/// Content-Type enforcement or CORS misconfiguration can be `Medium`.
/// The `gqlprobe` scanner ID and target `url` anchor the finding to
/// the endpoint under test.
pub fn create_finding(
    url: &str,
    title: &str,
    detail: &str,
    severity: Severity,
    remediation: &str,
) -> Result<Finding> {
    Ok(Finding::builder("gqlprobe", url, severity)
        .title(title)
        .detail(detail)
        .kind(FindingKind::Vulnerability)
        .tag("graphql")
        .tag("csrf")
        .cwe("CWE-352") // Cross-Site Request Forgery (CSRF)
        .remediation(remediation)
        .build()?)
}