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.
Дізнатися більшеТестування Продуктивності
Усі види тестування навантаження і продуктивності вашої системи від компанії CQR, що спеціалізується на онлайн-безпеці.
Дізнатися більше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.
Дізнатися більше