How Static Analysis Uncovered a Hidden Reflected XSS

Background — Code-Level Blind Spots in Response Rendering
During a static code analysis of a backend module used for exchange emulation, our tooling identified a Reflected Cross-Site Scripting (XSS) vulnerability. The issue stemmed from unescaped output being written directly into the HTTP response body without sanitization.
While reflected XSS is traditionally identified through dynamic testing, its root causes—improper handling of user input and unsafe rendering functions—are best addressed at the source level. This finding highlights a gap in developer hygiene and reinforces the importance of secure-by-design coding practices.
Discovery — SAST Detection of Unsafe Output Sinks
The vulnerability was located in an emulator component used for mimicking exchange behaviors. The following file and line numbers were flagged:
Location:/internal/api/emulator/response/handler.go: 406, 474, 493, 557, 657, 705, 762, 782, 892
The pattern identified across multiple code paths was the use of http.ResponseWriter.Write() to send data back to the client, without passing it through a templating engine or performing HTML escaping.
_, err = w.Write(resp)
...
_, err = w.Write(resp2)
Technical Root Cause — Unsafe Output Function
Static analysis confirmed that resp и resp2 could contain user-controlled or derived input.
The core issue lies in the direct use of w.Write() for rendering data in an HTTP response. This function performs no automatic HTML escaping, making it dangerous when the content includes any portion of user input.
By failing to validate or encode the output, the code becomes vulnerable to a classic reflected XSS attack. An attacker may craft a URL with malicious parameters that reflect into the response, executing arbitrary scripts in the browser.
Exploitation Path — From Input to Execution
The attack vector would follow this pattern:
Attacker crafts URL with a malicious payload in a query or POST parameter.
Backend reflects input into the HTTP response using
w.Write().Browser executes payload, assuming it’s part of legitimate content.
Impact includes:
Theft of session tokens or authentication data.
Redirection to malicious websites.
UI redressing or phishing overlays.
Though identified in a staging emulator component, such code often shares logic with production systems or may accidentally get promoted in CI/CD workflows.
Broader Lessons — Avoiding Dangerous Output Functions
This vulnerability underscores a recurring issue in Go and other backend languages: developers using low-level output functions without output encoding. Key takeaways:
Treat all output sinks (
Write(),fmt.Fprintf(), etc.) as tainted unless wrapped in a safe context.Never assume staging code is immune to security requirements.
Use static analysis early in the development lifecycle to detect dangerous patterns before deployment.
Recommendations — Fixing the Root Cause
Use Safe Templating:
Replace w.Write() calls with HTML-escaping template rendering, e.g.:
tmpl := template.Must(template.New("safe").Parse(html))
tmpl.Execute(w, data)
Enforce Output Encoding:
Use central wrappers for rendering responses that guarantee output is encoded.
SAST Rule Enforcement:
Configure static analysis tooling to flag:
Use of
w.Write()in web handlers.Unsafe string concatenation in HTTP responses.
Missing use of
html/template.
Treat All Environments Equally:
Enforce the same security standards in dev/staging as in production to prevent insecure logic from propagating.
Conclusion — Prevention Starts in the Codebase
This finding shows how seemingly harmless patterns in the codebase can introduce real-world risk. Reflected XSS remains a valid concern even in backend services, particularly when developers rely on manual response rendering. SAST proves its value by identifying vulnerabilities long before they reach a browser.
Серьезность: Высокий
CVE Reference: Internal finding (not publicly assigned)
CVSS Score: 7.5 (CVSS:3.1/AV:L/AC:H/PR:L/UI:N/S:C/C:H/I:H/A:N)
Affected Module: Emulator Response Handler
Exploit Technique: Reflected XSS via Unsafe Output
Exploit Path: Direct input reflection via http.ResponseWriter.Write()
Environment: Staging (with potential for promotion)
Другие Услуги
Insomnia Security Scanner
AI-powered web application security scanner by CQR. Automated vulnerability discovery, exploit verification, and detailed reporting for modern applications.
Узнать большеЗащита Инфраструктуры CRYEYE
Аудит безопасности с помощью CryEye обеспечивает информационную безопасность предприятия, защищая всю инфраструктуру.
Узнать большеТестирование на проникновение
Найдите уязвимости во всей инфраструктуре вашего бизнеса раньше, чем это сделают хакеры! В рамках консалтинга по тестированию на проникновение мы подберем методы пентестов.
Узнать большеСоциальная инженерия
Simulate real-world phishing, vishing, and pretexting attacks to measure and improve your team's security awareness and response capabilities.
Узнать большеНагрузочное Тестирование
All kinds of load and performance testing of your system from the CQR online security company.
Узнать большеAI-Powered Vulnerability Assessment
Leverage artificial intelligence to discover, prioritize, and remediate vulnerabilities across your digital assets faster and more accurately than traditional scanners.
Узнать большеCloud Security Audit (AWS / GCP / Azure)
Comprehensive security review of your cloud environments — IAM policies, network controls, data exposure, and misconfigurations across all major cloud platforms.
Узнать большеDevSecOps Integration
Embed security into every stage of your CI/CD pipeline. Automated SAST, DAST, SCA, and secret scanning so vulnerabilities are caught before they reach production.
Узнать большеAPI Security Testing
In-depth testing of REST, GraphQL, and SOAP APIs for authentication flaws, authorization bypasses, injection vulnerabilities, and data leakage risks.
Узнать большеMobile Application Penetration Testing
Manual and automated security testing for iOS and Android applications — reverse engineering, runtime analysis, traffic interception, and backend API assessment.
Узнать большеIoT Security Assessment
Evaluate firmware, communication protocols, cloud backends, and physical interfaces of IoT devices to identify vulnerabilities before attackers do.
Узнать большеBlockchain & Smart Contract Audit
Formal verification and manual code review of smart contracts on Ethereum, Solana, and other chains. Detect reentrancy, overflow, and logic flaws before deployment.
Узнать большеRed Team Operations
Advanced adversary simulation using real attacker TTPs (MITRE ATT&CK) to test your detection, response, and overall security posture under realistic conditions.
Узнать большеThreat Intelligence & Monitoring
Continuous monitoring of threat feeds, dark web, and attacker infrastructure to provide actionable intelligence specific to your organization and industry.
Узнать большеZero Trust Architecture Review
Assess and design your Zero Trust security model — identity verification, micro-segmentation, least-privilege access, and continuous validation controls.
Узнать большеCompliance Consulting (PCI DSS / SOC 2 / GDPR)
Expert guidance to achieve and maintain compliance with major security frameworks. Gap analysis, remediation roadmaps, and audit-readiness support.
Узнать большеDark Web Monitoring
Continuous surveillance of dark web forums, marketplaces, and breach databases for leaked credentials, sensitive data, or mentions of your organization.
Узнать большеPhishing Simulation & Awareness Training
Controlled phishing campaigns combined with interactive security awareness training to build a human firewall across your entire organization.
Узнать большеSupply Chain Security Audit
Assess third-party vendor risks, open-source dependencies, and software supply chain integrity to prevent attacks like SolarWinds and Log4Shell.
Узнать большеContainer & Kubernetes Security
Security review of Docker images, Kubernetes clusters, RBAC policies, network policies, and runtime configurations to harden your container infrastructure.
Узнать большеWeb Application Firewall (WAF) Deployment
Professional WAF setup, rule tuning, and ongoing management to block SQL injection, XSS, CSRF, and other OWASP Top 10 threats in real time.
Узнать большеBug Bounty Program Management
Full lifecycle management of your bug bounty program — scope definition, researcher coordination, triage, validation, and remediation tracking.
Узнать большеOSINT Investigation Services
Open-source intelligence gathering on individuals, organizations, and infrastructure. Ideal for pre-engagement recon, fraud investigation, and competitive analysis.
Узнать большеDigital Forensics & Incident Response
Rapid response to security breaches — evidence collection, malware analysis, attacker timeline reconstruction, and actionable remediation recommendations.
Узнать больше