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;
pub const PROBE_QUERY: &str = "{ __typename }";
pub const SENSITIVE_MUTATIONS: &[&str] = &[
"deleteUser",
"updateUser",
"createAdmin",
"deleteAll",
"resetPassword",
"changeRole",
];
pub async fn test_with_context(client: &ScanClient, ctx: &ScanContext) -> Result<Vec<Finding>> {
test(client, ctx.url()).await
}
pub async fn test(client: &ScanClient, url: &str) -> Result<Vec<Finding>> {
let mut findings = Vec::new();
debug!("Testing CSRF on {}", url);
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);
}
}
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);
}
}
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);
}
}
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)
}
#[derive(Debug)]
pub enum CsrfResult {
Vulnerable(String),
Safe,
Error(String),
}
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())),
}
}
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();
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()));
}
}
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())),
}
}
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(),
));
}
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())),
}
}
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(),
));
}
}
}
Ok(CsrfResult::Safe)
}
Err(e) => Ok(CsrfResult::Error(e.to_string())),
}
}
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") .remediation(remediation)
.build()?)
}