DOM XSS using web messages and a JavaScript URL

DOM XSS using Web Messages and a JavaScript URL:
Attack Description:
Web Messages (postMessage):
Feature Description: Web Messages, implemented through the postMessage method, allow communication between different windows or iframes within a browser, even if they originate from different origins.
Эксплуатация: An attacker can abuse this feature to send malicious messages to a vulnerable webpage, potentially leading to DOM XSS.
JavaScript URL:
Feature Description: A JavaScript URL is a URL that begins with the javascript: scheme followed by JavaScript code. When executed, it runs the embedded JavaScript code in the context of the current page.
Эксплуатация: An attacker can construct a JavaScript URL that contains malicious code and attempt to execute it within the target webpage.
Attack Steps:
Malicious Site Setup:
The attacker creates a malicious webpage containing a script with a JavaScript URL payload, designed to perform malicious actions.
Target Site with Web Messages:
The attacker identifies a target webpage that uses the postMessage method to communicate with iframes or windows.
Sending Malicious Web Message:
The attacker initiates a communication channel by embedding their malicious page within an iframe on the target site.
Exploiting the postMessage feature, the attacker sends a web message containing the JavaScript URL payload to the iframe on the target site.
Execution of JavaScript URL:
The JavaScript URL is executed within the context of the target site, potentially leading to DOM-based Cross-Site Scripting (XSS).
The injected script can manipulate the DOM, steal sensitive information, or perform other malicious actions within the target site.
Примеры эксплуатации
To better understand the DOM XSS using web messages and a JavaScript URL vulnerability, let’s take a look at one of the labs from PortSwigger, a well-known web security company. This lab demonstrates a DOM XSS using web messages and a JavaScript URL vulnerability.

Press “View Page Source” then, press Ctrl+F and type “message”

Then back to “Home” page, press “inspect (Q)” , go to console , type let url = “javascript:console.log(1)//http:” , url = “javascript:console.log(1)//http:” , url.indexOf(‘http:’
let url = "javascript:console.log(1)//http:"
undefined
url = "javascript:console.log(1)//http:"
'javascript:console.log(1)//http:'
url.indexOf("http:")
27
Then take the url from home page

Use this exploit and then we can see print() function is working

Scanners that detect vulnerabilities
Описание: A powerful web application AMAZON WEB SERVICES tool that includes features for scanning, crawling, and analyzing web applications.
OWASP Zed Attack Proxy (ZAP):
Описание: An open-source security testing tool designed to find vulnerabilities in web applications.
Описание: A deliberately insecure web application maintained by OWASP designed for learning and practicing application security testing.
DVWA (Damn Vulnerable Web Application):
Описание: A vulnerable web application used for practicing penetration testing skills.
BeEF (Browser Exploitation Framework):
Описание: A ПЕНТЕСТ tool focused on web browsers, allowing for testing against various client-side vulnerabilities.
Описание: A web-based tool to check the security headers of a given website, including Content Security Policy (CSP).
Описание: A JavaScript library that helps prevent DOM-based XSS attacks by sanitizing HTML and preventing the execution of malicious scripts.
Описание: A web application security scanner that can identify and report vulnerabilities in web applications, including DOM-based XSS.
Описание: A tool for tracking and capturing cross-site scripting (XSS) vulnerabilities in real-time.
Average CVSS score
Assigning a specific Common Vulnerability Scoring System (CVSS) score for “DOM XSS using web messages and a JavaScript URL” is challenging without specific details about a particular vulnerability. The CVSS score depends on various factors, including the impact, exploitability, and mitigating factors specific to each vulnerability.
CWE information
DOM XSS (CWE-79):
Описание: DOM XSS (Cross-Site Scripting) occurs when client-side scripts manipulate the Document Object Model (DOM) in an insecure way, allowing an attacker to inject and execute malicious scripts.
CWE Identifier: CWE-79 (Improper Neutralization of Input During Web Page Generation (‘Cross-site Scripting’))
Web Messages (CWE-1156):
Описание: Web Messages, implemented through the postMessage method, allow communication between different windows or iframes within a browser, even if they originate from different origins.
CWE Identifier: CWE-1156 (Origin Validation Error)
JavaScript URL (CWE-94):
Описание: JavaScript URLs are URLs that begin with the javascript: scheme followed by JavaScript code. When executed, it runs the embedded JavaScript code in the context of the current page.
CWE Identifier: CWE-94 (Improper Control of Generation of Code (‘Code Injection’))
Conclusion and Mitigation
DOM XSS using web messages and a JavaScript URL represents a critical security vulnerability that allows attackers to inject and execute malicious scripts within the Document Object Model (DOM) of a web application. By exploiting the communication between different windows or iframes through web messages and leveraging JavaScript URLs, attackers can potentially manipulate the content and behavior of a targeted webpage, leading to severe consequences such as data theft, unauthorized actions, or the compromise of sensitive information.
Mitigation Strategies:
Input Validation and Output Encoding:
Implement strict input validation to ensure that user inputs are sanitized and adhere to expected formats.
Apply output encoding to sanitize user inputs before displaying them in the browser, preventing the execution of injected scripts.
Политика безопасности контента (CSP):
Implement a robust Content Security Policy that restricts the sources from which scripts can be loaded. Disallow inline scripts and limit script sources to trusted domains.
Web Message Validation:
Validate web messages received using the postMessage method to ensure that they come from trusted sources and contain safe content. Validate the origin and structure of incoming messages.
Frame Ancestors Header (X-Frame-Options):
Set the X-Frame-Options header to DENY or SAMEORIGIN to control whether your web pages can be embedded in iframes. This helps mitigate the risk of exploitation.
Secure Cross-Origin Communication:
When using web messages for cross-origin communication, implement secure practices such as verifying the origin and ensuring that messages are only accepted from expected sources.
Регулярные аудиты безопасности:
Conduct regular аудиты безопасности, including penetration testing, to identify and address vulnerabilities in your web application. Pay specific attention to DOM XSS vulnerabilities associated with web messages and JavaScript URLs.
Security Awareness Training:
Educate developers about secure coding practices and the risks associated with DOM XSS. Ensure that the development team is aware of the specific challenges posed by web messages and JavaScript URLs.
Update and Patching:
Keep all software components, including web servers, frameworks, and libraries, up to date with the latest security patches to address known vulnerabilities.
Другие Услуги
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.
Узнать больше