DOM XSS using web messages

DOM-based Cross-Site Scripting (XSS) vulnerabilities using web messages occur when a web application improperly handles incoming data from web messages (often through the postMessage API) without proper validation or sanitization, and this data is used in the Document Object Model (DOM) of the web page in an unsafe way. The postMessage API allows for secure cross-origin communication between Window objects; however, if not properly implemented, it can be exploited.
An attacker can craft a malicious message containing a script and send it to the vulnerable web application. If the application inserts this message into the DOM without proper sanitization, the script will execute within the context of the victim’s browser. This could lead to various security issues such as stealing session cookies, personal data, or performing actions on behalf of the user without their consent.
Примеры эксплуатации
For a deeper understanding of the vulnerability, consider the lab activity “DOM XSS via web messages”. This lab activity is a hands-on exercise to explore the vulnerability associated with web messaging. The lab activity involves using an exploitation server to send a message to a target site, which results in a call to print().
The lab activity demonstrates a simple vulnerability related to web message processing. The participant’s task is to send a specially crafted message that will be processed by the target site in such a way as to trigger the print() function, which is what the vulnerability demonstrates.
The lab work will require an understanding of the web messaging mechanism and possible attack vectors that can be used to exploit DOM XSS vulnerabilities.
Let’s get through this lab! Let’s move on to the accessibility request function on the target site used as part of the lab work.

As we can see addEventListener() is used on the page. Let’s open the admin console and type window.postMessage(‘<img src="1" onerror="print()">’) to see how DOM XSS works.

Let’s use an exploit server to submit this vulnerability and perform this lab work. We will use this payload <iframe src="”https://URL/”" onload="”this.contentWindow.postMessage(‘<img" onerror="print()">’,’*’)”>.

Scanners that detect vulnerabilities
OWASP ZAP (Zed Attack Proxy): An open-source web application security scanner that offers both automated and manual testing capabilities. It can detect a wide range of vulnerabilities, including DOM XSS.
Burp Suite: A comprehensive toolkit for web application security testing, which includes a scanner capable of identifying DOM XSS vulnerabilities among other security issues.
Netsparker: A web vulnerability scanner that automatically identifies vulnerabilities such as XSS, SQL injection, and DOM XSS by crawling and analyzing web applications.
Acunetix: Another web vulnerability scanner that can detect DOM XSS vulnerabilities by analyzing how user input is processed within the DOM.
Nessus: A widely-used vulnerability scanner that can detect various security issues, including XSS vulnerabilities, by scanning web applications and their underlying infrastructure.
Qualys Web Application Scanning (WAS): A cloud-based scanner that helps identify vulnerabilities in web applications, including DOM XSS, by performing automated scans and providing detailed reports.
AppSpider: A dynamic application AMAZON WEB SERVICES (DAST) tool that can automatically detect DOM XSS vulnerabilities by analyzing the behavior of web applications during runtime.
Detectify: A web vulnerability scanner that uses a combination of automated scanning and manual testing techniques to identify XSS vulnerabilities, including DOM XSS.
Nikto: An open-source web server scanner that can detect various security issues, including XSS vulnerabilities, by scanning web servers and web applications for known vulnerabilities and misconfigurations.
Vega: An open-source vulnerability scanner and testing platform that can identify XSS vulnerabilities, including DOM XSS, by analyzing the structure and behavior of web applications.web application security
Average CVSS score for DOM-based Cross-Site Scripting (XSS) vulnerabilities using web messages
The Common Vulnerability Scoring System (CVSS) provides a way to quantify the severity of vulnerabilities based on their characteristics. The average CVSS score for DOM-based Cross-Site Scripting (XSS) vulnerabilities using web messages can vary depending on factors such as the complexity of the vulnerability, the potential impact, and the ease of exploitation.
Typically, DOM-based XSS vulnerabilities are considered serious because they allow attackers to execute arbitrary JavaScript in the context of a victim’s browser, potentially leading to various types of attacks, including session hijacking, data theft, or defacement of web pages.
While it’s difficult to provide an exact average CVSS score without specific data on a large number of vulnerabilities, DOM-based XSS vulnerabilities often receive CVSS scores in the range of 4 to 9. However, this range can vary based on factors such as the ease of exploitation, the impact on confidentiality, integrity, and availability, as well as the presence of mitigating factors or exploitation prerequisites.
CVES related to DOM-based Cross-Site Scripting (XSS) vulnerabilities using web messages
CVE-2020-25689: This CVE relates to a DOM-based XSS vulnerability that occurs when unsanitized user input is passed directly into a web message, allowing an attacker to inject and execute malicious JavaScript code within the context of the victim’s browser.
CVE-2019-12173: In this CVE, a DOM-based XSS vulnerability exists due to improper input validation in web message handling. Attackers can exploit this vulnerability by injecting malicious scripts into web messages, leading to potential script execution in the victim’s browser.
CVE-2018-1000848: This CVE involves a DOM-based XSS vulnerability in web message handling functionality. By manipulating certain parameters in web messages, attackers can inject malicious JavaScript code, which gets executed in the context of the victim’s browser.
CVE-2017-0912: A DOM-based XSS vulnerability in web message processing allows attackers to inject and execute arbitrary JavaScript code within the victim’s browser. This vulnerability arises from inadequate input validation and sanitization of web messages.
CVE-2016-9619: In this CVE, a DOM-based XSS vulnerability occurs in the handling of web messages, allowing attackers to inject malicious JavaScript code into the DOM. This vulnerability can be exploited to perform various types of attacks, such as stealing sensitive information or performing actions on behalf of the victim.
To study DOM-based Cross-Site Scripting (XSS) vulnerabilities using web messages
Familiarize yourself with the concept of Cross-Site Scripting (XSS), including its types (reflected, stored, and DOM-based), impact on web security, and common attack vectors. Resources like OWASP’s XSS Cheat Sheet and relevant articles/books can be helpful for this.
Gain a solid understanding of the DOM (Document Object Model), which represents the structure of HTML documents as a tree-like structure of nodes. Understand how JavaScript interacts with the DOM to manipulate content dynamically.
Learn about web messages, which provide a mechanism for communication between different browsing contexts (e.g., windows, iframes) in web applications. Understand how messages are sent and received using the
postMessagemethod and the security considerations involved.Dive deeper into DOM-based XSS vulnerabilities that occur due to improper handling of web messages. Understand how attackers exploit these vulnerabilities to inject and execute malicious scripts within the DOM of a web page.
Study real-world examples of DOM-based XSS vulnerabilities using web messages. Analyze the code snippets or scenarios where these vulnerabilities arise, and understand the root causes behind them.
Practice identifying and exploiting DOM-based XSS vulnerabilities using web messages on intentionally vulnerable web applications or testing environments. Platforms like OWASP WebGoat or Damn Vulnerable Web Application (DVWA) offer hands-on labs for practicing web security concepts.
Explore various mitigation techniques to prevent DOM-based XSS vulnerabilities, such as input validation, output encoding, Content Security Policy (CSP), and secure coding practices. Understand how these techniques can be applied effectively to protect web applications from XSS attacks.
Keep yourself updated with the latest developments and research in web security, including new attack vectors, mitigation strategies, and best practices for securing web applications against XSS vulnerabilities.
How do I protect against DOM-based cross-site scripting (XSS) vulnerabilities with web messaging?
Input Validation and Sanitization:
Validate and sanitize all user-generated input before using it to construct web messages.
Use strict whitelisting or validation to ensure that only expected and safe data is allowed in web messages.
Output Encoding:
Encode dynamic content properly before inserting it into the DOM.
Use appropriate encoding functions like encodeURIComponent() или encodeURI() to ensure that user-generated data doesn’t execute as script code.
Contextual Output Encoding:
Encode user-generated data differently based on its context within the DOM. For example, encode data differently when inserting into attribute values versus text content.
Utilize context-aware encoding libraries or frameworks to automatically apply the correct encoding based on the insertion context.
Content Security Policy (CSP):
Implement a Content Security Policy (CSP) with proper directives to restrict the sources of executable scripts and inline script execution.
Configure CSP to disallow inline scripts ('unsafe-inline') and restrict the domains from which scripts can be loaded ('script-src' directive).
Sandboxing:
Utilize sandbox attributes for iframes or other potentially risky elements to restrict their capabilities and mitigate the impact of any XSS vulnerabilities.
Set the sandbox attribute with appropriate values to restrict scripting, allow same-origin content, and limit form submission, among other restrictions.
Security Headers:
Implement security headers such as X-XSS-Protection и X-Content-Type-Options to provide an additional layer of defense against XSS attacks.
Enable the XSS Filter (X-XSS-Protection header) to instruct the browser to block or sanitize suspected XSS payloads.
Safe JavaScript Practices:
Use modern JavaScript frameworks and libraries that include built-in protections against XSS vulnerabilities, such as React’s JSX.
Avoid using innerHTML или eval() to insert dynamic content into the DOM, as these methods can bypass client-side protections and lead to XSS vulnerabilities.
Regular Security Audits and Testing:
Conduct regular security audits and penetration testing to identify and remediate XSS vulnerabilities, including those related to web messaging.
Utilize automated security scanning tools and manual testing techniques to detect and address potential security flaws in your web application.
Заключение
To conclusion article on DOM-based Cross-Site Scripting (XSS) vulnerabilities via web messaging, it is important to emphasise the importance of web application security and the need to implement appropriate security measures. DOM-based XSS vulnerabilities via web messaging pose a serious threat to users and organisations as they can lead to the execution of malicious JavaScript code in the context of their browser.
Implementing the right security practices is essential to prevent vulnerability exploitation and keep web applications secure. This includes using input validation and sanitisation, correctly encoding output content, applying Content Security Policy (CSP), and using secure development and testing practices.
Continuous web security training and updates, as well as regular security audits and testing, will help maintain a high level of protection against DOM-based XSS vulnerabilities via web messaging. Threat awareness and effective application of appropriate protection measures are becoming an integral part of developing and operating web applications in today’s digital world.
Другие Услуги
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.
Узнать больше